diff --git "a/data/dataset_In_Silico.csv" "b/data/dataset_In_Silico.csv" new file mode 100644--- /dev/null +++ "b/data/dataset_In_Silico.csv" @@ -0,0 +1,56407 @@ +"keyword","repo_name","file_path","file_extension","file_size","line_count","content","language" +"In Silico","GGFHF/ddRADseqTools","CHANGELOG.md",".md","1482","43","CURRENT VERSION: 0.45 + +******************************************************************************** + +Changes of v 0.44 to v 0.45 (February 2018) + +* Review of parameter values when the mutation function is called in rsitesearch.py. + +* Processing of verbose and trace options of simcasavaids.py. + +******************************************************************************** + +Changes of v 0.43 to v 0.44 (January 2018) + +* Enzymes with ambiguous restriction sites can be used. + +* Parameters enzyme1 and enzyme2 can be equal in rsiteseach.py (in this case, + it simulates a digestion with only one enzyme). + +* simcasavaids.py is a new tool which fixes sequence identifiers of a FASTQ read + file generated by ddRADseqTools to compatible format with CASAVA. + +* Several minor improvements. + +******************************************************************************** + +Changes of v 0.42 to v 0.43 (October 2017) + +* Parameters enzyme1 and enzyme2 can be an identifier or a restriction site + sequence, independently of each other. + +******************************************************************************** + +Changes of v 0.40 to v 0.42 (July 2017) + +* Fixed a bug in the algorithm to mutate sequences that occurs when there is + more than one SNP or indel. + +* Added new options in the programs to control the printing of verbose and + development info, and the making of statistical graphics. + +We thank to the professor Alex Buerkle his comments to improve ddRADseqTools. +","Markdown" +"In Silico","GGFHF/ddRADseqTools","LICENSE.md",".md","35142","675"," 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. + + {one line to give the program's name and a brief idea of what it does.} + Copyright (C) {year} {name of author} + + 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: + + {project} Copyright (C) {year} {fullname} + 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 +. +","Markdown" +"In Silico","GGFHF/ddRADseqTools","Package/seqlocation.py",".py","9429","257","#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +#------------------------------------------------------------------------------- + +'''This software has been developed by: + + GI Genética, Fisiología e Historia Forestal + Dpto. Sistemas y Recursos Naturales + ETSI Montes, Forestal y del Medio Natural + Universidad Politécnica de Madrid + https://github.com/ggfhf/ + + Licence: GNU General Public Licence Version 3 +''' + +#------------------------------------------------------------------------------- + +'''This source contains the program of the ddRADseqTools software package that + locates a sequence into the genome. +''' +#------------------------------------------------------------------------------- + +import gzip +import re +import sys + +from genlib import * + +#------------------------------------------------------------------------------- + +def main(argv): + '''Main line of the program.''' + + # build the options dictionary + options_dict = build_options() + + # it has been requested the help or to build a new config file + for param in argv: + # show the help and exit OK + if param.startswith('--help'): + print_help(options_dict) + sys.exit(0) + # build the config file and exit OK + elif param.startswith('--config'): + build_config(options_dict) + sys.exit(0) + + # get the config file + config_file = get_config_file(__file__) + + # get options from the config file and the input parameters + options_dict = get_options(options_dict, config_file, argv) + + # locate sequence + locate_seq(options_dict) + +#------------------------------------------------------------------------------- + +def locate_seq(options_dict): + '''Locate a sequence into the genome.''' + + genfile = options_dict['genfile']['value'] + seq = options_dict['seq']['value'] + verbose = options_dict['verbose']['value'] + trace = options_dict['trace']['value'] + + # set the verbose and trace status + if verbose.upper() == 'YES': + Message.set_verbose_status(True) + else: + Message.set_verbose_status(False) + if trace.upper() == 'YES': + Message.set_trace_status(True) + else: + Message.set_trace_status(False) + + # ... + Message.print('info', 'seq to be locate: {0}'.format(seq)) + Message.print('info', 'reverse compl. : {0}'.format(get_reverse_complementary_sequence(seq))) + + # open the genome file + try: + if genfile.endswith('.gz'): + genfile_id = gzip.open(genfile, mode='rt', encoding='iso-8859-1') + else: + genfile_id = open(genfile, mode='r', encoding='iso-8859-1') + except: + raise ProgramError('F002', genfile) + + # set the pattern of the head records (>locus_info) + pattern = r'^>(.*)$' + + # initialize the found site count + found_site_count = 0 + + # read the first record + record = genfile_id.readline() + + # while there are records + while record != '': + + # process the head record + if record.startswith('>'): + + # extract the data + mo = re.search(pattern, record) + locus_info = mo.group(1) + + # initialize the locus sequence of Watson strand + watson_locus_seq = '' + + # read the next record + record = genfile_id.readline() + + else: + + # control the FASTA format + raise ProgramError('F003', genfile, 'FASTA') + + # while there are records and they are sequence + while record != '' and not record.startswith('>'): + + # concatenate the record to the locus sequence of Watson strand + watson_locus_seq += record.strip().upper() + + # read the next record + record = genfile_id.readline() + + # find the first location in Watson locus sequence + start = watson_locus_seq.find(seq.upper()) + + # while the sequence is found in the Watson strand + while start >= 0: + + # print the location data + Message.print('info', 'Locus info: {0} | strand: + | start position: {1} | end position: {2}'.format(locus_info, (start + 1), (start + len(seq)))) + + # add 1 to found site count + found_site_count += 1 + + # find the next location + start = watson_locus_seq.find(seq.upper(), (start + len(seq))) + + # get the sequence of the Crick strand + crick_locus_seq = get_reverse_complementary_sequence(watson_locus_seq) + + # find the first location in Crick locus sequence + start = crick_locus_seq.find(seq.upper()) + + # while the sequence is the Crick strand + while start >= 0: + + # print the loation data + Message.print('info', 'Locus info: {0} | strand: - | start position: {1} | end position: {2}'.format(locus_info, (len(crick_locus_seq) - start), (len(crick_locus_seq) - start - len(seq) + 1))) + + # add 1 to found site count + found_site_count += 1 + + # find the next location + start = crick_locus_seq.find(seq.upper(), (start + len(seq))) + + # close genfile + genfile_id.close() + + # show the found site count + if found_site_count == 0: + Message.print('info', 'The sequence is not found') + else: + Message.print('info', 'The sequence is found in {0} sites'.format(found_site_count)) + +#------------------------------------------------------------------------------- + +def build_options(): + '''Build a dictionary with the program options.''' + + # get all options dictionary + all_options_dict = get_all_options_dict() + + # define the options dictionary + options_dict = { + 'genfile': all_options_dict['genfile'], + 'seq': all_options_dict['seq'], + 'verbose': all_options_dict['verbose'], + 'trace': all_options_dict['trace'] + } + + # return the options dictionary + return options_dict + +#------------------------------------------------------------------------------- + +def print_help(options_dict): + '''Print the program help.''' + + # get general data + project_name = get_project_name() + project_version = get_project_version() + program_file = get_file_name(__file__) + config_file = get_config_file(__file__) + + # print the helpplot_graphic(intervals) + Message.print('info', '') + Message.print('info', '{0} version {1}'.format(project_name, project_version)) + Message.print('info', '') + Message.print('info', '{0} locates a sequence into the genome.'.format(program_file)) + Message.print('info', '') + Message.print('info', 'Usage: {0} --help'.format(program_file)) + Message.print('info', '') + Message.print('info', ' Show the help of {0}.'.format(program_file)) + Message.print('info', '') + Message.print('info', ' or: {0} --config'.format(program_file)) + Message.print('info', '') + Message.print('info', ' Create the config file {0} with the default value of the options.'.format(config_file)) + Message.print('info', ' The default value of the options can be modified.'.format(config_file)) + Message.print('info', '') + Message.print('info', ' or: {0} [--option= [--option=, ...]]'.format(program_file)) + Message.print('info', '') + Message.print('info', ' The options values are read from the config file {0}, but they can be modified'.format(config_file)) + Message.print('info', ' in command line. The options are:') + Message.print('info', '') + Message.print('info', ' {0:9} {1}'.format('option', 'value')) + Message.print('info', ' {0:9} {1}'.format('=' * 9, '=' * 44)) + Message.print('info', ' {0:9} {1}'.format('--genfile', options_dict['genfile']['comment'])) + Message.print('info', ' {0:9} {1}'.format('--seq', options_dict['seq']['comment'])) + Message.print('info', ' {0:9} {1}'.format('--verbose', options_dict['verbose']['comment'])) + Message.print('info', ' {0:9} {1}'.format('--trace', options_dict['trace']['comment'])) + +#------------------------------------------------------------------------------- + +def build_config(options_dict): + '''Build the file with the options by default.''' + + # get the config file + config_file = get_config_file(__file__) + + # create the config file and write the default options + try: + with open(config_file, mode='w', encoding='iso-8859-1') as config_file_id: + config_file_id.write('{0:33} # {1}\n'.format('genfile' + '=' + options_dict['genfile']['default'], options_dict['genfile']['comment'])) + config_file_id.write('{0:33} # {1}\n'.format('seq' + '=' + options_dict['seq']['default'], options_dict['seq']['comment'])) + config_file_id.write('{0:33} # {1}\n'.format('verbose' + '=' + options_dict['verbose']['default'], options_dict['verbose']['comment'])) + config_file_id.write('{0:33} # {1}\n'.format('trace' + '=' + options_dict['trace']['default'], options_dict['trace']['comment'])) + except: + raise ProgramError('F001', config_file) + + # show OK message + Message.print('info', 'The configuration file {0} is created.'.format(get_file_name(config_file))) + +#------------------------------------------------------------------------------- + +if __name__ == '__main__': + main(sys.argv[1:]) + sys.exit(0) + +#------------------------------------------------------------------------------- +","Python" +"In Silico","GGFHF/ddRADseqTools","Package/pcrdupremoval.py",".py","36786","914","#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +#------------------------------------------------------------------------------- + +'''This software has been developed by: + + GI Genética, Fisiología e Historia Forestal + Dpto. Sistemas y Recursos Naturales + ETSI Montes, Forestal y del Medio Natural + Universidad Politécnica de Madrid + https://github.com/ggfhf/ + + Licence: GNU General Public Licence Version 3 +''' + +#------------------------------------------------------------------------------- + +'''This source contains the program of the ddRADseqTools software package that + quantifies the PCR duplicates and removes them from a file(s) in FASTQ/FASTA + format with sequences of a double digest RADseq. +''' +#------------------------------------------------------------------------------- + +import os.path +import re +import subprocess +import sys + +from genlib import * + +#------------------------------------------------------------------------------- + +def main(argv): + '''Main line of the program.''' + + # build the options dictionary + options_dict = build_options() + + # it has been requested the help or to build a new config file + for param in argv: + # show the help and exit OK + if param.startswith('--help'): + print_help(options_dict) + sys.exit(0) + # build the config file and exit OK + elif param.startswith('--config'): + build_config(options_dict) + sys.exit(0) + + # get the config file + config_file = get_config_file(__file__) + + # get options from the config file and the input parameters + options_dict = get_options(options_dict, config_file, argv) + + # process PCR duplicates of a double digest RADseq + process_pcr_duplicates(options_dict) + +#------------------------------------------------------------------------------- + +def process_pcr_duplicates(options_dict): + '''Process PCR duplicates of a double digest RADseq.''' + + format = options_dict['format']['value'] + readtype = options_dict['readtype']['value'] + readsfile1 = options_dict['readsfile1']['value'] + readsfile2 = options_dict['readsfile2']['value'] + clearfile = options_dict['clearfile']['value'] + dupstfile = options_dict['dupstfile']['value'] + plot = options_dict['plot']['value'] + verbose = options_dict['verbose']['value'] + trace = options_dict['trace']['value'] + + # set the verbose and trace status + if verbose.upper() == 'YES': + Message.set_verbose_status(True) + else: + Message.set_verbose_status(False) + if trace.upper() == 'YES': + Message.set_trace_status(True) + else: + Message.set_trace_status(False) + + # initialize the statistics + stats_dict = {} + + # asign the temporal file name with records unified by read + unified_reads_file = readsfile1 + '.unified' + + # build temporal file unifing records by read + unify_records(format, readtype, readsfile1, readsfile2, unified_reads_file) + + # asign the temporal file name with sorted records unified by read + sorted_reads_file = unified_reads_file + '.sorted' + + # sort the temporal file with records unified by read + sort_records(unified_reads_file, sorted_reads_file) + + # delete temporal file with records unified by read + os.remove(unified_reads_file) + Message.print('info', 'The temporal file {0} is deleted.'.format(get_file_name(unified_reads_file))) + + # asign the purged temporal file(s) name + purged_reads_file = sorted_reads_file + '.purged' + + # quantify and remove the PCR duplicates + stats_dict = purge_records(format, readtype, sorted_reads_file, purged_reads_file) + + # delete temporal file with sorted records unified by read + os.remove(sorted_reads_file) + Message.print('info', 'The temporal file {0} is deleted.'.format(get_file_name(sorted_reads_file))) + + # assign the output file(s) name + extention = '.fastq' if format == 'FASTQ' else '.fasta' + if readtype == 'SE': + clearfile1 = clearfile + extention + clearfile2 = None + elif readtype == 'PE': + clearfile1 = clearfile + '-1' + extention + clearfile2 = clearfile + '-2' + extention + + # restore the original file(s) format + restore_format(format, readtype, purged_reads_file, clearfile1, clearfile2) + + # delete temporal file without PCR duplicates + os.remove(purged_reads_file) + Message.print('info', 'The temporal file {0} is deleted.'.format(get_file_name(purged_reads_file))) + + # write the PCR duplicates statistics + write_pcrdup_stats(dupstfile, stats_dict) + + # plot the PCR duplicates graphics + if plot.upper() == 'YES': + plot_pcrdup_graphics(dupstfile, stats_dict) + + # plot the graphic of the individuals without data per locus + if plot.upper() == 'YES': + plot_individuals_withoutdata_graphic(dupstfile, stats_dict) + + # plot the graphic of the loci without data per individual + if plot.upper() == 'YES': + plot_loci_withoutdata_graphic(dupstfile, stats_dict) + +#------------------------------------------------------------------------------- + +def unify_records(format, readtype, readsfile1, readsfile2, unified_reads_file): + '''Build file(s) unifing records by read.''' + + # open the reads file(s) + try: + readsfile1_id = open(readsfile1, mode='r', encoding='iso-8859-1') + except: + raise ProgramError('F002', readsfile1) + if readtype == 'PE': + try: + readsfile2_id = open(readsfile2, mode='r', encoding='iso-8859-1') + except: + raise ProgramError('F002', readsfile2) + + # open the file unifing records by read + try: + unified_reads_file_id = open(unified_reads_file, mode='w', encoding='iso-8859-1') + except: + raise ProgramError('F002', unified_reads_file) + + # initialize the count of reads + reads_count = 0 + + # if the format is FASTA + if format == 'FASTA': + + # set the pattern of the head records (>read_info) + pattern = r'^>(.*)$' + + # if readtype is SE + if readtype == 'SE': + + # read the first record of readsfile(s) + record1 = readsfile1_id.readline() + + # while there are records in readsfile1 + while record1 != '': + + # process the head record + if record1.startswith('>'): + + # extract the data + mo = re.search(pattern, record1) + info1 = mo.group(1).strip() + + # initialize the sequence + seq1 = '' + + # read the next record of readsfile1 + record1 = readsfile1_id.readline() + + else: + + # control the FASTA format + raise ProgramError('F003', readsfile1, 'FASTA') + + # while there are records in readsfile1 and they are sequence + while record1 != '' and not record1.startswith('>'): + + # add the record to the sequence + seq1 += record1.strip() + + # read the next record of readsfile1 + record1 = readsfile1_id.readline() + + # write record in unifile + unified_reads_file_id.write('{0}|||{1}\n'.format(seq1, info1)) + + # notify the reads have been processed + reads_count += 1 + Message.print('verbose', '\rProcessed reads: {0:9d}'.format(reads_count)) + + # if the readtype is PE + elif readtype == 'PE': + + # read the first record of readsfile1 and readfile2 + record1 = readsfile1_id.readline() + record2 = readsfile2_id.readline() + + # while there are records in readsfile1 and readsfile2 + while record1 != '' and record2 != '': + + # process the head record of readsfile1 + if record1.startswith('>'): + + # extract the data + mo = re.search(pattern, record1) + info1 = mo.group(1).strip() + + # initialize the sequence of readsfile1 + seq1 = '' + + # read the next record of readsfile1 + record1 = readsfile1_id.readline() + + else: + + # control the FASTA format + raise ProgramError('F003', readsfile1, 'FASTA') + + # while there are records in readsfile1 and they are sequence + while record1 != '' and not record1.startswith('>'): + + # add the record to the sequence + seq1 += record1.strip() + + # read the next record of readsfile1 + record1 = readsfile1_id.readline() + + # process the head record of readsfile2 + if record2.startswith('>'): + + # extract the data + mo = re.search(pattern, record2) + info2 = mo.group(1).strip() + + # initialize the sequence of readsfile2 + seq2 = '' + + # read the next record of readsfile2 + record2 = readsfile2_id.readline() + + else: + + # control the FASTA forma + raise ProgramError('F003', readsfile2, 'FASTA') + + # while there are records in readsfile2 and they are sequence + while record2 != '' and not record2.startswith('>'): + + # add the record to the sequence + seq2 += record2.strip() + + # read the next record of readsfile2 + record2 = readsfile2_id.readline() + + # write record in unifile + unified_reads_file_id.write('{0}|||{1}|||{2}|||{3}\n'.format(seq1, seq2, info1, info2)) + + # notify the reads have been processed + reads_count += 1 + Message.print('verbose', '\rProcessed reads: {0:9d}'.format(reads_count)) + + # control there are not records in readsfile1 and readsfile2 + if record1 != '' or record2 != '': + raise ProgramError('L003', readsfile1, readsfile2) + + # if the format is FASTQ + elif format == 'FASTQ': + + # set the pattern of the head records (@read_info) + pattern = r'^@(.*)$' + + # if the readtype is SE + if readtype == 'SE': + + # read the first record of readsfile1 + record1 = readsfile1_id.readline() + + # while there are records in readsfile1 + while record1 != '': + + # process the head record of readsfile1 + if record1.startswith('@'): + # extract the data + mo = re.search(pattern, record1) + info1 = mo.group(1).strip() + else: + # control the FASTQ format + raise ProgramError('F003', readsfile1, 'FASTQ') + + # read and verify record of sequence of readsfile1 + record1 = readsfile1_id.readline() + if record1 == '': + # control the FASTQ format + raise ProgramError('F003', readsfile1, 'FASTQ') + + # assign the sequence + seq1 = record1.strip() + + # read and verify record of plus of readsfile1 + record1 = readsfile1_id.readline() + if not record1.startswith('+'): + # control the FASTQ format + raise ProgramError('F003', readsfile1, 'FASTQ') + + # read and verify record of quality of readsfile1 + record1 = readsfile1_id.readline() + if record1 == '': + # control the FASTQ format + raise ProgramError('F003', readsfile1, 'FASTQ') + + # assign the quality + quality1 = record1.strip() + + # write record in unifile + unified_reads_file_id.write('{0}|||{1}|||{2}\n'.format(seq1, info1, quality1)) + + # notify the reads have been processed + reads_count += 1 + Message.print('verbose', '\rProcessed reads: {0:9d}'.format(reads_count)) + + # read the next record of readsfile1 + record1 = readsfile1_id.readline() + + # if the readtype is PE + elif readtype == 'PE': + + # read the first record of readsfile1 and readsfie2 + record1 = readsfile1_id.readline() + record2 = readsfile2_id.readline() + + # while there are records in readsfile1 and readsfile2 + while record1 != '' and record2 != '': + + # process the head record of readsfile1 + if record1.startswith('@'): + # extract the data + mo = re.search(pattern, record1) + info1 = mo.group(1).strip() + else: + # control the FASTQ format + raise ProgramError('F003', readsfile1, 'FASTQ') + + # read and verify record of sequence + record1 = readsfile1_id.readline() + if record1 == '': + # control the FASTQ format + raise ProgramError('F003', readsfile1, 'FASTQ') + + # assign the sequence + seq1 = record1.strip() + + # read and verify record of plus + record1 = readsfile1_id.readline() + if not record1.startswith('+'): + # control the FASTQ format + raise ProgramError('F003', readsfile1, 'FASTQ') + + # read and verify record of quality + record1 = readsfile1_id.readline() + if record1 == '': + # control the FASTQ format + raise ProgramError('F003', readsfile1, 'FASTQ') + + # assign the quality + quality1 = record1.strip() + + # process the head record of readsfile2 + if record2.startswith('@'): + # extract the data + mo = re.search(pattern, record2) + info2 = mo.group(1).strip() + else: + # control the FASTQ format + raise ProgramError('F003', readsfile2, 'FASTQ') + + # read and verify record of sequence + record2 = readsfile2_id.readline() + if record2 == '': + # control the FASTQ format + raise ProgramError('F003', readsfile2, 'FASTQ') + + # assign the sequence + seq2 = record2.strip() + + # read and verify record of plus + record2 = readsfile2_id.readline() + if not record2.startswith('+'): + # control the FASTQ format + raise ProgramError('F003', readsfile2, 'FASTQ') + + # read and verify record of quality + record2 = readsfile2_id.readline() + if record2 == '': + # control the FASTQ format + raise ProgramError('F003', readsfile2, 'FASTQ') + + # assign the quality + quality2 = record2.strip() + + # write record in unifile + unified_reads_file_id.write('{0}|||{1}|||{2}|||{3}|||{4}|||{5}\n'.format(seq1, seq2, info1, info2, quality1, quality2)) + + # notify the reads have been processed + reads_count += 1 + Message.print('verbose', '\rProcessed reads: {0:9d}'.format(reads_count)) + + # read the next record of readsfile1 y readfile2 + record1 = readsfile1_id.readline() + record2 = readsfile2_id.readline() + + # control there are not records in readsfile1 and readsfile2 + if record1 != '' or record2 != '': + raise ProgramError('L003', readsfile1, readsfile2) + + # close files + readsfile1_id.close() + if readtype == 'PE': + readsfile2_id.close() + unified_reads_file_id.close() + + # show OK message + Message.print('verbose', '\n') + Message.print('info', 'The temporal file {0} is created.'.format(get_file_name(unified_reads_file))) + +#------------------------------------------------------------------------------- + +def sort_records(unified_reads_file, sorted_reads_file): + '''Sort the temporal file with records unified by read.''' + + Message.print('info', 'Sorting the temporal file {0} ...'.format(get_file_name(unified_reads_file))) + + # Sort the file with records unified by read + if sys.platform.startswith('linux') or sys.platform.startswith('darwin'): + rc = subprocess.call('sort {0} > {1}'.format(unified_reads_file, sorted_reads_file), shell=True) + elif sys.platform.startswith('win32') or sys.platform.startswith('cygwin'): + rc = subprocess.call('sort {0} /output {1}'.format(unified_reads_file, sorted_reads_file), shell=True) + else: + raise ProgramError('S001') + if rc != 0: + raise ProgramError('S002', unified_reads_file) + + # show OK message + Message.print('info', 'The temporal file {0} is created.'.format(get_file_name(sorted_reads_file))) + +#------------------------------------------------------------------------------- + +def purge_records(format, readtype, sorted_reads_file, purged_reads_file): + '''Quantify and remove the PCR duplicates.''' + + # open the file with sorted records unified by read + try: + sorted_reads_file_id = open(sorted_reads_file, mode='r', encoding='iso-8859-1') + except: + raise ProgramError('F002', sorted_reads_file) + + # open the file with reads purged + try: + purged_reads_file_id = open(purged_reads_file, mode='w', encoding='iso-8859-1') + except: + raise ProgramError('F002', purged_reads_file) + + # asign the pattern of the records: + # FASTA: seq1|||info1 in SE and seq1|||seq2|||info1|||info2 in PE + # FASTQ: seq1|||info1|||quality1 in SE and seq1|||seq2|||info1|||info2|||quality1|||quality2 in PE + if format == 'FASTA' and readtype == 'SE': + pattern_record = r'^(.*)\|\|\|(.*)$' + elif format == 'FASTA' and readtype == 'PE': + pattern_record = r'^(.*)\|\|\|(.*)\|\|\|(.*)\|\|\|(.*)$' + elif format == 'FASTQ' and readtype =='SE': + pattern_record = r'^(.*)\|\|\|(.*)\|\|\|(.*)$' + elif format == 'FASTQ' and readtype =='PE': + pattern_record = r'^(.*)\|\|\|(.*)\|\|\|(.*)\|\|\|(.*)\|\|\|(.*)\|\|\|(.*)$' + + # assign the pattern of the info when the origin is simddRADseq.py + pattern_info_se = r'^read: (\d+) \| locus: (\d+) \| read in locus: (\d+) \| fragment: (\d+) \| mutated: (.+) \| individual: (.+) \| index1: (.+) \| index2:$' + pattern_info_pe = r'^read: (\d+) \| locus: (\d+) \| read in locus: (\d+) \| fragment: (\d+) \| mutated: (.+) \| individual: (.+) \| index1: (.+) \| index2: (.+)$' + + # initialize the stats + stats_dict = {} + + # initialize the count of reads + reads_count = 0 + + # initialize the count of removed reads + removedreads_count = 0 + + # read the first record of sorted_reads_file + record1 = sorted_reads_file_id.readline() + + # while there are records in sorted_reads_file + while record1 != '': + + # add 1 to the count of reads + reads_count += 1 + + # if readtype is SE + if readtype == 'SE': + + # extract the data of record1 + try: + mo = re.search(pattern_record, record1) + record1_seq1 = mo.group(1).strip() + record1_info1 = mo.group(2).strip() + except: + raise ProgramError('D102', record1.strip('\n'), sorted_reads_file) + + # extract the data of info1 + try: + mo = re.search(pattern_info_se, record1_info1) + record1_locus = mo.group(2).strip() + record1_mutated = mo.group(5).strip() + record1_individual = mo.group(6).strip() + key = '{0}-{1}'.format(record1_locus, record1_individual) + except: + key = 'invitro' + + # notify the reads have been processed + Message.print('verbose', '\rProcessed reads: {0:9d}'.format(reads_count)) + + # read the next record of unifile + record2 = sorted_reads_file_id.readline() + + # if record2 has data + if record2 != '': + + # extract the data of record2 + try: + mo = re.search(pattern_record, record2) + record2_seq1 = mo.group(1).strip() + except: + raise ProgramError('D102', record2.strip('\n'), sorted_reads_file) + + # if record2 has not data + else: + record2_seq1 = '' + + # if record1_seq1 is not equal to record2_seq1, write record in purgedfile + if record1_seq1 != record2_seq1: + data_dict = stats_dict.get(key, {'total':0, 'total_nomutated':0, 'total_mutated':0, 'removed':0, 'removed_nomutated':0, 'removed_mutated':0}) + data_dict['total'] += 1 + if record1_mutated == 'True': + data_dict['total_mutated'] += 1 + else: + data_dict['total_nomutated'] += 1 + stats_dict[key] = data_dict + purged_reads_file_id.write(record1) + else: + removedreads_count += 1 + data_dict = stats_dict.get(key, {'total':0, 'total_nomutated':0, 'total_mutated':0, 'removed':0, 'removed_nomutated':0, 'removed_mutated':0}) + data_dict['total'] += 1 + if record1_mutated == 'True': + data_dict['total_mutated'] += 1 + else: + data_dict['total_nomutated'] += 1 + data_dict['removed'] += 1 + if record1_mutated == 'True': + data_dict['removed_mutated'] += 1 + else: + data_dict['removed_nomutated'] += 1 + stats_dict[key] = data_dict + Message.print('trace', 'record removed: {0}'.format(record1_info1)) + + # asssign record2 to record1 + record1 = record2 + + # if readtype is PE + elif readtype == 'PE': + + # extract the data of record1 + try: + mo = re.search(pattern_record, record1) + record1_seq1 = mo.group(1).strip() + record1_seq2 = mo.group(2).strip() + record1_info1 = mo.group(3).strip() + except: + raise ProgramError('D102', record1.strip('\n'), sorted_reads_file) + + # extract the data of info1 + try: + mo = re.search(pattern_info_pe, record1_info1) + record1_locus = mo.group(2).strip() + record1_mutated = mo.group(5).strip() + record1_individual = mo.group(6).strip() + key = '{0}-{1}'.format(record1_locus, record1_individual) + except: + key = 'invitro' + + # notify the reads have been processed + Message.print('verbose', '\rProcessed reads: {0:9d}'.format(reads_count)) + + # read the next record of unifile + record2 = sorted_reads_file_id.readline() + + # if record2 has data + if record2 != '': + + # extract the data of record2 + try: + mo = re.search(pattern_record, record2) + record2_seq1 = mo.group(1).strip() + record2_seq2 = mo.group(2).strip() + except: + raise ProgramError('D102', record2.strip('\n'), sorted_reads_file) + + # if record2 has not data + else: + record2_seq1 = '' + record2_seq2 = '' + + # if record1_seq1 concated with record1_seq2 is not equal to record2_seq1 concated with record2_seq2, write record in purgedfile + if (record1_seq1 + record1_seq2) != (record2_seq1 + record2_seq2): + data_dict = stats_dict.get(key, {'total':0, 'total_nomutated':0, 'total_mutated':0, 'removed':0, 'removed_nomutated':0, 'removed_mutated':0}) + data_dict['total'] += 1 + if record1_mutated == 'True': + data_dict['total_mutated'] += 1 + else: + data_dict['total_nomutated'] += 1 + stats_dict[key] = data_dict + purged_reads_file_id.write(record1) + else: + removedreads_count += 1 + data_dict = stats_dict.get(key, {'total':0, 'total_nomutated':0, 'total_mutated':0, 'removed':0, 'removed_nomutated':0, 'removed_mutated':0}) + data_dict['total'] += 1 + if record1_mutated == 'True': + data_dict['total_mutated'] += 1 + else: + data_dict['total_nomutated'] += 1 + data_dict['removed'] += 1 + if record1_mutated == 'True': + data_dict['removed_mutated'] += 1 + else: + data_dict['removed_nomutated'] += 1 + stats_dict[key] = data_dict + Message.print('trace', 'record removed: {0}'.format(record1_info1)) + + # asssign record2 to record1 + record1 = record2 + + # close files + sorted_reads_file_id.close() + purged_reads_file_id.close() + + # show OK message + Message.print('verbose', '\n') + Message.print('info', 'The temporal file {0} is created.'.format(get_file_name(purged_reads_file))) + + # save the count of reads and removed reads in stats + stats_dict['reads_count'] = reads_count + stats_dict['removedreads_count'] = removedreads_count + + # return the stats + return stats_dict + +#------------------------------------------------------------------------------- + +def restore_format(format, readtype, purged_reads_file, clearfile1, clearfile2): + '''Restore the original file(s) format.''' + + # open the file with reads purged + try: + purged_reads_file_id = open(purged_reads_file, mode='r', encoding='iso-8859-1') + except: + raise ProgramError('F002', purged_reads_file) + + # open the file(s) with reads purged in the original format + try: + clearfile1_id = open(clearfile1, mode='w', encoding='iso-8859-1') + except: + raise ProgramError('F002', clearfile1) + if readtype == 'PE': + try: + clearfile2_id = open(clearfile2, mode='w', encoding='iso-8859-1') + except: + raise ProgramError('F002', clearfile2) + + # initialize the count of reads + reads_count = 0 + + # if the inputfile format is FASTA + if format == 'FASTA': + + # assign the pattern of the records: seq1|||info1 in SE and seq1|||seq2|||info1|||info2 in PE + if readtype == 'SE': + pattern = r'^(.*)\|\|\|(.*)$' + elif readtype == 'PE': + pattern = r'^(.*)\|\|\|(.*)\|\|\|(.*)\|\|\|(.*)$' + + # read the first record of purgedfile + record = purged_reads_file_id.readline() + + # while there are records in purgedfile + while record != '': + + # extract the data + try: + mo = re.search(pattern, record) + if readtype == 'SE': + seq1 = mo.group(1).strip() + info1 = mo.group(2).strip() + elif readtype == 'PE': + seq1 = mo.group(1).strip() + seq2 = mo.group(2).strip() + info1 = mo.group(3).strip() + info2 = mo.group(4).strip() + except: + raise ProgramError('D102', record.strip('\n'), purged_reads_file) + + # write the info and the sequence in clearfile(s) + clearfile1_id.write('>{0}\n'.format(info1)) + clearfile1_id.write('{0}\n'.format(seq1)) + if readtype == 'PE': + clearfile2_id.write('>{0}\n'.format(info2)) + clearfile2_id.write('{0}\n'.format(seq2)) + + # notify the reads have been processed + reads_count += 1 + Message.print('verbose', '\rProcessed reads: {0:9d}'.format(reads_count)) + + # read the next record of purgedfile + record = purged_reads_file_id.readline() + + # if the inputfile format is FASTQ + elif format == 'FASTQ': + + # assign the pattern of the records: seq1|||info1|||quality1 in SE and seq1|||seq2|||info1|||info2|||quality1|||quality2 in PE + if readtype == 'SE': + pattern = r'^(.*)\|\|\|(.*)\|\|\|(.*)$' + elif readtype == 'PE': + pattern = r'^(.*)\|\|\|(.*)\|\|\|(.*)\|\|\|(.*)\|\|\|(.*)\|\|\|(.*)$' + + # read the first record of purgedfile + record = purged_reads_file_id.readline() + + # while there are records in purgedfile + while record != '': + + # extract the data + try: + mo = re.search(pattern, record) + if readtype == 'SE': + seq1 = mo.group(1).strip() + info1 = mo.group(2).strip() + quality1 = mo.group(3).strip() + elif readtype == 'PE': + seq1 = mo.group(1).strip() + seq2 = mo.group(2).strip() + info1 = mo.group(3).strip() + info2 = mo.group(4).strip() + quality1 = mo.group(5).strip() + quality2 = mo.group(6).strip() + except: + raise ProgramError('D102', record.strip('\n'), purged_reads_file) + + # write the info and the sequence in clearfile(s) + clearfile1_id.write('@{0}\n'.format(info1)) + clearfile1_id.write('{0}\n'.format(seq1)) + clearfile1_id.write('+\n') + clearfile1_id.write('{0}\n'.format(quality1)) + if readtype == 'PE': + clearfile2_id.write('@{0}\n'.format(info2)) + clearfile2_id.write('{0}\n'.format(seq2)) + clearfile2_id.write('+\n') + clearfile2_id.write('{0}\n'.format(quality2)) + + # notify the reads have been processed + reads_count += 1 + Message.print('verbose', '\rProcessed reads: {0:9d}'.format(reads_count)) + + # read the next record of purgedfile + record = purged_reads_file_id.readline() + + # close files + purged_reads_file_id.close() + clearfile1_id.close() + if readtype == 'PE': + clearfile2_id.close() + + # show OK message + Message.print('verbose', '\n') + if readtype == 'SE': + Message.print('info', 'The file {0} is created.'.format(get_file_name(clearfile1))) + elif readtype == 'PE': + Message.print('info', 'The files {0} and {1} are created.'.format(get_file_name(clearfile1), get_file_name(clearfile2))) + +#------------------------------------------------------------------------------- + +def build_options(): + '''Build a dictionary with the program options.''' + + # get all options dictionary + all_options_dict = get_all_options_dict() + + # define the options dictionary + options_dict = { + 'format': all_options_dict['format'], + 'readtype': all_options_dict['readtype'], + 'readsfile1': all_options_dict['readsfile1'], + 'readsfile2': all_options_dict['readsfile2'], + 'clearfile': all_options_dict['clearfile'], + 'dupstfile': all_options_dict['dupstfile'], + 'plot': all_options_dict['plot'], + 'verbose': all_options_dict['verbose'], + 'trace': all_options_dict['trace'] + } + + # return the options dictionary + return options_dict + +#------------------------------------------------------------------------------- + +def print_help(options_dict): + '''Print the program help.''' + + # get general data + project_name = get_project_name() + project_version = get_project_version() + + program_file = get_file_name(__file__) + config_file = get_config_file(__file__) + + # print the help + Message.print('info', '') + Message.print('info', '{0} version {1}'.format(project_name, project_version)) + Message.print('info', '') + Message.print('info', '{0} quantifies the PCR duplicates and removes them from a file(s) in FASTQ/FASTA format with sequences of a double digest RADseq.'.format(program_file)) + Message.print('info', '') + Message.print('info', 'Usage: {0} --help'.format(program_file)) + Message.print('info', '') + Message.print('info', ' Show the help of {0}.'.format(program_file)) + Message.print('info', '') + Message.print('info', ' or: {0} --config'.format(program_file)) + Message.print('info', '') + Message.print('info', ' Create the config file {0} with the default value of the options.'.format(config_file)) + Message.print('info', ' The default value of the options can be modified.'.format(config_file)) + Message.print('info', '') + Message.print('info', ' or: {0} [--option= [--option=, ...]]'.format(program_file)) + Message.print('info', '') + Message.print('info', ' The options values are read from the config file {0}, but they can be modified'.format(config_file)) + Message.print('info', ' in command line. The options are:') + Message.print('info', '') + Message.print('info', ' {0:12} {1}'.format('option', 'value')) + Message.print('info', ' {0:12} {1}'.format('=' * 12, '=' * 95)) + Message.print('info', ' {0:12} {1}'.format('--format', options_dict['format']['comment'])) + Message.print('info', ' {0:12} {1}'.format('--readtype', options_dict['readtype']['comment'])) + Message.print('info', ' {0:12} {1}'.format('--readsfile1', options_dict['readsfile1']['comment'])) + Message.print('info', ' {0:12} {1}'.format('--readsfile2', options_dict['readsfile2']['comment'])) + Message.print('info', ' {0:12} {1}'.format('--clearfile', options_dict['clearfile']['comment'])) + Message.print('info', ' {0:12} {1}'.format('--dupstfile', options_dict['dupstfile']['comment'])) + Message.print('info', ' {0:12} {1}'.format('--plot', options_dict['plot']['comment'])) + Message.print('info', ' {0:12} {1}'.format('--verbose', options_dict['verbose']['comment'])) + Message.print('info', ' {0:12} {1}'.format('--trace', options_dict['trace']['comment'])) + +#------------------------------------------------------------------------------- + +def build_config(options_dict): + '''Build the file with the options by default.''' + + # get the config file + config_file = get_config_file(__file__) + + # create the config file and write the default options + try: + with open(config_file, mode='w', encoding='iso-8859-1') as config_file_id: + config_file_id.write('{0:46} # {1}\n'.format('format' + '=' + options_dict['format']['default'], options_dict['format']['comment'])) + config_file_id.write('{0:46} # {1}\n'.format('readtype' + '=' + options_dict['readtype']['default'], options_dict['readtype']['comment'])) + config_file_id.write('{0:46} # {1}\n'.format('readsfile1' + '=' + options_dict['readsfile1']['default'], options_dict['readsfile1']['comment'])) + config_file_id.write('{0:46} # {1}\n'.format('readsfile2' + '=' + options_dict['readsfile2']['default'], options_dict['readsfile2']['comment'])) + config_file_id.write('{0:46} # {1}\n'.format('clearfile' + '=' + options_dict['clearfile']['default'], options_dict['clearfile']['comment'])) + config_file_id.write('{0:46} # {1}\n'.format('dupstfile' + '=' + options_dict['dupstfile']['default'], options_dict['dupstfile']['comment'])) + config_file_id.write('{0:46} # {1}\n'.format('plot' + '=' + options_dict['plot']['default'], options_dict['plot']['comment'])) + config_file_id.write('{0:46} # {1}\n'.format('verbose' + '=' + options_dict['verbose']['default'], options_dict['verbose']['comment'])) + config_file_id.write('{0:46} # {1}\n'.format('trace' + '=' + options_dict['trace']['default'], options_dict['trace']['comment'])) + except: + raise ProgramError('F001', config_file) + + # show OK message + Message.print('info', 'The configuration file {0} is created.'.format(get_file_name(config_file))) + +#------------------------------------------------------------------------------- + +if __name__ == '__main__': + main(sys.argv[1:]) + sys.exit(0) + +#------------------------------------------------------------------------------- +","Python" +"In Silico","GGFHF/ddRADseqTools","Package/rsitesearch.py",".py","34534","706","#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +#------------------------------------------------------------------------------- + +'''This software has been developed by: + + GI Genética, Fisiología e Historia Forestal + Dpto. Sistemas y Recursos Naturales + ETSI Montes, Forestal y del Medio Natural + Universidad Politécnica de Madrid + https://github.com/ggfhf/ + + Licence: GNU General Public Licence Version 3 +''' + +#------------------------------------------------------------------------------- + +'''This source contains the program of the ddRADseqTools software package that + searches the restriction sites of a genome, does a double digestion and writes + a file in FASTA format with the fragments gotten. +''' +#------------------------------------------------------------------------------- + +import gzip +import re +import sys + +from genlib import * + +#------------------------------------------------------------------------------- + +def main(argv): + '''Main line of the program.''' + + # build the options dictionary + options_dict = build_options() + + # it has been requested the help or to build a new config file + for param in argv: + # show the help and exit OK + if param.startswith('--help'): + print_help(options_dict) + sys.exit(0) + # build the config file and exit OK + elif param.startswith('--config'): + build_config(options_dict) + sys.exit(0) + + # get the config file + config_file = get_config_file(__file__) + + # get options from the config file and the input parameters + options_dict = get_options(options_dict, config_file, argv) + + # get the restriction site sequences + rsfile = options_dict['rsfile']['value'] + enzyme1 = options_dict['enzyme1']['value'] + enzyme2 = options_dict['enzyme2']['value'] + (ressite1_seq, ressite1_lcut_seq, ressite1_rcut_seq, ressite2_seq, ressite2_lcut_seq, ressite2_rcut_seq) = get_ressites(rsfile, enzyme1, enzyme2) + + # if the sequences of the restriction sites are different + if ressite1_seq.upper() != ressite2_seq.upper(): + + # get the fragments doing a double digestion of the genome + Message.print('info', 'The enzymes have different restriction site sequences, so the fragments will correspond to a double digestion.') + do_double_digest(options_dict) + + # if the sequences of the restriction sites are equal + else: + + # get the fragments doing a single digestion of the genome + Message.print('info', 'The enzymes have equal restriction site sequences, so the fragments will correspond to a single digestion.') + do_single_digest(options_dict) + +#------------------------------------------------------------------------------- + +def do_double_digest(options_dict): + '''Do in silico a double digest of the genome.''' + + genfile = options_dict['genfile']['value'] + fragsfile = options_dict['fragsfile']['value'] + rsfile = options_dict['rsfile']['value'] + enzyme1 = options_dict['enzyme1']['value'] + enzyme2 = options_dict['enzyme2']['value'] + minfragsize = options_dict['minfragsize']['value'] + maxfragsize = options_dict['maxfragsize']['value'] + fragstfile = options_dict['fragstfile']['value'] + fragstinterval = options_dict['fragstinterval']['value'] + plot = options_dict['plot']['value'] + verbose = options_dict['verbose']['value'] + trace = options_dict['trace']['value'] + + # set the verbose and trace status + if verbose.upper() == 'YES': + Message.set_verbose_status(True) + else: + Message.set_verbose_status(False) + if trace.upper() == 'YES': + Message.set_trace_status(True) + else: + Message.set_trace_status(False) + + # get the restriction site sequences + (ressite1_seq, ressite1_lcut_seq, ressite1_rcut_seq, ressite2_seq, ressite2_lcut_seq, ressite2_rcut_seq) = get_ressites(rsfile, enzyme1, enzyme2) + Message.print('trace', 'ressite1_seq: {0} - ressite1_lcut_seq: {1} - ressite1_rcut_seq: {2}'.format(ressite1_seq, ressite1_lcut_seq, ressite1_rcut_seq)) + Message.print('trace', 'ressite2_seq: {0} - ressite2_lcut_seq: {1} - ressite2_rcut_seq: {2}'.format(ressite2_seq, ressite2_lcut_seq, ressite2_rcut_seq)) + + # get the restriction overhangs + if len(ressite1_lcut_seq) >= len(ressite1_rcut_seq): + resoverhang1_seq = get_reverse_complementary_sequence(ressite1_lcut_seq) + else: + resoverhang1_seq = ressite1_rcut_seq + if len(ressite2_lcut_seq) >= len(ressite2_rcut_seq): + resoverhang2_seq = ressite1_lcut_seq + else: + resoverhang2_seq = get_reverse_complementary_sequence(ressite2_rcut_seq) + Message.print('trace', 'resoverhang1_seq: {0}'.format(resoverhang1_seq)) + Message.print('trace', 'resoverhang2_seq: {0}'.format(resoverhang2_seq)) + + # get the list of sequences corresponding to each enzyme + unambiguous_ressite1_seq_list = get_unambiguous_sequence_list(ressite1_seq.upper()) + unambiguous_ressite2_seq_list = get_unambiguous_sequence_list(ressite2_seq.upper()) + Message.print('trace', 'unambiguous_ressite1_seq_list: {0}'.format(unambiguous_ressite1_seq_list)) + Message.print('trace', 'unambiguous_ressite2_seq_list: {0}'.format(unambiguous_ressite2_seq_list)) + + # open the genome file + try: + if genfile.endswith('.gz'): + genfile_id = gzip.open(genfile, mode='rt', encoding='iso-8859-1') + else: + genfile_id = open(genfile, mode='r', encoding='iso-8859-1') + except: + raise ProgramError('F002', genfile) + + # open the fragments file + try: + fragsfile_id = open(fragsfile, mode='w', encoding='iso-8859-1') + except: + raise ProgramError('F002', fragsfile) + + # set the pattern of the head records (>locus_info) + pattern = r'^>(.*)$' + + # initialize the count of the total fragments and written fragments + total_fragments_count = 0 + written_fragments_count = 0 + + # initialize the intervals + intervals_dict = {} + + # initialize the GC distribution + GC_distribution_dict = {} + + # read the first record + record = genfile_id.readline() + + # while there are records + while record != '': + + # process the head record + if record.startswith('>'): + + # extract the data + mo = re.search(pattern, record) + locus_info = mo.group(1) + + # initialize the locus sequence of Watson strand + watson_locus_seq = '' + + # read the next record + record = genfile_id.readline() + + else: + + # control the FASTA format + raise ProgramError('F003', genfile, 'FASTA') + + # while there are records and they are sequence + while record != '' and not record.startswith('>'): + + # concatenate the record to the locus sequence of Watson strand + watson_locus_seq += record.strip().upper() + + # read the next record + record = genfile_id.readline() + + Message.print('trace', 'watson_locus_seq: {0}'.format(watson_locus_seq)) + + # initialize the list of the restriction sites found of the first enzyme in the Watson strand + ressite1_positions_list = [] + + # build the list position found corresponding to first enzyme in the Watson strand + for unambigous_ressite1_seq in unambiguous_ressite1_seq_list: + Message.print('trace', 'unambigous_ressite1_seq: {0}'.format(unambigous_ressite1_seq)) + for m in re.finditer(r'(?=({0}))'.format(unambigous_ressite1_seq), watson_locus_seq): + ressite1_positions_list.append(m.start()) + + # sort the list position found corresponding to first enzyme in the Watson strand + ressite1_positions_list.sort() + Message.print('trace', 'ressite1_positions_list: {0}'.format(ressite1_positions_list)) + + # for each restriction site of the first enzyme in the Watson strand, verify if there is a cut with the second enzyme + for i in range(len(ressite1_positions_list)): + + # initialize the list of restriction site of the second enzyme from the restriction site of the first enzyme in the Watson strand + ressite2_positions_list = [] + + # search the next restriction site of every unambiguous sequence of the second enzyme from the restriction site of the first enzyme in the Watson strand + for unambigous_ressite2_seq in unambiguous_ressite2_seq_list: + Message.print('trace', 'unambigous_ressite2_seq: {0}'.format(unambigous_ressite2_seq)) + unambigous_ressite2_position = watson_locus_seq.find(unambigous_ressite2_seq, (ressite1_positions_list[i] + len(ressite1_seq))) + if unambigous_ressite2_position != -1: + ressite2_positions_list.append(unambigous_ressite2_position) + + # if any restriction site of the second enzyme is not found, exit of the while loop because there is not cut + if ressite2_positions_list == []: + break; + + # calculate the next restriction site of every unambiguous sequence of the second enzyme from the restriction site of the first enzyme in the Watson strand + ressite2_position = min(ressite2_positions_list) + Message.print('trace', 'ressite1_positions_list[i]: {0} - ressite2_positions_list: {1} - ressite2_position: {2}'.format(ressite1_positions_list[i], ressite2_positions_list, ressite2_position)) + + # if a restriction site of the second enzyme is found and this is previous to a restriction site of the first enzyme + if i == (len(ressite1_positions_list) - 1) or ressite2_position < ressite1_positions_list[i + 1]: + + # add 1 to the count of total fragments + total_fragments_count += 1 + + # calculate the start and end positions of the fragment in the genome + start_position = ressite1_positions_list[i] + len(ressite1_seq) - len(resoverhang1_seq) + end_position = ressite2_position + len(resoverhang2_seq) + + # get the genome insert + fragment_seq = watson_locus_seq[start_position:end_position].upper() + + # calculate the fragment length + fragment_len = len(fragment_seq) + + # calculate the GC rate and the N count + (GC_rate, N_count) = get_GC_N_data(fragment_seq) + GC_rate_formatted = '{0:3.2f}'.format(GC_rate) + + # if the fragment length is between the lower and the upper loci fragments size + if minfragsize <= fragment_len <= maxfragsize: + + # add 1 to the count of fragments written + written_fragments_count += 1 + + # write the FASTA head and fragment in the fragments file + fragsfile_id.write('>fragment: {0:d} | length: {1:d} | GC: {2} | strand: {3} | start: {4:d} | end: {5:d} | locus: {6}\n'.format(written_fragments_count, fragment_len, GC_rate_formatted, '+', start_position + 1, end_position, locus_info)) + fragsfile_id.write('{0}\n'.format(fragment_seq)) + Message.print('trace', 'fragment_seq: {0}'.format(fragment_seq)) + + # notify the reads have been written + Message.print('verbose', '\rFragments written ... {0:9d}'.format(written_fragments_count)) + + # update the GC distribution + GC_distribution_dict[GC_rate_formatted] = GC_distribution_dict.get(GC_rate_formatted, 0) + 1 + + # update the intervals with the fragment length + intervals_dict = update_fragments_intervals(intervals_dict, fragstinterval, fragment_len, N_count) + + # get the sequence of the Crick strand + crick_locus_seq = get_reverse_complementary_sequence(watson_locus_seq) + Message.print('trace', 'crick_locus_seq: {0}'.format(crick_locus_seq)) + + # initialize the list of the restriction sites found of the first enzyme in the Crick strand + ressite1_positions_list = [] + + # build the list position found corresponding to first enzyme in the Crick strand + for unambigous_ressite1_seq in unambiguous_ressite1_seq_list: + Message.print('trace', 'unambigous_ressite1_seq: {0}'.format(unambigous_ressite1_seq)) + for m in re.finditer(r'(?=({0}))'.format(unambigous_ressite1_seq), crick_locus_seq): + ressite1_positions_list.append(m.start()) + + # sort the list position found corresponding to first enzyme in the Crick strand + ressite1_positions_list.sort() + Message.print('trace', 'ressite1_positions_list: {0}'.format(ressite1_positions_list)) + + # for each restriction site of the first enzyme in the Crick strand, verify if there is a cut with the second enzyme + for i in range(len(ressite1_positions_list)): + + # initialize the list of restriction site of the second enzyme from the restriction site of the first enzyme in the Crick strand + ressite2_positions_list = [] + + # search the next restriction site of every unambiguous sequence of the second enzyme from the restriction site of the first enzyme in the Crick strand + for unambigous_ressite2_seq in unambiguous_ressite2_seq_list: + Message.print('trace', 'unambigous_ressite2_seq: {0}'.format(unambigous_ressite2_seq)) + unambigous_ressite2_position = crick_locus_seq.find(unambigous_ressite2_seq, (ressite1_positions_list[i] + len(ressite1_seq))) + if unambigous_ressite2_position != -1: + ressite2_positions_list.append(unambigous_ressite2_position) + + # if any restriction site of the second enzyme is not found, exit of the while loop because there is not cut + if ressite2_positions_list == []: + break; + + # calculate the next restriction site of every unambiguous sequence of the second enzyme from the restriction site of the first enzyme in the Crick strand + ressite2_position = min(ressite2_positions_list) + Message.print('trace', 'ressite1_positions_list[i]: {0} - ressite2_positions_list: {1} - ressite2_position: {2}'.format(ressite1_positions_list[i], ressite2_positions_list, ressite2_position)) + + # if a restriction site of the second enzyme is found and this is previous to a restriction site of the first enzyme + if i == (len(ressite1_positions_list) - 1) or ressite2_position < ressite1_positions_list[i + 1]: + + # add 1 to the count of total fragments + total_fragments_count += 1 + + # calculate the start and end positions of the fragment in the genome + start_position = ressite1_positions_list[i] + len(ressite1_seq) - len(resoverhang1_seq) + end_position = ressite2_position + len(resoverhang2_seq) + + # get the genome insert + fragment_seq = crick_locus_seq[start_position:end_position].upper() + + # calculate the fragment length + fragment_len = len(fragment_seq) + + # calculate the GC rate and the N count + (GC_rate, N_count) = get_GC_N_data(fragment_seq) + GC_rate_formatted = '{0:3.2f}'.format(GC_rate) + + # if the fragment length is between the lower and the upper loci fragments size + if minfragsize <= fragment_len <= maxfragsize: + + # add 1 to the count of fragments written + written_fragments_count += 1 + + # write the FASTA head and fragment in the fragments file + fragsfile_id.write('>fragment: {0:d} | length: {1:d} | GC: {2} | strand: {3} | start: {4:d} | end: {5:d} | locus: {6}\n'.format(written_fragments_count, fragment_len, GC_rate_formatted, '-', (len(crick_locus_seq) - start_position), (len(crick_locus_seq) - end_position + 1), locus_info)) + fragsfile_id.write('{0}\n'.format(fragment_seq)) + Message.print('trace', 'fragment_seq: {0}'.format(fragment_seq)) + + # notify the reads have been written + Message.print('verbose', '\rFragments written ... {0:9d}'.format(written_fragments_count)) + + # update the GC distribution + GC_distribution_dict[GC_rate_formatted] = GC_distribution_dict.get(GC_rate_formatted, 0) + 1 + + # update the intervals with the fragment length + intervals_dict = update_fragments_intervals(intervals_dict, fragstinterval, fragment_len, N_count) + + # close files + genfile_id.close() + fragsfile_id.close() + + # show OK message + Message.print('verbose', '\n') + Message.print('info', 'The file {0} containing the fragments of the double digest of the genome is created.'.format(get_file_name(fragsfile))) + + # write the statistics and save them in the statistics file + title = 'Distribution of fragments after a double digest with {0} and {1}'.format(enzyme1, enzyme2) + write_fragments_stats(fragstfile, intervals_dict, total_fragments_count, written_fragments_count, minfragsize, maxfragsize, title) + if plot.upper() == 'YES': + plot_fragments_graphic(fragstfile, intervals_dict, title) + + # write the GC distribution file + write_GC_distribution(fragsfile, GC_distribution_dict) + +#------------------------------------------------------------------------------- + +def do_single_digest(options_dict): + '''Do in silico a single digest of the genome.''' + + genfile = options_dict['genfile']['value'] + fragsfile = options_dict['fragsfile']['value'] + rsfile = options_dict['rsfile']['value'] + enzyme1 = options_dict['enzyme1']['value'] + enzyme2 = options_dict['enzyme2']['value'] + minfragsize = options_dict['minfragsize']['value'] + maxfragsize = options_dict['maxfragsize']['value'] + fragstfile = options_dict['fragstfile']['value'] + fragstinterval = options_dict['fragstinterval']['value'] + plot = options_dict['plot']['value'] + verbose = options_dict['verbose']['value'] + trace = options_dict['trace']['value'] + + # set the verbose and trace status + if verbose.upper() == 'YES': + Message.set_verbose_status(True) + else: + Message.set_verbose_status(False) + if trace.upper() == 'YES': + Message.set_trace_status(True) + else: + Message.set_trace_status(False) + + # get the restriction site sequences + (ressite1_seq, ressite1_lcut_seq, ressite1_rcut_seq, ressite2_seq, ressite2_lcut_seq, ressite2_rcut_seq) = get_ressites(rsfile, enzyme1, enzyme2) + Message.print('trace', 'ressite1_seq: {0} - ressite1_lcut_seq: {1} - ressite1_rcut_seq: {2}'.format(ressite1_seq, ressite1_lcut_seq, ressite1_rcut_seq)) + + # get the restriction overhangs (the restriction overhang sequences in both ends can be different) + if len(ressite1_lcut_seq) >= len(ressite1_rcut_seq): + resoverhang1_seq = get_reverse_complementary_sequence(ressite1_lcut_seq) + else: + resoverhang1_seq = ressite1_rcut_seq + if len(ressite2_lcut_seq) >= len(ressite2_rcut_seq): + resoverhang2_seq = ressite1_lcut_seq + else: + resoverhang2_seq = get_reverse_complementary_sequence(ressite2_rcut_seq) + Message.print('trace', 'resoverhang1_seq: {0}'.format(resoverhang1_seq)) + Message.print('trace', 'resoverhang2_seq: {0}'.format(resoverhang2_seq)) + + # get the list of sequences corresponding to each enzyme + unambiguous_ressite1_seq_list = get_unambiguous_sequence_list(ressite1_seq.upper()) + Message.print('trace', 'unambiguous_ressite1_seq_list: {0}'.format(unambiguous_ressite1_seq_list)) + + # open the genome file + try: + if genfile.endswith('.gz'): + genfile_id = gzip.open(genfile, mode='rt', encoding='iso-8859-1') + else: + genfile_id = open(genfile, mode='r', encoding='iso-8859-1') + except: + raise ProgramError('F002', genfile) + + # open the fragments file + try: + fragsfile_id = open(fragsfile, mode='w', encoding='iso-8859-1') + except: + raise ProgramError('F002', fragsfile) + + # set the pattern of the head records (>locus_info) + pattern = r'^>(.*)$' + + # initialize the count of the total fragments and written fragments + total_fragments_count = 0 + written_fragments_count = 0 + + # initialize the intervals + intervals_dict = {} + + # initialize the GC distribution + GC_distribution_dict = {} + + # read the first record + record = genfile_id.readline() + + # while there are records + while record != '': + + # process the head record + if record.startswith('>'): + + # extract the data + mo = re.search(pattern, record) + locus_info = mo.group(1) + + # initialize the locus sequence of Watson strand + watson_locus_seq = '' + + # read the next record + record = genfile_id.readline() + + else: + + # control the FASTA format + raise ProgramError('F003', genfile, 'FASTA') + + # while there are records and they are sequence + while record != '' and not record.startswith('>'): + + # concatenate the record to the locus sequence of Watson strand + watson_locus_seq += record.strip().upper() + + # read the next record + record = genfile_id.readline() + + Message.print('trace', 'watson_locus_seq: {0}'.format(watson_locus_seq)) + + # initialize the list of position corresponding to the restriction sites in the Watson strand + ressite1_positions_list = [] + + # build the list of position corresponding to the restriction sites in the Watson strand + for unambigous_ressite1_seq in unambiguous_ressite1_seq_list: + Message.print('trace', 'unambigous_ressite1_seq: {0}'.format(unambigous_ressite1_seq)) + for m in re.finditer(r'(?=({0}))'.format(unambigous_ressite1_seq), watson_locus_seq): + ressite1_positions_list.append(m.start()) + + # sort the list of position corresponding to the restriction sites in the Watson strand + ressite1_positions_list.sort() + Message.print('trace', 'ressite1_positions_list: {0}'.format(ressite1_positions_list)) + + # inicialize the last position processed in the Watson strand + last_ressite1_position = 0 + + # inicialize the indicator of first cut with True + is_first_cut = True + + # for each restriction site in the Watson strand + for ressite1_position in ressite1_positions_list: + + # add 1 to the count of total fragments + total_fragments_count += 1 + + # calculate the start and end positions of the fragment in the genome + if is_first_cut == True: + start_position = 0 + else: + start_position = last_ressite1_position + len(ressite1_seq) - len(resoverhang1_seq) + end_position = ressite1_position + len(resoverhang2_seq) + + # set the indicator of first cut to False + is_first_cut = False + + # get the genome insert + fragment_seq = watson_locus_seq[start_position:end_position].upper() + + # calculate the fragment length + fragment_len = len(fragment_seq) + + # calculate the GC rate and the N count + (GC_rate, N_count) = get_GC_N_data(fragment_seq) + GC_rate_formatted = '{0:3.2f}'.format(GC_rate) + + # if the fragment length is between the lower and the upper loci fragments size + if minfragsize <= fragment_len <= maxfragsize: + + # add 1 to the count of fragments written + written_fragments_count += 1 + + # write the FASTA head and fragment in the fragments file + fragsfile_id.write('>fragment: {0:d} | length: {1:d} | GC: {2} | strand: {3} | start: {4:d} | end: {5:d} | locus: {6}\n'.format(written_fragments_count, fragment_len, GC_rate_formatted, '+', start_position + 1, end_position, locus_info)) + fragsfile_id.write('{0}\n'.format(fragment_seq)) + Message.print('trace', 'fragment_seq: {0}'.format(fragment_seq)) + + # notify the reads have been written + Message.print('verbose', '\rFragments written ... {0:9d}'.format(written_fragments_count)) + + # update the GC distribution + GC_distribution_dict[GC_rate_formatted] = GC_distribution_dict.get(GC_rate_formatted, 0) + 1 + + # update the intervals with the fragment length + intervals_dict = update_fragments_intervals(intervals_dict, fragstinterval, fragment_len, N_count) + + # save the last position processed in the Watson strand + last_ressite1_position = ressite1_position + + # if there are nucleotides after the last restriction site in the Watson strand + if last_ressite1_position < len(watson_locus_seq): + + # add 1 to the count of total fragments + total_fragments_count += 1 + + # calculate the start and end positions of the fragment in the genome + #start_position = last_ressite1_position + #end_position = len(watson_locus_seq) + start_position = last_ressite1_position + len(ressite1_seq) - len(resoverhang1_seq) + end_position = len(watson_locus_seq) + + # get the genome insert + fragment_seq = watson_locus_seq[start_position:end_position].upper() + + # calculate the fragment length + fragment_len = len(fragment_seq) + + # calculate the GC rate and the N count + (GC_rate, N_count) = get_GC_N_data(fragment_seq) + GC_rate_formatted = '{0:3.2f}'.format(GC_rate) + + # if the fragment length is between the lower and the upper loci fragments size + if minfragsize <= fragment_len <= maxfragsize: + + # add 1 to the count of fragments written + written_fragments_count += 1 + + # write the FASTA head and fragment in the fragments file + fragsfile_id.write('>fragment: {0:d} | length: {1:d} | GC: {2} | strand: {3} | start: {4:d} | end: {5:d} | locus: {6}\n'.format(written_fragments_count, fragment_len, GC_rate_formatted, '+', start_position + 1, end_position, locus_info)) + fragsfile_id.write('{0}\n'.format(fragment_seq)) + Message.print('trace', 'fragment_seq: {0}'.format(fragment_seq)) + + # notify the reads have been written + Message.print('verbose', '\rFragments written ... {0:9d}'.format(written_fragments_count)) + + # update the GC distribution + GC_distribution_dict[GC_rate_formatted] = GC_distribution_dict.get(GC_rate_formatted, 0) + 1 + + # update the intervals with the fragment length + intervals_dict = update_fragments_intervals(intervals_dict, fragstinterval, fragment_len, N_count) + + # close files + genfile_id.close() + fragsfile_id.close() + + # show OK message + Message.print('verbose', '\n') + Message.print('info', 'The file {0} containing the fragments of the single digest of the genome is created.'.format(get_file_name(fragsfile))) + + # write the statistics and save them in the statistics file + title = 'Distribution of fragments after a single digest with {0}'.format(enzyme1) + write_fragments_stats(fragstfile, intervals_dict, total_fragments_count, written_fragments_count, minfragsize, maxfragsize, title) + if plot.upper() == 'YES': + plot_fragments_graphic(fragstfile, intervals_dict, title) + + # write the GC distribution file + write_GC_distribution(fragsfile, GC_distribution_dict) + +#------------------------------------------------------------------------------- + +def build_options(): + '''Build a dictionary with the program options.''' + + # get all options dictionary + all_options_dict = get_all_options_dict() + + # define the options dictionary + options_dict = { + 'genfile': all_options_dict['genfile'], + 'fragsfile': all_options_dict['fragsfile'], + 'rsfile': all_options_dict['rsfile'], + 'enzyme1': all_options_dict['enzyme1'], + 'enzyme2': all_options_dict['enzyme2'], + 'minfragsize': all_options_dict['minfragsize'], + 'maxfragsize': all_options_dict['maxfragsize'], + 'fragstfile': all_options_dict['fragstfile'], + 'fragstinterval': all_options_dict['fragstinterval'], + 'plot': all_options_dict['plot'], + 'verbose': all_options_dict['verbose'], + 'trace': all_options_dict['trace'] + } + + # return the options dictionary + return options_dict + +#------------------------------------------------------------------------------- + +def print_help(options_dict): + '''Print the program help.''' + + # get general data + project_name = get_project_name() + project_version = get_project_version() + program_file = get_file_name(__file__) + config_file = get_config_file(__file__) + + # print the help + Message.print('info', '') + Message.print('info', '{0} version {1}'.format(project_name, project_version)) + Message.print('info', '') + Message.print('info', '{0} searches the restriction sites of a genome, do a double digestion and write a file in FASTA format with the fragments gotten.'.format(program_file)) + Message.print('info', '') + Message.print('info', 'Usage: {0} --help'.format(program_file)) + Message.print('info', '') + Message.print('info', ' Show the help of {0}.'.format(program_file)) + Message.print('info', '') + Message.print('info', ' or: {0} --config'.format(program_file)) + Message.print('info', '') + Message.print('info', ' Create the config file {0} with the default value of the options.'.format(config_file)) + Message.print('info', ' The default value of the options can be modified.'.format(config_file)) + Message.print('info', '') + Message.print('info', ' or: {0} [--option= [--option=, ...]]'.format(program_file)) + Message.print('info', '') + Message.print('info', ' The options values are read from the config file {0}, but they can be modified'.format(config_file)) + Message.print('info', ' in command line. The options are:') + Message.print('info', '') + Message.print('info', ' {0:16} {1}'.format('option', 'value')) + Message.print('info', ' {0:16} {1}'.format('=' * 16, '=' * 78)) + Message.print('info', ' {0:16} {1}'.format('--genfile', options_dict['genfile']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--fragsfile', options_dict['fragsfile']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--rsfile', options_dict['rsfile']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--enzyme1', options_dict['enzyme1']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--enzyme2', options_dict['enzyme2']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--minfragsize', options_dict['minfragsize']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--maxfragsize', options_dict['maxfragsize']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--fragstfile', options_dict['fragstfile']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--fragstinterval', options_dict['fragstinterval']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--plot', options_dict['plot']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--verbose', options_dict['verbose']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--trace', options_dict['trace']['comment'])) + +#------------------------------------------------------------------------------- + +def build_config(options_dict): + '''Build the file with the options by default.''' + + # get the config file + config_file = get_config_file(__file__) + + # create the config file and write the default options + try: + with open(config_file, mode='w', encoding='iso-8859-1') as config_file_id: + config_file_id.write('{0:43} # {1}\n'.format('genfile' + '=' + options_dict['genfile']['default'], options_dict['genfile']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('fragsfile' + '=' + options_dict['fragsfile']['default'], options_dict['fragsfile']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('rsfile' + '=' + options_dict['rsfile']['default'], options_dict['rsfile']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('enzyme1' + '=' + options_dict['enzyme1']['default'], options_dict['enzyme1']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('enzyme2' + '=' + options_dict['enzyme2']['default'], options_dict['enzyme2']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('minfragsize' + '=' + options_dict['minfragsize']['default'], options_dict['minfragsize']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('maxfragsize' + '=' + options_dict['maxfragsize']['default'], options_dict['maxfragsize']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('fragstfile' + '=' + options_dict['fragstfile']['default'], options_dict['fragstfile']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('fragstinterval' + '=' + options_dict['fragstinterval']['default'], options_dict['fragstinterval']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('plot' + '=' + options_dict['plot']['default'], options_dict['plot']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('verbose' + '=' + options_dict['verbose']['default'], options_dict['verbose']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('trace' + '=' + options_dict['trace']['default'], options_dict['trace']['comment'])) + except: + raise ProgramError('F001', config_file) + + # show OK message + Message.print('info', 'The configuration file {0} is created.'.format(get_file_name(config_file))) + +#------------------------------------------------------------------------------- + +if __name__ == '__main__': + main(sys.argv[1:]) + sys.exit(0) + +#------------------------------------------------------------------------------- +","Python" +"In Silico","GGFHF/ddRADseqTools","Package/genlib.py",".py","113838","2790","#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +#------------------------------------------------------------------------------- + +''' +This software has been developed by: + + GI Genética, Fisiología e Historia Forestal + Dpto. Sistemas y Recursos Naturales + ETSI Montes, Forestal y del Medio Natural + Universidad Politécnica de Madrid + https://github.com/ggfhf/ + +Licence: GNU General Public Licence Version 3 +''' + +#------------------------------------------------------------------------------- + +''' +This source contains the general functions and classes used by other programs +of the ddRADseqTools software package. +''' +#------------------------------------------------------------------------------- + +import os.path +import random +import re +import statistics +import sys + +import numpy as np + +#------------------------------------------------------------------------------- + +def get_project_name(): + ''' + Get the project name. + ''' + + # assign the project name + project_name = 'ddRADseqTools' + + # return the project name: + return project_name + +#------------------------------------------------------------------------------- + +def get_project_version(): + ''' + Get the project name. + ''' + + # assign the project version + project_version = '0.45' + + # return the project name: + return project_version + +#------------------------------------------------------------------------------- + +def get_directory(path): + ''' + Get the directory of a complete path. + ''' + + # assign directory of a complete path + directory = os.path.dirname(path) + '/' + + # return the directory + return directory + +#------------------------------------------------------------------------------- + +def get_file_name(path): + ''' + Get the file name with extension of a complete path. + ''' + + # assign the file name of a complete path + file_name = os.path.basename(path) + + # return the file name with extension + return file_name + +#------------------------------------------------------------------------------- + +def get_file_name_noext(path): + ''' + Get the file name without extension of a complete path. + ''' + + # assign the complete file name of a complete path + file_name = os.path.basename(path) + + # get the the file name without extension + file_name_noext = os.path.splitext(file_name)[0] + + # return the file name without extension + return file_name_noext + +#------------------------------------------------------------------------------- + +def change_extension(path, new_extension): + ''' + Change the file extension. + ''' + + # get the path included file name without extension + i = path.rfind('.') + if i >= 0: + new_path = path[:i + 1] + new_extension + else: + new_path = path + new_extension + + # return the path with new extension + return new_path + +#------------------------------------------------------------------------------- + +def get_config_file(path): + ''' + Get the configuration file. + ''' + + # build the config file + program_name = os.path.splitext(path)[0] + config_file = program_name + '-config.txt' + + # return the config file + return config_file + +#------------------------------------------------------------------------------- + +def get_ressites(rsfile, enzyme1, enzyme2): + ''' + Get the restriction site sequences. The variables enzyme1 and enzyme2 can + hold a valid nucleotides sequence corresponding to the restriction sites + sequence of an enzyme or an enzyme identifier. In last case, the restriction + site sequence is searched in rsfile. + ''' + + # initialize the control variables + enzyme1_found = False + enzyme2_found = False + + # if enzyme1 has a valid nucleotides sequence + if is_valid_sequence(enzyme1, allowed_ambiguity_codes=True, other_allowed_characters_list=[], cut_tag_check=True): + ressite1_seq = enzyme1 + enzyme1_found = True + + # else enzyme1 is an identifier + else: + + # open the rsfile + try: + rsfile_id = open(rsfile, mode='r', encoding='iso-8859-1') + except: + raise ProgramError('F002', rsfile) + + # set the pattern of the rsfile record (enzyme_id;restriction_site_seq) + pattern = r'^(.*);(.*)$' + + # read the first record + record = rsfile_id.readline() + + # while there are records and the two enzymes are not found + while record != '' and not enzyme1_found: + + # if the record is not a comment nor a line with blank characters + if not record.lstrip().startswith('#') and record.strip() != '': + + # extract the data + try: + mo = re.search(pattern, record) + enzyme_id = mo.group(1).strip() + restriction_site_seq = mo.group(2).strip().lower() + except: + raise ProgramError('D102', record.strip('\n'), rsfile) + + # verify that the data are correct + if not is_valid_sequence(restriction_site_seq, allowed_ambiguity_codes=True, other_allowed_characters_list=[], cut_tag_check=True): + raise ProgramError('D103', restriction_site_seq, rsfile) + + # assign the data + if enzyme_id == enzyme1: + ressite1_seq = restriction_site_seq + enzyme1_found = True + + # read the next record + record = rsfile_id.readline() + + # close the rsfile + rsfile_id.close() + + # if enzyme2 has a valid nucleotides sequence + if is_valid_sequence(enzyme2, allowed_ambiguity_codes=True, other_allowed_characters_list=[], cut_tag_check=True): + ressite2_seq = enzyme2 + enzyme2_found = True + + # else enzyme2 is an identifier + else: + + # open the rsfile + try: + rsfile_id = open(rsfile, mode='r', encoding='iso-8859-1') + except: + raise ProgramError('F002', rsfile) + + # set the pattern of the rsfile record (enzyme_id;restriction_site_seq) + pattern = r'^(.*);(.*)$' + + # read the first record + record = rsfile_id.readline() + + # while there are records and the two enzymes are not found + while record != '' and not enzyme2_found: + + # if the record is not a comment nor a line with blank characters + if not record.lstrip().startswith('#') and record.strip() != '': + + # extract the data + try: + mo = re.search(pattern, record) + enzyme_id = mo.group(1).strip() + restriction_site_seq = mo.group(2).strip().lower() + except: + raise ProgramError('D102', record.strip('\n'), rsfile) + + # verify that the data are correct + if not is_valid_sequence(restriction_site_seq, allowed_ambiguity_codes=True, other_allowed_characters_list=[], cut_tag_check=True): + raise ProgramError('D103', restriction_site_seq, rsfile) + + # assign the data + if enzyme_id == enzyme2: + ressite2_seq = restriction_site_seq + enzyme2_found = True + + # read the next record + record = rsfile_id.readline() + + # close the rsfile + rsfile_id.close() + + # control the two enzymes are found + if not enzyme1_found or not enzyme2_found: + if not enzyme1_found: + enzymes_text = enzyme1 + if not enzyme2_found and enzyme1_found: + enzymes_text = enzyme2 + if not enzyme2_found and not enzyme1_found: + enzymes_text += ' & ' + enzyme2 + raise ProgramError('D301', enzymes_text) + + # get the cutted restriction sites + cutsite1 = ressite1_seq.find('*') + if cutsite1 >= 0: + ressite1_lcut_seq = ressite1_seq[:cutsite1] + ressite1_rcut_seq = ressite1_seq[cutsite1 + 1:] + else: + raise ProgramError('D302', ressite1_seq) + cutsite2 = ressite2_seq.find('*') + if cutsite2 >= 0: + ressite2_lcut_seq = ressite2_seq[:cutsite2] + ressite2_rcut_seq = ressite2_seq[cutsite2 + 1:] + else: + raise ProgramError('D302', ressite2_seq) + + # remove the cut mark of the restriction site + ressite1_seq = remove_cutmark(ressite1_seq) + ressite2_seq = remove_cutmark(ressite2_seq) + + # return the the restriction sites + return (ressite1_seq, ressite1_lcut_seq, ressite1_rcut_seq, ressite2_seq, ressite2_lcut_seq, ressite2_rcut_seq) + +#------------------------------------------------------------------------------- + +def get_symbols(): + ''' + Get the symbol of the indexes and the DBR to indentify the PCR duplicates + in the end. + ''' + + # assing symbols + index1_symbol = '1' + index2_symbol = '2' + dbr_symbol = '3' + + # return the symbols + return (index1_symbol, index2_symbol, dbr_symbol) + +#------------------------------------------------------------------------------- + +def get_ends(endsfile, wend, cend, technique, index1len, index1_symbol, index2len, index2_symbol, dbrlen, dbr_symbol): + ''' + Get the end sequences. The variables wend and cend hold end codes of the + Wantson and Crick strand. The sequences are searched in endsfile. + ''' + + # initialize the control variables + wend_found = False + cend_found = False + + # open endsfile + try: + endsfile_id = open(endsfile, mode='r', encoding='iso-8859-1') + except: + raise ProgramError('F002', endsfile) + + # read the first record + record = endsfile_id.readline() + + # while there are records or the two ends are found + while record != '' and not (wend_found and cend_found): + + # if the record is not a comment nor a line with blank characters + if not record.lstrip().startswith('#') and record.strip() != '': + + # set the pattern of the endsfile record (end_id|end_seq) + pattern = r'^(.*);(.*)$' + + # extract the data + try: + mo = re.search(pattern, record) + end_id = mo.group(1).strip() + end_seq = mo.group(2).strip() + except: + raise ProgramError('D102', record.strip('\n'), endsfile) + + # verify that the data are correct + if not is_valid_sequence(end_seq, allowed_ambiguity_codes=False, other_allowed_characters_list=['1', '2', '3'], cut_tag_check=False): + raise ProgramError('D103', end_seq, endsfile) + + # assign the data + if end_id == wend: + wend_seq = end_seq + wend_found = True + if end_id == cend: + cend_seq = end_seq + cend_found = True + + # read the next record + record = endsfile_id.readline() + + # control the two ends are found + if not wend_found or not cend_found: + if not wend_found: + ends_text = wend + if not cend_found and wend_found: + ends_text = cend + if not cend_found and not wend_found: + ends_text += ' & ' + cend + raise ProgramError('D303', ends_text, endsfile) + + # verify if there is index1 and its length and location + index1_symbol_count_wend = wend_seq.count(index1_symbol) + index1_symbol_count_cend = cend_seq.count(index1_symbol) + if index1_symbol_count_wend != index1len or index1_symbol_count_cend > 0: + raise ProgramError('D305', index1_symbol * index1len) + index1_in_wend = index1_symbol * index1len in wend_seq + if not index1_in_wend: + raise ProgramError('D305', index1_symbol * index1len) + + # verify if there is index2 and its length and location + index2_symbol_count_wend = wend_seq.count(index2_symbol) + index2_symbol_count_cend = cend_seq.count(index2_symbol) + if technique in ['IND1', 'IND1_DBR']: + if index2len > 0: + raise ProgramError('NOT-ZERO', technique, 'index2') + if index2_symbol_count_wend > 0 or index2_symbol_count_cend > 0: + raise ProgramError('L004', 'index2', technique, endsfile) + elif technique in ['IND1_IND2', 'IND1_IND2_DBR']: + if index2_symbol_count_wend > 0 or index2_symbol_count_cend != index2len: + raise ProgramError('D307', index2_symbol * index2len) + index2_in_cend = index2_symbol * index2len in cend_seq + if not index2_in_cend: + raise ProgramError('D307', index2_symbol * index2len) + + # verify if there is DBR and its length + dbr_symbol_count_wend = wend_seq.count(dbr_symbol) + dbr_symbol_count_cend = cend_seq.count(dbr_symbol) + if technique in ['IND1', 'IND1_IND2']: + if dbrlen > 0: + raise ProgramError('NOT-ZERO', technique, 'dbrlen') + if dbr_symbol_count_wend > 0 or dbr_symbol_count_cend > 0: + raise ProgramError('L004', 'BDR', technique, endsfile) + dbr_strand = 'none' + elif technique in ['IND1_DBR', 'IND1_IND2_DBR']: + if (dbr_symbol_count_wend != dbrlen or dbr_symbol_count_cend > 0) and (dbr_symbol_count_wend > 0 or dbr_symbol_count_cend != dbrlen): + raise ProgramError('D306', dbr_symbol * dbrlen) + dbr_in_wend = dbr_symbol * dbrlen in wend_seq + dbr_in_cend = dbr_symbol * dbrlen in cend_seq + if (dbr_in_wend and dbr_in_cend) or (not dbr_in_wend and not dbr_in_cend): + raise ProgramError('D306', dbr_symbol * dbrlen) + dbr_strand = 'WEND' if dbr_in_wend else 'CEND' + + # close endsfile + endsfile_id.close() + + # return the two ends + return (wend_seq, cend_seq, dbr_strand) + +#------------------------------------------------------------------------------- + +def get_individuals(individualsfile, technique): + ''' + Get the indviduals data from individualsfile. + ''' + + # initialize the individuals dictionary + individuals_dict = {} + + # open individualsfile + try: + individualsfile_id = open(individualsfile, mode='r', encoding='iso-8859-1') + except: + raise ProgramError('F002', individualsfile) + + # read the first record + record = individualsfile_id.readline() + + # while there are records + while record != '': + + # if the record is not a comment nor a line with blank characters + if not record.strip().startswith('#') and record.strip() != '': + + # set the pattern of the individualsfile record (individual_id;replicated_individual_id;population_id;index1_seq(5'->3');[index2_seq(5'->3')]) + pattern = r'^(.+);(.+);(.+);(.+);(.*)$' + + # extract the data + try: + mo = re.search(pattern, record) + individual_id = mo.group(1).strip() + replicated_individual_id = mo.group(2).strip() + population_id = mo.group(3).strip() + index1_seq = mo.group(4).strip().lower() + index2_seq = mo.group(5).strip().lower() + except: + raise ProgramError('D102', record.strip('\n'), individualsfile) + + # verify that indexes data are correct + if technique in ['IND1', 'IND1_DBR'] and index2_seq != '': + raise ProgramError('L004', 'index2', technique, individualsfile) + if technique in ['IND1_IND2', 'IND1_IND2_DBR'] and index2_seq == '': + raise ProgramError('L005', 'index2', technique, individualsfile) + if not is_valid_sequence(index1_seq, allowed_ambiguity_codes=False, other_allowed_characters_list=[], cut_tag_check=False): + raise ProgramError('D103', index1_seq, individualsfile) + if not is_valid_sequence(index2_seq, allowed_ambiguity_codes=False, other_allowed_characters_list=[], cut_tag_check=False): + raise ProgramError('D103', index2_seq, individualsfile) + + # add data to the dictionary + if index2_seq == '': + individual_key = index1_seq.upper() + else: + individual_key = index1_seq.upper() + '-' + index2_seq.upper() + individuals_dict[individual_key] = {'individual_id':individual_id, 'replicated_individual_id':replicated_individual_id, 'population_id':population_id, 'index1_seq':index1_seq, 'index2_seq':index2_seq} + + # read the next record + record = individualsfile_id.readline() + + # close individualsfile + individualsfile_id.close() + + # verify identifications of replicated individuals + for individual_key, individual_data in individuals_dict.items(): + replicated_individual_id = individual_data['replicated_individual_id'] + if replicated_individual_id.upper() != 'NONE': + replicated_individual_id_found = False + for individual_key2, individual_data2 in individuals_dict.items(): + if individual_data2['individual_id'] == replicated_individual_id: + replicated_individual_id2 = individual_data2['replicated_individual_id'] + if replicated_individual_id2.upper() == 'NONE': + replicated_individual_id_found = True + break + else: + raise ProgramError('L008', replicated_individual_id, individualsfile) + if not replicated_individual_id_found: + raise ProgramError('L007', replicated_individual_id, individualsfile) + + # return the individuals dictionary + return individuals_dict + +#------------------------------------------------------------------------------- + +def get_individual_keys(individuals_dict): + ''' + Get the indvidual keys from individuals dictionary. + ''' + + # initialize the individual keys list + individual_keys_list = [] + + # get the keys of the individuals dictionary + for individual_key, data in individuals_dict.items(): + individual_keys_list.append(individual_key) + + # return the individual keys list + return individual_keys_list + +#------------------------------------------------------------------------------- + +def get_fragments_list(fragsfile): + ''' + Get the fragments from fragsfile and sort them randomly. + ''' + + # initialize the fragments list + fragments_list = [] + + # set the pattern of the head records (>read_info) + pattern = r'^>fragment: (\d*)(.*)GC: (\d\.\d\d)(.*)$' + + # open fragsfile + try: + fragsfile_id = open(fragsfile, mode='r', encoding='iso-8859-1') + except: + raise ProgramError('F002', fragsfile) + + # read the first record of fragsfile + record = fragsfile_id.readline() + + # while there are records in fragsfile + while record != '': + + # process the head record + if record.startswith('>'): + + # extract the data + mo = re.search(pattern, record) + try: + fragment_num = int(mo.group(1).strip()) + GC_rate = float(mo.group(3).strip()) + except: + raise ProgramError('D003', GC_rate, 'GC_rate') + + # initialize the sequence + fragment_seq = '' + + # read the next record of fragsfile + record = fragsfile_id.readline() + + else: + + # control the FASTA format + raise ProgramError('F003', fragsfile, 'FASTA') + + # while there are records in fragsfile and they are sequence + while record != '' and not record.startswith('>'): + + # add the record to the sequence + fragment_seq += record.strip() + + # read the next record of fragsfile + record = fragsfile_id.readline() + + # add new fragment to fragments_list + fragments_list.append([fragment_num, GC_rate, fragment_seq, random.random()]) + + # sort randomly the fragments list + fragments_list = sorted(fragments_list, key=lambda x:x[3]) + + # close fragsfile + fragsfile_id.close() + + # return the fragments list + return fragments_list + +#------------------------------------------------------------------------------- + +def get_nucleotide_dict(): + ''' + Get a dictionary with nucleotide data. + ''' + + # +----+------------------+------------------+-------------+ + # |Code| Description | Translation |Complementary| + # +----+------------------+------------------+-------------+ + # | A |Adenine |A | T/U | + # +----+------------------+------------------+-------------+ + # | C |Cytosine |C | G | + # +----+------------------+------------------+-------------+ + # | G |Guanine |G | C | + # +----+------------------+------------------+-------------+ + # | T |Thymine |T | A | + # +----+------------------+------------------+-------------+ + # | U |Uracil |U | A | + # +----+------------------+------------------+-------------+ + # | R |puRine |A or G | Y | + # +----+------------------+------------------+-------------+ + # | Y |pYrimidine |C or T/U | R | + # +----+------------------+------------------+-------------+ + # | S |Strong interaction|C or G | S | + # +----+------------------+------------------+-------------+ + # | W |Weak interaction |A or T/U | W | + # +----+------------------+------------------+-------------+ + # | K |Keto group |G or T/U | M | + # +----+------------------+------------------+-------------+ + # | M |aMino group |A or C | K | + # +----+------------------+------------------+-------------+ + # | B |not A |C or G or T/U | V | + # +----+------------------+------------------+-------------+ + # | V |not T |A or C or G | B | + # +----+------------------+------------------+-------------+ + # | D |not C |A or G or T/U | H | + # +----+------------------+------------------+-------------+ + # | H |not G |A or C or T/U | D | + # +----+------------------+------------------+-------------+ + # | N |aNy |A or C or G or T/U| N | + # +----+------------------+------------------+-------------+ + + # build the nucleotide dictonary + nucleotide_dict = { + 'A':{'code': 'A', 'nuclotide_list':['A'], 'complementary_code':'T', 'complementary_nuclotide_list':['T']}, + 'a':{'code': 'a', 'nuclotide_list':['a'], 'complementary_code':'t', 'complementary_nuclotide_list':['t']}, + 'C':{'code': 'C', 'nuclotide_list':['C'], 'complementary_code':'G', 'complementary_nuclotide_list':['G']}, + 'c':{'code': 'c', 'nuclotide_list':['c'], 'complementary_code':'g', 'complementary_nuclotide_list':['g']}, + 'G':{'code': 'G', 'nuclotide_list':['G'], 'complementary_code':'C', 'complementary_nuclotide_list':['C']}, + 'g':{'code': 'g', 'nuclotide_list':['g'], 'complementary_code':'c', 'complementary_nuclotide_list':['c']}, + 'T':{'code': 'T', 'nuclotide_list':['T'], 'complementary_code':'A', 'complementary_nuclotide_list':['A']}, + 't':{'code': 't', 'nuclotide_list':['t'], 'complementary_code':'a', 'complementary_nuclotide_list':['a']}, + 'R':{'code': 'R', 'nuclotide_list':['A','G'], 'complementary_code':'Y', 'complementary_nuclotide_list':['C','T']}, + 'r':{'code': 'r', 'nuclotide_list':['a','g'], 'complementary_code':'y', 'complementary_nuclotide_list':['c','t']}, + 'Y':{'code': 'Y', 'nuclotide_list':['C','T'], 'complementary_code':'R', 'complementary_nuclotide_list':['A','G']}, + 'y':{'code': 'y', 'nuclotide_list':['c','t'], 'complementary_code':'r', 'complementary_nuclotide_list':['a','g']}, + 'S':{'code': 'S', 'nuclotide_list':['C','G'], 'complementary_code':'S', 'complementary_nuclotide_list':['C','G']}, + 's':{'code': 's', 'nuclotide_list':['c','G'], 'complementary_code':'s', 'complementary_nuclotide_list':['c','g']}, + 'W':{'code': 'W', 'nuclotide_list':['A','T'], 'complementary_code':'W', 'complementary_nuclotide_list':['A','T']}, + 'w':{'code': 'w', 'nuclotide_list':['a','t'], 'complementary_code':'w', 'complementary_nuclotide_list':['a','t']}, + 'K':{'code': 'K', 'nuclotide_list':['G','T'], 'complementary_code':'M', 'complementary_nuclotide_list':['A','C']}, + 'k':{'code': 'k', 'nuclotide_list':['g','t'], 'complementary_code':'m', 'complementary_nuclotide_list':['a','c']}, + 'M':{'code': 'M', 'nuclotide_list':['A','C'], 'complementary_code':'K', 'complementary_nuclotide_list':['G','T']}, + 'm':{'code': 'm', 'nuclotide_list':['a','c'], 'complementary_code':'k', 'complementary_nuclotide_list':['g','t']}, + 'B':{'code': 'B', 'nuclotide_list':['C','G','T'], 'complementary_code':'V', 'complementary_nuclotide_list':['A','C','G']}, + 'b':{'code': 'b', 'nuclotide_list':['c','G','T'], 'complementary_code':'v', 'complementary_nuclotide_list':['a','c','g']}, + 'V':{'code': 'V', 'nuclotide_list':['A','C','G'], 'complementary_code':'B', 'complementary_nuclotide_list':['C','G','T']}, + 'v':{'code': 'v', 'nuclotide_list':['a','c','g'], 'complementary_code':'b', 'complementary_nuclotide_list':['c','g','t']}, + 'D':{'code': 'D', 'nuclotide_list':['A','G','T'], 'complementary_code':'H', 'complementary_nuclotide_list':['A','C','T']}, + 'd':{'code': 'd', 'nuclotide_list':['a','g','t'], 'complementary_code':'h', 'complementary_nuclotide_list':['a','c','t']}, + 'H':{'code': 'H', 'nuclotide_list':['A','C','T'], 'complementary_code':'D', 'complementary_nuclotide_list':['A','G','T']}, + 'h':{'code': 'h', 'nuclotide_list':['a','C','t'], 'complementary_code':'d', 'complementary_nuclotide_list':['a','g','t']}, + 'N':{'code': 'N', 'nuclotide_list':['A','C','G','T'], 'complementary_code':'N', 'complementary_nuclotide_list':['A','C','G','T']}, + 'n':{'code': 'n', 'nuclotide_list':['a','c','g','t'], 'complementary_code':'n', 'complementary_nuclotide_list':['a','c','g','t']} + } + + # return the nucleotide dictionary + return nucleotide_dict + +#------------------------------------------------------------------------------- + +def get_nucleotide_list(allowed_ambiguity_codes, allowed_lowercase_code): + ''' + Get a list with the nucleotide codes. + ''' + + # initialize the nucleotide list + nucleotide_list = [] + + # get the nucleotide dictonary + nucleotide_dict = get_nucleotide_dict() + + # build the nucleotide list + for code in nucleotide_dict.keys(): + lenght = len(nucleotide_dict[code]['nuclotide_list']) + if (not allowed_ambiguity_codes and lenght == 1 or allowed_ambiguity_codes) and (code.isupper() or code.islower() and allowed_lowercase_code): + nucleotide_list.append(code) + + # sort the nucleotide_list + if nucleotide_list != []: + nucleotide_list.sort() + + # return the nucleotide list + return nucleotide_list + +#------------------------------------------------------------------------------- + +def is_valid_sequence(seq, allowed_ambiguity_codes, other_allowed_characters_list, cut_tag_check): + ''' + Verify if seq have a valid nucleotides sequence. In addition to standard + codes, others allowed characters can be passed. + ''' + + # initialize the control variable + OK = True + + # get nucleotide list + nucleotide_list = get_nucleotide_list(allowed_ambiguity_codes, allowed_lowercase_code=True) + + # set cut tag and cut tag count + cut_tag = '*' + cut_tag_count = 0 + + # verify each nucleotide of the sequence + for i in range(len(seq)): + if cut_tag_check: + if seq[i] not in nucleotide_list and seq[i] != cut_tag and seq[i] not in other_allowed_characters_list: + OK = False + break + if seq[i] == cut_tag: + cut_tag_count += 1 + else: + if seq[i] not in nucleotide_list and seq[i] not in other_allowed_characters_list: + OK = False + break + + # verify the cut tag count + if cut_tag_check: + if cut_tag_count != 1: + OK = False + + # return the control variable + return OK + +#------------------------------------------------------------------------------- + +def get_complementary_sequence(seq): + ''' + Get the complementary sequence of seq. + ''' + + # get the nucleotide dictionary + nucleotide_dict = get_nucleotide_dict() + + # convert the sequence to a list + seq_list = list(seq) + + # get the list changing each nucleotide by its complementary nucleotide + complementary_seq_list = [nucleotide_dict[nucleotide]['complementary_code'] for nucleotide in seq_list] + + # get a string from the complementary list + complementary_seq = ''.join(complementary_seq_list) + + # return the complementary sequence + return complementary_seq + +#------------------------------------------------------------------------------- + +def get_reverse_sequence(seq): + ''' + Get the reverse sequence of seq. + ''' + + # convert the sequence to a list and reverse the elements of the list + seq_list = list(seq) + seq_list.reverse() + + # get a string from the reverse list + reverse_seq = ''.join(seq_list) + + # return the reverse complementary sequence + return reverse_seq + +#------------------------------------------------------------------------------- + +def get_reverse_complementary_sequence(seq): + ''' + Get the reverse complementary sequence of seq. + ''' + + # get the nucleotide dictionary + nucleotide_dict = get_nucleotide_dict() + + # convert the sequence to a list and reverse the elements of the list + seq_list = list(seq) + seq_list.reverse() + + # get the reverse list changing each nucleotide by its complementary nucleotide + revcompl_seq_list = [nucleotide_dict[nucleotide]['complementary_code'] for nucleotide in seq_list] + + # get a string from the reverse complementary list + revcompl_seq = ''.join(revcompl_seq_list) + + # return the reverse complementary sequence + return revcompl_seq + +#------------------------------------------------------------------------------- + +def get_unambiguous_sequence_list(seq): + ''' + Get the list of unambiguous sequences from a sequence with ambiguous nucleotides. + ''' + + # get the nucleotide dictionary + nucleotide_dict = get_nucleotide_dict() + + # if there is not any nucleotide in the sequence + if seq == '': + unambiguous_sequence_list = [''] + + # if there are nucleotidea in the sequence + else: + + # initialize unambiguous sequence list + unambiguous_sequence_list = [] + + # get the nucleotide list corresponding with the code of the first nucleotide + nucleotide_list = nucleotide_dict[seq[0]]['nuclotide_list'] + + # get the list of unambiguous sequences of the sequence except the first nuclotide + split_seq_list = get_unambiguous_sequence_list(seq[1:]) + + # build the unambiguous sequence list + for nucleotide in nucleotide_list: + for split_seq in split_seq_list: + unambiguous_sequence_list.append('{0}{1}'.format(nucleotide, split_seq)) + + # return the unambiguous sequence list + return unambiguous_sequence_list + +#------------------------------------------------------------------------------- + +def get_sequence_with_mismakes_list(seq, admitted_mismatches): + ''' + Get the list of sequences corresponding to a sequence with mismatches. + ''' + + # get the nucleotide list + nucleotide_list = get_nucleotide_list(allowed_ambiguity_codes=False, allowed_lowercase_code=False) + + # if there is not any mismatch + if admitted_mismatches == 0: + sequence_with_mismakes_list = [seq] + + # if there are nucleotidea in the sequence + else: + + # initialize unambiguous sequence list + sequence_with_mismakes_list = [] + + seq_list = [] + for i in range(len(seq)): + for j in range(len(nucleotide_list)): + seq_list.append('{0}{1}{2}'.format(seq[:i], nucleotide_list[j], seq[i+1:])) + + total_seq_list = [] + for i in range(len(seq_list)): + total_seq_list += get_sequence_with_mismakes_list(seq_list[i], admitted_mismatches - 1) + + # remove duplicate sequences + sequence_with_mismakes_list = list(set(total_seq_list)) + + # return the list of sequences corresponding to a sequence with mismatches + return sequence_with_mismakes_list + +#------------------------------------------------------------------------------- + +def remove_cutmark(ressite_seq): + ''' + Remove the cut mark '*' of the restriction site. + ''' + + # initialize the cleared restriction site sequence + cleared_ressite_seq = '' + + # remove the cut mark + for i in range(len(ressite_seq)): + if ressite_seq[i] != '*': + cleared_ressite_seq += ressite_seq[i] + + # return the cleared restriction site sequence + return cleared_ressite_seq + +#------------------------------------------------------------------------------- + +def remove_nucleotides(seq, nucleotides): + ''' + Remove a nucleotides set of a sequence. + ''' + + # calculate the length of the nucleotides + length = len(nucleotides) + + # find the start point of the site where is the nucleotides + start = seq.upper().find(nucleotides.upper()) + + # get the sequence without the nucleotides + if start >= 0: + seq = seq[0:start] + seq[(start + length):] + + # return the sequence without the nucleotides + return seq + +#------------------------------------------------------------------------------- + +def remove_nucleotides_from_seq_to_end(seq, nucleotides, sense): + ''' + Remove nucleotides into a nucleotides set from a sequence to a end. + ''' + + # calculate the length of the nucleotides + length = len(nucleotides) + + # find the start point and the end point of the site where is the nucleotides + start = seq.upper().find(nucleotides.upper()) + end = start + length + + # get the cut sequence + if start >= 0: + if sense == '33': + seq = seq[:(start + length)] + elif sense == '55': + seq = seq[start:] + + # return the sequence + return seq + +#------------------------------------------------------------------------------- + +def get_GC_N_data(seq): + ''' + Get the GC rate and the count of nucleotide codes no standard. + ''' + + # initialize the GC, GCAT and N counts + GC_count = 0 + GCAT_count = 0 + N_count = 0 + + # for each nuecletide in the sequence + for i in range(len(seq)): + + # if nucleotide is C or G + if seq[i] in ['C', 'G']: + + # add 1 to the GC count + GC_count += 1 + + # if nucleotide is C or G or A or T + if seq[i] in ['C', 'G', 'A', 'T']: + + # add 1 to the GCAT count + GCAT_count += 1 + + # if nucleotide is not C or G or A or T (i. e. other nucletide code no standard) + if seq[i] not in ['C', 'G', 'A', 'T']: + + # add 1 to the N count + N_count += 1 + + # calculate the GC rate + GC_rate = GC_count / GCAT_count if GCAT_count != 0 else 0 + + # return the GC rate and the count of nucleotide codes no standard + return (GC_rate, N_count) + +#------------------------------------------------------------------------------- + +def generate_sequence(length): + ''' + Generate randomly a nucleotides sequence with the length passed. + ''' + + # the four nucleotides + nts_list = ['A', 'T', 'C', 'G'] + + # initialize the sequence + seq = '' + + # get randomly a new nucleotide and add it to the sequence + for i in range(length): + radnum = random.randrange(0, 4) + seq += nts_list[radnum] + + # return the sequence + return seq + +#------------------------------------------------------------------------------- + +def build_random_sequence(length, unambiguous_ressite1_seq_list, unambiguous_ressite2_seq_list): + ''' + Build randomly a nucleotides sequence with the length passed verifing the + restriction sites are not included. + ''' + + # initialice the control variable + is_seq_found = True + + # generate a sequence without restriction site sequences + while is_seq_found: + + # generate random sequence + random_seq = generate_sequence(length) + is_seq_found = False + + # if both restriction site sequences are not found, set the control variable to False + try: + for ressite1_seq in unambiguous_ressite1_seq_list: + if random_seq.upper().find(ressite1_seq.upper()) != -1: + raise BreakLoops + for ressite2_seq in unambiguous_ressite2_seq_list: + if random_seq.upper().find(ressite2_seq.upper()) != -1: + raise BreakLoops + except: + is_seq_found = True + + # return the sequence + return random_seq + +#------------------------------------------------------------------------------- + +def merge_sequence(long_seq, replacing_seq, short_seq): + ''' + Merge a sequence of few nucleotides in a certain position of a longer + sequence. + ''' + + # verify the length of short_seq is equeal to length of replacing_seq + if len(short_seq) != len(replacing_seq): + raise ProgramError('L001', short_seq, replacing_seq) + + # find replacing_seq in long_seq + position = long_seq.find(replacing_seq) + if position < 0: + raise ProgramError('L002', replacing_seq, long_seq) + + # bind the merged sequence + merged_seq = long_seq[0:position] + short_seq + long_seq[position+len(short_seq):len(long_seq)] + + # return the merged sequence + return merged_seq + +#------------------------------------------------------------------------------- + +def match_sequences(seq1, seq2, admitted_mismatches): + ''' + Verify that two sequences are matched. + ''' + + # calculate the length of the two sequences and verify that they are equeal + seq1_len = len(seq1) + seq2_len = len(seq2) + if seq1_len != seq2_len: + raise ProgramError('L002', seq1, seq2) + + # calculate the mismatches and get the control sequence + mismatches = 0 + control_seq = '' + for i in range(len(seq1)): + if seq1[i] == seq2[i]: + control_seq += '1' + else: + mismatches += 1 + control_seq += '0' + + # verify the match + are_matched = True if mismatches <= admitted_mismatches else False + + # return if the sequences are matches and the control sequence + return (are_matched, control_seq) + +#------------------------------------------------------------------------------- + +def mutate_sequence(seq, indelprob, maxindelsize, locusmaxmut, min_seq_len, unambiguous_ressite1_seq_list, unambiguous_ressite2_seq_list): + ''' + Mutate the sequence of one nucleotide or do a indel depending on the indel + probability with a indel. The mutated sequence has not the nuclotides + of the restriction sites. + ''' + + # get the mutations number of the sequence + seq_mutations_number_list = [] + for i in range(1, locusmaxmut + 1): + for j in range(1, i + 1): + seq_mutations_number_list.append(j) + seq_mutations_number = seq_mutations_number_list[random.randrange(0, len(seq_mutations_number_list))] + Message.print('trace', 'seq_mutations_number: {0}'.format(seq_mutations_number)) + + # assign the initial value of new sequence + new_seq = '' + + # initialize the attempts number + attempts_number = 0 + + # while the new sequence lenth is less than get a sequence with a length greater or equal than the minimum sequence length + while len(new_seq) < min_seq_len and attempts_number < 10: + + Message.print('trace', 'attempts_number: {0}'.format(attempts_number)) + + # assign the initial value of the previous sequence + old_seq = seq + + # do seq_mutations_number mutations + for i in range(seq_mutations_number): + + # get the length of previous mutated sequence + length = len(old_seq) + + # there is an indel + if indelprob > random.random(): + + # get random indel size + indelsize = random.randrange(1, maxindelsize + 1) + + # if there is a insertion + if random.random() < 0.5: + + # set the indel type + indel_type = 'insertion' + + # get indel initial position + j = random.randrange(0, length) + + # get the insertion sequence + insertion_seq = build_random_sequence(indelsize, unambiguous_ressite1_seq_list, unambiguous_ressite2_seq_list).lower() + + # build the new sequence + new_seq = old_seq[:j] + insertion_seq + old_seq[j:] + + Message.print('trace', 'insertion ({0}) generated in {1} with length of {2}'.format(insertion_seq, j, indelsize)) + + # there is a deletion + else: + + # get indel initial position + j = random.randrange(0, length - indelsize) + + # build the new sequence + new_seq = old_seq[:j] + old_seq[(j + indelsize):] + + Message.print('trace', 'deletion generated in {0} with length of {1}'.format(j, indelsize)) + + # there is a SNP or there was an excessive number of indel attempts due to a short fragments + else: + + # get SNP position + j = random.randrange(0, length) + + # get the mutated nucleotide + while True: + mutated_nucleotide = generate_sequence(1).lower() + # verify that mutated nucleotide is not equal to nucleotide without mutation + if mutated_nucleotide.upper() != old_seq[j].upper(): + break + + # build the new mutated sequence on the previusly mutated sequence + new_seq = old_seq[:j] + mutated_nucleotide + old_seq[(j + 1):] + Message.print('trace', 'SNP in position {0} changing {1} by {2}'.format(j, old_seq[j], mutated_nucleotide)) + + # assign new sequence to the previous sequence for the next iteration + old_seq = new_seq + + # if some restriction site sequence is found, the sequence is not OK + try: + for ressite1_seq in unambiguous_ressite1_seq_list: + if new_seq.upper().find(ressite1_seq.upper()) != -1: + raise BreakLoops + for ressite2_seq in unambiguous_ressite2_seq_list: + if new_seq.upper().find(ressite2_seq.upper()) != -1: + raise BreakLoops + except: + new_seq = '' + Message.print('trace', 'some restriction site sequence is found') + + # add 1 to the attempts number + attempts_number += 1 + + # when the new sequence could not be built + if new_seq == '': new_seq = seq + + # return the mutated sequence + return new_seq + +#------------------------------------------------------------------------------- + +def generate_quality(qltylen): + ''' + Generate a quality sequence. + ''' + + # generate a quality sequence + quality = 'E' * qltylen + + # return the quality + return quality + +#------------------------------------------------------------------------------- + +def calculate_locus_reads_number(readsnum, minreadvar, maxreadvar, locinum): + ''' + Calculate randomly the reads number of a locus depending on the total reads + number and the number of loci. + ''' + + # calculate randomly the reads number + min_readsnum = round(readsnum * minreadvar / locinum) + max_readsnum = round(readsnum * maxreadvar / locinum) + locus_readsnum = random.randrange(min_readsnum, max_readsnum + 1) + + # return the reads number of the locus + return locus_readsnum + +#------------------------------------------------------------------------------- + +def arethere_pcrdup(pcrdupprob, GC_rate, GC_distribution_list, gcfactor): + ''' + Determine if there are PCR duplicates. + ''' + + # search the accumulated counts total rate + gc_count_total_rate = 0 + for i in range(len(GC_distribution_list)): + if GC_distribution_list[i][0] <= GC_rate: + gc_count_total_rate = GC_distribution_list[i][2] + else: + break + + # decide if there are PCR duplicates + if pcrdupprob > 0 and (pcrdupprob + (gc_count_total_rate - 0.5) * gcfactor) > random.random(): + return True + else: + return False + +#------------------------------------------------------------------------------- + +def calculate_pcrdup_num(pcrdup, pcrdistribution, multiparam ,poissonparam): + ''' + Calculate the PCR duplicates number. + ''' + + # initialize the PCR duplicates number + pcrdup_num = 0 + + # calculate the PCR duplicates number + if pcrdup: + if pcrdistribution == 'MULTINOMIAL': + distribution = np.random.multinomial(1, multiparam, 1) + for i in range(len(distribution[0])): + if distribution[0][i] == 1: + pcrdup_num = i + break + elif pcrdistribution == 'POISSON': + pcrdup_num = np.random.poisson(poissonparam, 1) + + # return the PCR duplicates number + return pcrdup_num + +#------------------------------------------------------------------------------- + +def update_fragments_intervals(intervals_dict, fragstinterval, fragment_len, N_count): + ''' + Update the intervals with the fragment data. + ''' + + # calculate the interval identification + start = ((fragment_len - 1) // fragstinterval) * fragstinterval + 1 + end = start + fragstinterval - 1 + interval_id = '{0:0>9d}-{1:0>9d}'.format(start, end) + + # retrieve the intervals data + data_interval = intervals_dict.get(interval_id, [0, 0]) + + # add 1 to the count of the range + data_interval[0] += 1 + + # if N count is greater than 0 + if N_count > 0: + # add 1 to the count of fragment with N + data_interval[1] += 1 + + # update the data interval + intervals_dict[interval_id] = data_interval + + # return the updated intervals + return intervals_dict + +#------------------------------------------------------------------------------- + +def write_fragments_stats(fragstfile, intervals_dict, total_fragments_count, written_fragments_count, minfragsize, maxfragsize, title): + ''' + Write the statistics of the fragments gotten in the double digest. + ''' + + # get a list with the sorted intervals + intervals_list = [] + for interval_id, data in intervals_dict.items(): + intervals_list.append([interval_id, data[0], data[1]]) + intervals_list.sort() + + # open the text file of fragments statistics + try: + fragstfile_id = open(fragstfile, mode='w', encoding='iso-8859-1') + except: + raise ProgramError('F002', fragstfile) + + # open the CSV file of fragments statistics + csv_fragstfile = change_extension(fragstfile, 'csv') + try: + csv_fragstfile_id = open(csv_fragstfile, mode='w', encoding='iso-8859-1') + except: + raise ProgramError('F002', csv_fragstfile) + + # write the heads in text file + fragstfile_id.write('{0}\n'.format(title)) + fragstfile_id.write('{0}\n'.format('=' * len(title))) + fragstfile_id.write('\n') + fragstfile_id.write('+-------------------+-------+-------+-------------+\n') + fragstfile_id.write('| FRAGMENT INTERVAL | FRAGS |PERCENT|FRAGS W/N (*)|\n') + fragstfile_id.write('+-------------------+-------+-------+-------------+\n') + + # write the heads in CSV file + csv_fragstfile_id.write('""FRAGMENT INTERVAL"";""FRAGS"";""PERCENT"";""FRAGS WITH Ns"";\n') + + # write the data of each interval + pattern = r'(\d+)-(\d+)$' + for i in range(len(intervals_list)): + + # extract the data + try: + mo = re.search(pattern, intervals_list[i][0]) + first_value = int(mo.group(1)) + last_value = int(mo.group(2)) + except: + raise ProgramError('D101', pattern, intervals_list[i][0]) + count = intervals_list[i][1] + percentage = intervals_list[i][1] * 100 / total_fragments_count if total_fragments_count else 0 + count_N = intervals_list[i][2] + + # write the data in the text file + fragstfile_id.write('|{0:>9d}-{1:<9d}|{2:>7d}|{3:>7.4f}|{4:>13d}|\n'.format(first_value, last_value, count, percentage, count_N)) + fragstfile_id.write('+-------------------+-------+-------+-------------+\n') + + # write the data in the CSV file + csv_fragstfile_id.write('""{0:>9d}-{1:<9d}"";{2};{3};{4};\n'.format(first_value, last_value, count, percentage, count_N)) + + # write the counts of the total fragments and fragments written in the text data + fragstfile_id.write('| Total |{0:>7d}|\n'.format(total_fragments_count)) + fragstfile_id.write('+-------------------+-------+\n') + fragstfile_id.write('\n') + fragstfile_id.write('There are {0} fragments with size between {1} and {2} nucleotides'.format(written_fragments_count, minfragsize, maxfragsize)) + fragstfile_id.write('\n') + fragstfile_id.write('(*) Number of fragments with Ns in their sequence') + + # close statistics files + fragstfile_id.close() + csv_fragstfile_id.close() + + # show OK message + Message.print('info', 'The statistics can be consulted in the file {0}.'.format(get_file_name(fragstfile))) + Message.print('info', 'The CSV file {0} can be used to import data in a statistics program.'.format(get_file_name(csv_fragstfile))) + +#------------------------------------------------------------------------------- + +def plot_fragments_graphic(fragstfile, intervals_dict, title): + ''' + Plot a fragments distribution graphic and save it in a file. + ''' + + # verify that the library numpy is installed + try: + import numpy as np + except: + Message.print('info', 'The library numpy is not installed. The program will not plot the fragments distribution graphic.') + return + + # verify that the library matplotlib is installed + try: + import matplotlib.pyplot as plt + except: + Message.print('info', 'The library matplotlib is not installed. The program will not plot the fragments distribution graphic.') + return + + # get a list with the sorted intervals + intervals_list = [] + for interval_id, data in intervals_dict.items(): + intervals_list.append([interval_id, data[0], data[1]]) + intervals_list.sort() + + # get intervals list and counts list with range values lower or equal to 1000 nucleotides + pattern = r'(\d+)-(\d+)$' + interval_id_list = [] + counts_list = [] + for i in range(len(intervals_list)): + try: + mo = re.search(pattern, intervals_list[i][0]) + first_value = int(mo.group(1)) + last_value = int(mo.group(2)) + except: + raise ProgramError('D101', pattern, intervals_list[i][0]) + if first_value <= 1000: + interval_id_list.append('{0:d}-{1:d}'.format(first_value, last_value)) + counts_list.append(int(intervals_list[i][1])) + + # do the graphic + fig = plt.figure() + fig.subplots_adjust(top=0.8) + fig.set_size_inches(20, 15) + ind = np.arange(len(counts_list)) + width = 0.35 + ax = fig.add_subplot(211) + ax.set_title(title) + ax.set_xlabel('Length intervals') + ax.set_ylabel('Count') + xTickMarks = interval_id_list + ax.set_xticks(ind + width) + xtickNames = ax.set_xticklabels(xTickMarks) + plt.setp(xtickNames, rotation=45, fontsize=10) + plt.bar(ind, counts_list, width, color='red') + + # build the graphic file + graphic_file = os.path.splitext(fragstfile)[0] + '.png' + + # save the graphic in the file graphicfile + plt.savefig(graphic_file) + + # show OK message + Message.print('info', 'The statistics graphic is saved in the file {0}.'.format(get_file_name(graphic_file))) + +#------------------------------------------------------------------------------- + +def write_pcrdup_stats(dupstfile, stats_dict): + ''' + Write the PCR duplicates statistics. + ''' + + # open the text file of PCR duplicates statistics + try: + dupstfile_id = open(dupstfile, mode='w', encoding='iso-8859-1') + except: + raise ProgramError('F002', dupstfile) + + # open the CSV file of PCR duplicates statistics + csv_dupstfile = change_extension(dupstfile, 'csv') + try: + csv_dupstfile_id = open(csv_dupstfile, mode='w', encoding='iso-8859-1') + except: + raise ProgramError('F002', csv_dupstfile) + + # write the data + if stats_dict != {}: + + # get the reads count and remove it from the dictionary + reads_count = stats_dict['reads_count'] + del stats_dict['reads_count'] + + # get the reads count and remove it from the dictionary + removedreads_count = stats_dict['removedreads_count'] + del stats_dict['removedreads_count'] + + # verify if data have been gotten in vitro or in silico + invitro_count = stats_dict.get('invitro', 0) + + # if in silico way, write the loci and individuals statistics + if invitro_count == 0: + + # calculate the loci statistics + loci_stats_dict = calculate_loci_pcrdup_stats(stats_dict) + + # get loci PCR duplicates list + loci_pcrdup_list = [] + for locus, pcrdup in loci_stats_dict.items(): + loci_pcrdup_list.append(pcrdup) + + # set the pattern of the key of stats dictionary + pattern = r'^(\d+)-(.+)$' + + # initialize the loci list and the individuals list + loci_list = [] + individuals_list = [] + + # for each key in stats dictionary + for key in stats_dict.keys(): + + # extract the data + try: + mo = re.search(pattern, key) + locus = int(mo.group(1)) + individual = mo.group(2) + except: + raise ProgramError('D101', pattern, key) + + # add locus to the loci list + if loci_list.count(locus) == 0: + loci_list.append(locus) + + # add individual to the individuals list + if individuals_list.count(individual) == 0: + individuals_list.append(individual) + + # sort the loci list and the individuals list + loci_list.sort() + individuals_list.sort() + + # initialize the total of loci and loci with PCR duplicates + loci_total = 0 + loci_pcrdup_total = 0 + + # initialize dictionary of loci total per individual without data + loci_without_data_dict = {} + for individual in individuals_list: + loci_without_data_dict[individual] = 0 + + # write heads in text file + dupstfile_id.write('Distribution of removed and total reads by locus and individual\n') + dupstfile_id.write('===============================================================\n') + dupstfile_id.write('\n') + dupstfile_id.write('+-------------+') + for individual in individuals_list: + dupstfile_id.write('-----------+') + dupstfile_id.write('-----------------------+-----------+--------------|\n') + dupstfile_id.write('| LOCUS |') + for individual in individuals_list: + dupstfile_id.write('{0:11}|'.format(individual)) + dupstfile_id.write('REMOV.READS-TOTAL READS|DUPLICATES?|INDS. W/O DATA|\n') + dupstfile_id.write('+-------------+') + for individual in individuals_list: + dupstfile_id.write('-----------+') + dupstfile_id.write('-----------------------+-----------+--------------|\n') + + # write heads in CSV file + csv_dupstfile_id.write('""LOCUS"";') + for individual in individuals_list: + csv_dupstfile_id.write('""{0} REMOV.READS"";""{0} TOTAL READS"";'.format(individual)) + csv_dupstfile_id.write('""REMOVED READS"";""TOTAL READS"";""DUPLICATES?"";""INDS. W/O DATA"";""INDS. W/O DATA RATE""\n') + + # write locus data per individual in text file and CSV file + for locus in loci_list: + + # add 1 to the total of loci + loci_total += 1 + + # initialize total reads and removed reads of the locus + locus_total_reads = 0 + locus_removed_reads = 0 + locus_individuals_without_data = 0 + + # write the locus identification in the text file + dupstfile_id.write('|{0:>13d}|'.format(locus)) + + # write the locus identification in the CSV file + csv_dupstfile_id.write('""{0}"";'.format(locus)) + + # for every individual identification + for individual in individuals_list: + + # get the total and removed reads of the locus and individual + key = '{0}-{1}'.format(locus, individual) + data_dict = stats_dict.get(key, {'total':0, 'removed':0}) + + # add the PCR duplicated reads of the locus and individual to the locus PCR duplicates total + locus_total_reads += data_dict['total'] + locus_removed_reads += data_dict['removed'] + + # add 1 to locus individuals without data if there is not reads in the locus/individual + locus_individuals_without_data += 1 if data_dict['total'] == 0 else 0 + + # add 1 to total of loci of the individual without data if there is not reads in the locus/individual + loci_without_data_dict[individual] += 1 if data_dict['total'] == 0 else 0 + + # write the removed reads of the locus and individual in the text file + #dupstfile_id.write('{0:>10d}|'.format(data_dict['removed'])) + dupstfile_id.write('{0:>4d} - {1:>4d}|'.format(data_dict['removed'], data_dict['total'])) + + # write the PCR duplicated reads of the locus and individual in the CSV file + csv_dupstfile_id.write('{0};{1};'.format(data_dict['removed'], data_dict['total'])) + + # determine if the locus has PCR duplicates + if locus_removed_reads / locus_total_reads > 0.1: + is_locus_with_pcrdup = True + loci_pcrdup_total += 1 + else: + is_locus_with_pcrdup = False + + # write the locus PCR duplicates total and z in text file + dupstfile_id.write('{0:>10d} - {1:>10d}|{2:>11}|{3:>7d} ({4:>3.2f})|\n'.format(locus_removed_reads, locus_total_reads, 'Yes' if is_locus_with_pcrdup else 'No', locus_individuals_without_data, locus_individuals_without_data / len(individuals_list))) + + # write the separation line in text file + dupstfile_id.write('+-------------+') + for individual in individuals_list: + dupstfile_id.write('-----------+') + dupstfile_id.write('-----------------------+-----------+--------------|\n') + + # write the locus PCR duplicates total and z in CSV file + csv_dupstfile_id.write('{0};{1};{2};{3};{4};\n'.format(locus_removed_reads, locus_total_reads, 'Yes' if is_locus_with_pcrdup else 'No', locus_individuals_without_data, locus_individuals_without_data / len(individuals_list))) + + # write the total of loci per individual without data in dupstfile in text file + dupstfile_id.write('|LOCI W/O DATA|') + for individual in individuals_list: + dupstfile_id.write('{0:>5d}({1:>3.2f})|'.format(loci_without_data_dict[individual], loci_without_data_dict[individual] / len(loci_list))) + dupstfile_id.write(' | | |\n') + dupstfile_id.write('+-------------+') + for individual in individuals_list: + dupstfile_id.write('-----------+') + dupstfile_id.write('-----------------------+-----------+--------------|\n') + + # write the total of loci per individual without data in dupstfile in CSV file + csv_dupstfile_id.write('""LOCI W/O DATA"";') + for individual in individuals_list: + csv_dupstfile_id.write('{0};{1};'.format(loci_without_data_dict[individual], loci_without_data_dict[individual] / len(loci_list))) + csv_dupstfile_id.write(';;;;\n') + + # write the resume of stats in dupstfile in text file + rate = loci_pcrdup_total / loci_total if loci_total != 0 else 0 + dupstfile_id.write('\n') + dupstfile_id.write('loci total: {0} - loci with PCR duplicates total: {1} ({2:3.2f})\n'.format(loci_total, loci_pcrdup_total, rate)) + dupstfile_id.write('reads count: {0} - removed reads count: {1}\n'.format(reads_count, removedreads_count)) + + # write the resume of stats in dupstfile in csv file + csv_dupstfile_id.write(';\n') + csv_dupstfile_id.write('""loci total: {0} - loci with PCR duplicates total: {1} ({2:3.2f})"";\n'.format(loci_total, loci_pcrdup_total, rate)) + csv_dupstfile_id.write('""reads count: {0} - removed reads count: {1}"";\n'.format(reads_count, removedreads_count)) + + # close statistics files + dupstfile_id.close() + csv_dupstfile_id.close() + + # show OK message + Message.print('info', 'The statistics can be consulted in the file {0}.'.format(get_file_name(dupstfile))) + Message.print('info', 'The CSV file {0} can be used to import data in a statistics program.'.format(get_file_name(csv_dupstfile))) + +#------------------------------------------------------------------------------- + +def calculate_loci_pcrdup_stats(stats_dict): + ''' + Calculate the PCR duplicates statistics of loci. + ''' + + # initialize the loci stats + loci_stats_dict = {} + + # set the pattern of the key of stats dictionary + pattern = r'^(\d+)-(.+)$' + + # for each key in stats dictionary + for stats_key, stats_data_dict in stats_dict.items(): + + # extract the data + try: + mo = re.search(pattern, stats_key) + locus = int(mo.group(1)) + individual = mo.group(2) + except: + raise ProgramError('D101', pattern, stats_key) + + # add value to the locus count + locus_data_dict = loci_stats_dict.get(locus, {'total':0, 'removed':0}) + locus_data_dict['total'] += stats_data_dict['total'] + locus_data_dict['removed'] += stats_data_dict['removed'] + loci_stats_dict[locus] = locus_data_dict + + # return the loci stats + return loci_stats_dict + +#------------------------------------------------------------------------------- + +def plot_pcrdup_graphics(dupstfile, stats_dict): + ''' + Plot a statistics graphics and save it in a file. + ''' + + # verify that data have been gotten in vitro or in silico + invitro_count = stats_dict.get('invitro', 0) + + # if in vitro, return + if invitro_count != 0: + return + + # verify that the library numpy is installed + try: + import numpy as np + except: + Message.print('info', 'The library numpy is not installed. The program will not plot the statistic graphic.') + return + + # verify that the library matplotlib is installed + try: + import matplotlib.pyplot as plt + except: + Message.print('info', 'The library matplotlib is not installed. The program will not plot the statistic graphic.') + return + + # calculate the loci statistics + loci_stats_dict = calculate_loci_pcrdup_stats(stats_dict) + + # get loci list and counts list order by loci id + loci_list_1 = sorted(loci_stats_dict.keys()) + counts_list_1 = [] + for locus in loci_list_1: + counts_list_1.append(loci_stats_dict[locus]['removed']) + + # do graphic ""removed reads order by locus id"" + fig = plt.figure() + fig.subplots_adjust(top=0.8) + fig.set_size_inches(60, 15) + ind = np.arange(len(counts_list_1)) + width = 0.35 + ax = fig.add_subplot(211) + ax.set_title('Removed reads order by locus id') + ax.set_xlabel('Loci') + ax.set_ylabel('Count') + xTickMarks = loci_list_1 + ax.set_xticks(ind + width) + xtickNames = ax.set_xticklabels(xTickMarks) + plt.setp(xtickNames, rotation=45, fontsize=10) + plt.bar(ind, counts_list_1, width, color='red') + + # build graphic ""Removed reads order by locus id"" file name + graphic_file_1 = os.path.splitext(dupstfile)[0] + '-1.png' + + # save graphic ""Removed reads order by locus id"" in their file + plt.savefig(graphic_file_1) + + # get loci list and counts list order by count + loci_stats_list = [] + for locus, locus_data in loci_stats_dict.items(): + loci_stats_list.append([locus, locus_data['removed']]) + loci_stats_list = sorted(loci_stats_list, key=lambda x:x[1], reverse=True) + loci_list_2 = [] + counts_list_2 = [] + for i in range(len(loci_stats_list)): + loci_list_2.append(loci_stats_list[i][0]) + counts_list_2.append(loci_stats_list[i][1]) + + # do graphic ""Removed reads order by count"" + fig = plt.figure() + fig.subplots_adjust(top=0.8) + fig.set_size_inches(60, 15) + ind = np.arange(len(counts_list_2)) + width = 0.35 + ax = fig.add_subplot(211) + ax.set_title('Removed reads order by count') + ax.set_xlabel('Loci') + ax.set_ylabel('Count') + xTickMarks = loci_list_2 + ax.set_xticks(ind + width) + xtickNames = ax.set_xticklabels(xTickMarks) + plt.setp(xtickNames, rotation=45, fontsize=10) + plt.bar(ind, counts_list_2, width, color='red') + + # build graphic ""Removed reads order by count"" file name + graphic_file_2 = os.path.splitext(dupstfile)[0] + '-2.png' + + # save graphic ""Removed reads order by count"" in their file + plt.savefig(graphic_file_2) + + # show OK message + Message.print('info', 'The statistics graphics are saved in the files {0} and {1}.'.format(get_file_name(graphic_file_1), get_file_name(graphic_file_2))) + +#------------------------------------------------------------------------------- + +def calculate_individuals_withoutdata_distribution(stats_dict): + ''' + Calculate the distribution of the individuals without data per locus. + ''' + + # initialize the distribution of the individuals without data per locus + individuals_withoutdata_distribution_dict = {} + for i in range(11): + individuals_withoutdata_distribution_dict['{0:2.1f}'.format(round(i/10, 1))] = 0 + + # initialize the count of the individuals with data per locus + individuals_withdata_count_dict = {} + + # initialize the loci list and the individuals list + loci_list = [] + individuals_list = [] + + # set the pattern of the key of stats dictionary + pattern = r'^(\d+)-(.+)$' + + # for each key in stats dictionary + for stats_key, data_dict in stats_dict.items(): + + # extract the data + try: + mo = re.search(pattern, stats_key) + locus = int(mo.group(1)) + individual = mo.group(2) + except: + raise ProgramError('D101', pattern, stats_key) + + # add locus to the loci list + if loci_list.count(locus) == 0: + loci_list.append(locus) + + # add individual to the individuals list + if individuals_list.count(individual) == 0: + individuals_list.append(individual) + + # add 1 to individual with data per locus if there is reads in the locus/individual + individuals_withdata_count_dict[locus] = individuals_withdata_count_dict.get(locus, 0) + 1 if data_dict['total'] > 0 else 0 + + # calculate the distribution of the individuals per locus without data + for locus in loci_list: + rate = round((len(individuals_list) - individuals_withdata_count_dict[locus]) / len(individuals_list), 1) + individuals_withoutdata_distribution_dict['{0:2.1f}'.format(rate)] += 1 + + # return the distribution of the individuals per locus without data + return individuals_withoutdata_distribution_dict + +#------------------------------------------------------------------------------- + +def plot_individuals_withoutdata_graphic(dupstfile, stats_dict): + ''' + Plot the graphic of distribution of the individuals without data per locus and save it in a file. + ''' + + # verify if data have been gotten in vitro or in silico + invitro_count = stats_dict.get('invitro', 0) + + # if in vitro, return + if invitro_count != 0: + return + + # verify that the library numpy is installed + try: + import numpy as np + except: + Message.print('info', 'The library numpy is not installed. The program will not plot the individuals per locus without data graphic.') + return + + # verify that the library matplotlib is installed + try: + import matplotlib.pyplot as plt + except: + Message.print('info', 'The library matplotlib is not installed. The program will not plot the individuals per locus without data graphic.') + return + + # calculate the the distribution of the individuals per locus without data + individuals_withoutdata_distribution_dict = calculate_individuals_withoutdata_distribution(stats_dict) + + # get rate list and counts list order by rate + rate_list = sorted(individuals_withoutdata_distribution_dict.keys()) + counts_list = [] + for rate in rate_list: + counts_list.append(individuals_withoutdata_distribution_dict[rate] + 1e-7) + + # do graphic ""Distribution of the individuals without data per locus"" + fig = plt.figure() + fig.subplots_adjust(top=0.8) + fig.set_size_inches(20, 10) + ind = np.arange(len(counts_list)) + width = 0.35 + ax = fig.add_subplot(211) + ax.set_title('Distribution of the individuals without data per locus') + ax.set_xlabel('Distribution') + ax.set_ylabel('Count') + xTickMarks = rate_list + ax.set_xticks(ind + width) + xtickNames = ax.set_xticklabels(xTickMarks) + plt.setp(xtickNames, rotation=45, fontsize=10) + plt.bar(ind, counts_list, width, color='red') + + # build graphic ""Distribution of the individuals without data per locus"" file name + graphic_file = get_directory(dupstfile) + 'individuals_withoutdata.png' + + # save graphic ""Distribution of the individuals without data per locus"" in their file + plt.savefig(graphic_file) + + # show OK message + Message.print('info', 'The graphic of the distribution of the individuals without data per locus is saved in the file {0}.'.format(get_file_name(graphic_file))) + +#------------------------------------------------------------------------------- + +def calculate_loci_withoutdata_distribution(stats_dict): + ''' + Calculate the distribution of the loci without data per individual. + ''' + + # initialize the distribution of the loci without data per individual + loci_withoutdata_distribution_dict = {} + for i in range(11): + loci_withoutdata_distribution_dict['{0:2.1f}'.format(round(i/10, 1))] = 0 + + # initialize the count of the loci with data per individual + loci_withdata_count_dict = {} + + # initialize the loci list and the individuals list + loci_list = [] + individuals_list = [] + + # set the pattern of the key of stats dictionary + pattern = r'^(\d+)-(.+)$' + + # for each key in stats dictionary + for stats_key, data_dict in stats_dict.items(): + + # extract the data + try: + mo = re.search(pattern, stats_key) + locus = int(mo.group(1)) + individual = mo.group(2) + except: + raise ProgramError('D101', pattern, stats_key) + + # add locus to the loci list + if loci_list.count(locus) == 0: + loci_list.append(locus) + + # add individual to the individuals list + if individuals_list.count(individual) == 0: + individuals_list.append(individual) + + # add 1 to locus with data per individual if there is reads in the locus/individual + loci_withdata_count_dict[individual] = loci_withdata_count_dict.get(individual, 0) + 1 if data_dict['total'] > 0 else 0 + + # calculate the distribution of the loci per individual without data + for individual in individuals_list: + rate = round((len(loci_list) - loci_withdata_count_dict[individual]) / len(loci_list), 1) + loci_withoutdata_distribution_dict['{0:2.1f}'.format(rate)] += 1 + + # return the distribution of the loci per individual without data + return loci_withoutdata_distribution_dict + +#------------------------------------------------------------------------------- + +def plot_loci_withoutdata_graphic(dupstfile, stats_dict): + ''' + Plot the graphic of the loci without data per individual and save it in a file. + ''' + + # verify if data have been gotten in vitro or in silico + invitro_count = stats_dict.get('invitro', 0) + + # if in vitro, return + if invitro_count != 0: + return + + # verify that the library numpy is installed + try: + import numpy as np + except: + Message.print('info', 'The library numpy is not installed. The program will not plot the loci per individual without data graphic.') + return + + # verify that the library matplotlib is installed + try: + import matplotlib.pyplot as plt + except: + Message.print('info', 'The library matplotlib is not installed. The program will not plot the loci per individual without data graphic.') + return + + # calculate the the distribution of the loci per individual without data + loci_withoutdata_distribution_dict = calculate_loci_withoutdata_distribution(stats_dict) + + # get rate list and counts list order by rate + rate_list = sorted(loci_withoutdata_distribution_dict.keys()) + counts_list = [] + for rate in rate_list: + counts_list.append(loci_withoutdata_distribution_dict[rate] + 1e-7) + + # do graphic ""Distribution of the loci without data per individual"" + fig = plt.figure() + fig.subplots_adjust(top=0.8) + fig.set_size_inches(20, 10) + ind = np.arange(len(counts_list)) + width = 0.35 + ax = fig.add_subplot(211) + ax.set_title('Distribution of the loci without data per individual') + ax.set_xlabel('Distribution') + ax.set_ylabel('Count') + xTickMarks = rate_list + ax.set_xticks(ind + width) + xtickNames = ax.set_xticklabels(xTickMarks) + plt.setp(xtickNames, rotation=45, fontsize=10) + plt.bar(ind, counts_list, width, color='red') + + # build graphic ""Distribution of the loci without data per individual"" file name + graphic_file = get_directory(dupstfile) + 'loci_withoutdata.png' + + # save graphic ""Distribution of the loci without data per individual"" in their file + plt.savefig(graphic_file) + + # show OK message + Message.print('info', 'The graphic of the distribution of the loci without data per individual is saved in the file {0}.'.format(get_file_name(graphic_file))) + +#------------------------------------------------------------------------------- + +def write_GC_distribution(fragsfile, GC_distribution_dict): + ''' + Save the GC distribution in a file. + ''' + + # get a list with the sorted GC distribution + GC_distribution_list = [] + for GC_rate, count in GC_distribution_dict.items(): + GC_distribution_list.append([float(GC_rate), count]) + GC_distribution_list.sort() + + # build the GC distribution file + GC_distribution_file = os.path.splitext(fragsfile)[0] + '-GC-distribution.csv' + + # create the config file and write the default options + try: + with open(GC_distribution_file, mode='w', encoding='iso-8859-1') as GC_distribution_file_id: + for i in range(len(GC_distribution_list)): + GC_distribution_file_id.write('{0};{1}\n'.format(GC_distribution_list[i][0], GC_distribution_list[i][1])) + except: + raise ProgramError('F001', GC_distribution_file) + + # show OK message + Message.print('info', 'The file {0} containing the GC distribution is created.'.format(get_file_name(GC_distribution_file))) + +#------------------------------------------------------------------------------- + +def get_GC_distribution(GC_distribution_file): + ''' + Get the GC distribution list. + ''' + + # initialize the GC distribution list + GC_distribution_list = [] + + # initialize the total of counts + counts_total = 0 + + # open the GC distribution file + try: + GC_distribution_file_id = open(GC_distribution_file, mode='r', encoding='iso-8859-1') + except: + raise ProgramError('F002', GC_distribution_file) + + # read the first record of the GC distribution file + record = GC_distribution_file_id.readline() + + # while there are records in the GC distribution file + while record != '': + + # set the pattern of the GC distribution file record (GC_rate|count) + pattern = r'([\d\.]+);(\d+)$' + + # extract the data + try: + mo = re.search(pattern, record) + GC_rate = float(mo.group(1).strip()) + count = int(mo.group(2).strip()) + except: + raise ProgramError('D102', record.strip('\n'), GC_distribution_file) + + # add count to the total of counts + counts_total += count + + # add data to the list + GC_distribution_list.append([GC_rate, count, 0]) + + # read the next record + record = GC_distribution_file_id.readline() + + # close GC distribution file + GC_distribution_file_id.close() + + # sort the GC distribution list + GC_distribution_list.sort() + + # calculate the accumulated counts total rate + counts_acumulated = 0 + for i in range(len(GC_distribution_list)): + counts_acumulated += GC_distribution_list[i][1] + GC_distribution_list[i][2] = counts_acumulated / counts_total + + # return GC distribution list + return GC_distribution_list + +#------------------------------------------------------------------------------- + +def get_float_list(float_list_string): + ''' + ''' + + # verify that the string ends with a comma + if float_list_string[len(float_list_string) - 1] != ',': + float_list_string += ',' + + # initialize the float list + float_list = [] + + # get every value of the float list + length = len(float_list_string) + i = 0 + j = float_list_string.find(',') + while j != -1: + if j != 0: + value = float_list_string[i:j] + try: + float_list.append(float(value.strip())) + except: + raise ProgramError('L009', float_list_string) + i = j + 1 + j = float_list_string.find(',',i) + + # verify that the float list is not empty + if float_list == []: + raise ProgramError('L009', float_list_string) + + # verify that the elements of the float list sum 1.0 + total = 0 + for i in range(len(float_list)): + total += float_list[i] + if total != 1.0: + raise ProgramError('L009', float_list_string) + + # return the float list + return float_list + +#------------------------------------------------------------------------------- + +def get_all_options_dict(): + ''' + Get a dictionary with all options available in the software package. + ''' + + # define all options dictionary + all_options_dict = { + 'cend': {'value':'', 'default':'end02', 'comment':""code used in endsfile corresponding to the end where the adapter 2 is""}, + 'clearfile': {'value':'', 'default':'./results/reads-cleared', 'comment':'path of the file with PCR duplicates removed without extension'}, + 'cut': {'value':'', 'default':'YES', 'comment':'YES (cut nucleotides from or until a seq into the read) or NO (change bases by Ns from or until a seq into the read)'}, + 'cutfile': {'value':'', 'default':'./results/reads-cut', 'comment':'path of the file with cut reads from a sequence to 3\' end'}, + 'dbrlen': {'value':'', 'default':'4', 'comment':'DBR sequence length (it must be 0 when technique is IND1 or IND1_IND2)'}, + 'dropout': {'value':'', 'default':'0.0', 'comment':'mutation probability in the enzyme recognition sites (0.0 <= dropout < 1.0)'}, + 'dupstfile': {'value':'', 'default':'./results/pcrduplicates-stats.txt', 'comment':'path of the the PCR duplicates statistics file'}, + 'endsfile': {'value':'', 'default':'./ends.txt', 'comment':'path oh the end selengthquences file'}, + 'enzyme1': {'value':'', 'default':'EcoRI', 'comment':'id of 1st restriction enzyme used in rsfile or its restriction site sequence'}, + 'enzyme2': {'value':'', 'default':'MseI', 'comment':'id of 2nd restriction enzyme used in rsfile or its restriction site sequence'}, + 'filenum': {'value':'', 'default':'1', 'comment':'1: in SE file or the first file in PE files; 2: the second file in PE files'}, + 'format': {'value':'', 'default':'FASTQ', 'comment':'FASTA or FASTQ (format of fragments file)'}, + 'fragsfile': {'value':'', 'default':'./results/fragments.fasta', 'comment':'path of the fragments file'}, + 'fragsnum': {'value':'', 'default':'10000', 'comment':'fragments number'}, + 'fragstinterval': {'value':'', 'default':'25', 'comment':'interval length of fragment size'}, + 'fragstfile': {'value':'', 'default':'./results/fragments-stats.txt', 'comment':'path of the fragment statistics file'}, + 'gcfactor': {'value':'', 'default':'0.0', 'comment':'weight factor of GC ratio in a locus with PCR duplicates (0.0 <= gcfactor < 1.0)'}, + 'genfile': {'value':'', 'default':'./genomes/genome.fasta', 'comment':'file of the reference genome in fasta format'}, + 'gz': {'value':'', 'default':'NO', 'comment':'YES or NO (gzip format is used to compress the files)'}, + 'indelprob': {'value':'', 'default':'0.4', 'comment':'insertion/deletion probability (0.0 <= indelprob < 1.0)'}, + 'index1len': {'value':'', 'default':'6', 'comment':'index sequence length in the adapter 1'}, + 'index2len': {'value':'', 'default':'6', 'comment':'index sequence length in the adapter 2 (it must be 0 when technique is IND1)'}, + 'individualsfile': {'value':'', 'default':'./individuals.txt', 'comment':'path of individuals file'}, + 'insertlen': {'value':'', 'default':'100', 'comment':'read length, i. e. genome sequence length inserted in reads'}, + 'locinum': {'value':'', 'default':'100', 'comment':'loci number to sample'}, + 'locusmaxmut': {'value':'', 'default':'1', 'comment':'maximum mutations number by locus (1 <= locusmaxmut <= 5)'}, + 'maxfragsize': {'value':'', 'default':'300', 'comment':""upper boundary of loci fragment's size""}, + 'maxindelsize': {'value':'', 'default':'3', 'comment':'upper insertion/deletion size (1 <= maxindelsize < 30)'}, + 'maxreadvar': {'value':'', 'default':'1.2', 'comment':'upper variation on reads number per locus (1.0 <= maxreadvar <= 1.5)'}, + 'method': {'value':'', 'default':'RANDOM', 'comment':'RANDOM or GENOME (a reference genome is used to simulate the sequences)'}, + 'minfragsize': {'value':'', 'default':'201', 'comment':""lower boundary of loci fragment's size""}, + 'minreadvar': {'value':'', 'default':'0.8', 'comment':'lower variation on reads number per locus (0.5 <= minreadvar <= 1.0)'}, + 'multiparam': {'value':'', 'default':'0.333,0.267,0.200,0.133,0.067', 'comment':'probability values to multinomial distribution with format prob1,prob2,...,probn (they must sum 1.0)'}, + 'mutprob': {'value':'', 'default':'0.2', 'comment':'mutation probability (0.0 <= mutprob < 1.0)'}, + 'plot': {'value':'', 'default':'YES', 'comment':'statistical graphs: YES or NO'}, + 'poissonparam': {'value':'', 'default':'1.0', 'comment':'lambda value of the Poisson distribution'}, + 'pcrdupprob': {'value':'', 'default':'0.0', 'comment':'PCR duplicates probability in a locus (0.0 <= pcrdupprob < 1.0)'}, + 'pcrdistribution': {'value':'', 'default':'MULTINOMIAL', 'comment':'distribution type to calculate the PCR duplicates number: MULTINOMIAL or POISSON'}, + 'readsfile': {'value':'', 'default':'./results/reads', 'comment':'path of the read file without extension'}, + 'input_readfile': {'value':'', 'default':'./results/reads-1.fastq', 'comment':'path of the read file'}, + 'readsfile1': {'value':'', 'default':'./results/reads-1.fastq', 'comment':'path of the reads file in SE read type or the Watson strand reads file in PE case'}, + 'readsfile2': {'value':'', 'default':'./results/reads-2.fastq', 'comment':'path of the Crick strand reads file in PE read type or NONE in SE case'}, + 'readsnum': {'value':'', 'default':'10000', 'comment':'reads number'}, + 'readtype': {'value':'', 'default':'PE', 'comment':'SE (single-end) or PE (pair-end)'}, + 'rsfile': {'value':'', 'default':'./restrictionsites.txt', 'comment':'path of the restriction sites file'}, + 'sense': {'value':'', 'default':'33', 'comment':'33 (cut or change from the seq 3\' end to read 3\' end) or 55 (cut or change from read 5\' end to the seq 5\' end)'}, + 'seq': {'value':'', 'default':'TGGAGGTGGGG', 'comment':'sequence to be located'}, + 'technique': {'value':'', 'default':'IND1_IND2_DBR', 'comment':'IND1 (only index1), IND1_DBR (index1 + DBR), IND1_IND2 (index1 + index2) or IND1_IND2_DBR (index1 + index2 + DBR)'}, + 'trace': {'value':'', 'default':'NO', 'comment':'additional info useful to the developer team: YES or NO'}, + 'trimfile': {'value':'', 'default':'./results/reads-trimmed', 'comment':'path of the file with trimmed reads without extension'}, + 'verbose': {'value':'', 'default':'YES', 'comment':'additional job status info during the run: YES or NO'}, + 'wend': {'value':'', 'default':'end01', 'comment':""code used in endsfile corresponding to the end where the adapter 1 is""}, + } + + # return all options dictionary + return all_options_dict + +#------------------------------------------------------------------------------- + +def get_options(options_dict, config_file, argv): + ''' + Get options from config file and the input parameters. + ''' + + # open config file + try: + file_id = open(config_file, mode='r', encoding='iso-8859-1') + except: + raise ProgramError('F002', config_file) + + # read the first record + record = file_id.readline() + + # while there are records + while record != '': + + # if the record is not a comment nor a line with blank characters + if not record.lstrip().startswith('#') and record.strip() != '': + + # parse and extract options from the config file + options_dict = parse_options(options_dict, record, ""CF"") + + # read the next record + record = file_id.readline() + + # close config file + file_id.close() + + # parse and extract options from the input parameters + for param in argv: + options_dict = parse_options(options_dict, param, ""IP"") + + # return the dictionary of options + return options_dict + +#------------------------------------------------------------------------------- + +def parse_options(options_dict, param, origin): + ''' + Parse and extract a option from the config file or the input parameters. + ''' + + # parse cend + if param.startswith('--cend=') or param.lstrip().startswith('cend='): + wend = get_option_value(param, origin) + options_dict['cend']['value'] = wend + + # parse clearfile + elif param.startswith('--clearfile=') or param.lstrip().startswith('clearfile='): + clearfile = get_option_value(param, origin) + options_dict['clearfile']['value'] = clearfile + + # parse cut + elif param.startswith('--cut=') or param.lstrip().startswith('cut='): + cut = get_option_value(param, origin).upper() + if cut not in ['YES', 'NO']: + raise ProgramError('D205', 'cut', cut) + options_dict['cut']['value'] = cut + + # parse cutfile + elif param.startswith('--cutfile=') or param.lstrip().startswith('cutfile='): + cutfile = get_option_value(param, origin) + options_dict['cutfile']['value'] = cutfile + + # parse dbrlen + elif param.startswith('--dbrlen=') or param.lstrip().startswith('dbrlen='): + try: + dbrlen = int(get_option_value(param, origin)) + except: + raise ProgramError('D002', 'dbrlen', 0, 10) + if dbrlen < 0 or dbrlen > 10: + raise ProgramError('D002', 'dbrlen', 0, 10) + options_dict['dbrlen']['value'] = dbrlen + + # parse dropout + elif param.startswith('--dropout=') or param.lstrip().startswith('dropout='): + try: + dropout = float(get_option_value(param, origin)) + except: + raise ProgramError('D005', 'dropout', 0.0, 1.0) + if dropout < 0.0 or dropout >= 1.0: + raise ProgramError('D005', 'dropout', 0.0, 1.0) + options_dict['dropout']['value'] = dropout + + # parse dupstfile + elif param.startswith('--dupstfile=') or param.lstrip().startswith('dupstfile='): + dupstfile = get_option_value(param, origin) + options_dict['dupstfile']['value'] = dupstfile + + # parse endsfile + elif param.startswith('--endsfile=') or param.lstrip().startswith('endsfile='): + endsfile = get_option_value(param, origin) + options_dict['endsfile']['value'] = endsfile + + # parse enzyme1 + elif param.startswith('--enzyme1=') or param.lstrip().startswith('enzyme1='): + enzyme1 = get_option_value(param, origin) + options_dict['enzyme1']['value'] = enzyme1 + + # parse enzyme2 + elif param.startswith('--enzyme2=') or param.lstrip().startswith('enzyme2='): + enzyme2 = get_option_value(param, origin) + options_dict['enzyme2']['value'] = enzyme2 + + # parse filenum + elif param.startswith('--filenum=') or param.lstrip().startswith('filenum='): + filenum = get_option_value(param, origin) + if filenum not in ['1', '2']: + raise ProgramError('D206', filenum) + options_dict['filenum']['value'] = filenum + + # parse fragsfile + elif param.startswith('--fragsfile=') or param.lstrip().startswith('fragsfile='): + fragsfile = get_option_value(param, origin) + options_dict['fragsfile']['value'] = fragsfile + + # parse fragsnum + elif param.startswith('--fragsnum=') or param.lstrip().startswith('fragsnum='): + try: + fragsnum = int(get_option_value(param, origin)) + except: + raise ProgramError('D001', 'fragsnum', 0) + if fragsnum <= 0: + raise ProgramError('D001', 'fragsnum', 0) + options_dict['fragsnum']['value'] = fragsnum + + # parse fragstinterval + elif param.startswith('--fragstinterval=') or param.lstrip().startswith('fragstinterval='): + try: + fragstinterval = int(get_option_value(param, origin)) + except: + raise ProgramError('D001', 'fragstinterval', 0) + if fragstinterval <= 0: + raise ProgramError('D001', 'fragstinterval', 0) + options_dict['fragstinterval']['value'] = fragstinterval + + # parse fragstfile + elif param.startswith('--fragstfile=') or param.lstrip().startswith('fragstfile='): + fragstfile = get_option_value(param, origin) + options_dict['fragstfile']['value'] = fragstfile + + # parse format + elif param.startswith('--format=') or param.lstrip().startswith('format='): + format = get_option_value(param, origin).upper() + if format not in ['FASTA', 'FASTQ']: + raise ProgramError('D203', format) + options_dict['format']['value'] = format + + # parse gcfactor + elif param.startswith('--gcfactor=') or param.lstrip().startswith('gcfactor='): + try: + gcfactor = float(get_option_value(param, origin)) + except: + raise ProgramError('D005', 'gcfactor', 0.0, 1.0) + if gcfactor < 0.0 or gcfactor >= 1.0: + raise ProgramError('D005', 'gcfactor', 0.0, 1.0) + options_dict['gcfactor']['value'] = gcfactor + + # parse genfile + elif param.startswith('--genfile=') or param.lstrip().startswith('genfile='): + genfile = get_option_value(param, origin) + options_dict['genfile']['value'] = genfile + + # parse gz + elif param.startswith('--gz=') or param.lstrip().startswith('gz='): + gz = get_option_value(param, origin).upper() + if gz not in ['YES', 'NO']: + raise ProgramError('D205', 'gz', gz) + options_dict['gz']['value'] = gz + + # parse indelprob + elif param.startswith('--indelprob=') or param.lstrip().startswith('indelprob='): + try: + indelprob = float(get_option_value(param, origin)) + except: + raise ProgramError('D005', 'indelprob', 0.0, 1.0) + if indelprob < 0.0 or indelprob >= 1.0: + raise ProgramError('D005', 'indelprob', 0.0, 1.0) + options_dict['indelprob']['value'] = indelprob + + # parse index1len + elif param.startswith('--index1len=') or param.lstrip().startswith('index1len='): + try: + index1len = int(get_option_value(param, origin)) + except: + raise ProgramError('D002', 'index1len', 1, 10) + if index1len < 1 or index1len > 10: + raise ProgramError('D002', 'index1len', 1, 10) + options_dict['index1len']['value'] = index1len + + # parse index2len + elif param.startswith('--index2len=') or param.lstrip().startswith('index2len='): + try: + index2len = int(get_option_value(param, origin)) + except: + raise ProgramError('D002', 'index2len', 0, 10) + if index2len < 0 or index2len > 10: + raise ProgramError('D002', 'index2len', 0, 10) + options_dict['index2len']['value'] = index2len + + # parse individualsfile + elif param.startswith('--individualsfile=') or param.lstrip().startswith('individualsfile='): + individualsfile = get_option_value(param, origin) + options_dict['individualsfile']['value'] = individualsfile + + # parse input_readfile + elif param.startswith('--input_readfile=') or param.lstrip().startswith('input_readfile='): + input_readfile = get_option_value(param, origin) + options_dict['input_readfile']['value'] = input_readfile + + # parse insertlen + elif param.startswith('--insertlen=') or param.lstrip().startswith('insertlen='): + try: + insertlen = int(get_option_value(param, origin)) + except: + raise ProgramError('D001', 'insertlen', 0) + if insertlen <= 0: + raise ProgramError('D001', 'insertlen', 0) + options_dict['insertlen']['value'] = insertlen + + # parse locium + elif param.startswith('--locinum=') or param.lstrip().startswith('locinum='): + try: + locinum = int(get_option_value(param, origin)) + except: + raise ProgramError('D001', 'locinum', 0) + if locinum < 1: + raise ProgramError('D001', 'locinum', 0) + options_dict['locinum']['value'] = locinum + + # parse locusmaxmut + elif param.startswith('--locusmaxmut=') or param.lstrip().startswith('locusmaxmut='): + try: + locusmaxmut = int(get_option_value(param, origin)) + except: + raise ProgramError('D002', 'locusmaxmut', 1, 5) + if locusmaxmut < 1 or locusmaxmut > 5: + raise ProgramError('D002', 'locusmaxmut', 1, 5) + options_dict['locusmaxmut']['value'] = locusmaxmut + + # parse maxfragsize + elif param.startswith('--maxfragsize=') or param.lstrip().startswith('maxfragsize='): + try: + maxfragsize = int(get_option_value(param, origin)) + except: + raise ProgramError('D001', 'maxfragsize', 0) + if maxfragsize <= 0: + raise ProgramError('D001', 'maxfragsize', 0) + options_dict['maxfragsize']['value'] = maxfragsize + + # parse maxindelsize + elif param.startswith('--maxindelsize=') or param.lstrip().startswith('maxindelsize='): + try: + maxindelsize = int(get_option_value(param, origin)) + except: + raise ProgramError('D002', 'maxindelsize', 1, 30) + if maxindelsize < 1 or maxindelsize > 30: + raise ProgramError('D002', 'maxindelsize', 1, 30) + options_dict['maxindelsize']['value'] = maxindelsize + + # parse maxreadvar + elif param.startswith('--maxreadvar=') or param.lstrip().startswith('maxreadvar='): + try: + maxreadvar = float(get_option_value(param, origin)) + except: + raise ProgramError('D004', 'maxreadvar', 1.0, 1.5) + if maxreadvar < 1.0 or maxreadvar > 1.5: + raise ProgramError('D004', 'maxreadvar', 1.0, 1.5) + options_dict['maxreadvar']['value'] = maxreadvar + + # parse method + elif param.startswith('--method=') or param.lstrip().startswith('method='): + method = get_option_value(param, origin).upper() + if method not in ['RANDOM', 'GENOME']: + raise ProgramError('METHOD', method) + options_dict['method']['value'] = method + + # parse minfragsize + elif param.startswith('--minfragsize=') or param.lstrip().startswith('minfragsize='): + try: + minfragsize = int(get_option_value(param, origin)) + except: + raise ProgramError('D001', 'minfragsize', 0) + if minfragsize <= 0: + raise ProgramError('D001', 'minfragsize', 0) + options_dict['minfragsize']['value'] = minfragsize + + # parse minreadvar + elif param.startswith('--minreadvar=') or param.lstrip().startswith('minreadvar='): + try: + minreadvar = float(get_option_value(param, origin)) + except: + raise ProgramError('D004', 'minreadvar', 0.5, 1.0) + if minreadvar < 0.5 or minreadvar > 1.0: + raise ProgramError('D004', 'minreadvar', 0.5, 1.0) + options_dict['minreadvar']['value'] = minreadvar + + # parse multiparam + elif param.startswith('--multiparam=') or param.lstrip().startswith('multiparam='): + multiparam_string = get_option_value(param, origin) + multiparam = get_float_list(multiparam_string) + options_dict['multiparam']['value'] = multiparam + + # parse mutprob + elif param.startswith('--mutprob=') or param.lstrip().startswith('mutprob='): + try: + mutprob = float(get_option_value(param, origin)) + except: + raise ProgramError('D005', 'mutprob', 0.0, 1.0) + if mutprob < 0.0 or mutprob >= 1.0: + raise ProgramError('D005', 'mutprob', 0.0, 1.0) + options_dict['mutprob']['value'] = mutprob + + # parse plot + elif param.startswith('--plot=') or param.lstrip().startswith('plot='): + plot = get_option_value(param, origin).upper() + if plot not in ['YES', 'NO']: + raise ProgramError('D205', 'plot', plot) + options_dict['plot']['value'] = plot + + # parse poissonparam + elif param.startswith('--poissonparam=') or param.lstrip().startswith('poissonparam='): + try: + poissonparam = float(get_option_value(param, origin)) + except: + raise ProgramError('D006', 'poissonparam', 0.0) + if poissonparam < 0.0: + raise ProgramError('D006', 'poissonparam', 0.0) + options_dict['poissonparam']['value'] = poissonparam + + # parse pcrdistribution + elif param.startswith('--pcrdistribution=') or param.lstrip().startswith('pcrdistribution='): + pcrdistribution = get_option_value(param, origin).upper() + if pcrdistribution not in ['MULTINOMIAL', 'POISSON']: + raise ProgramError('PCRDISTRIBUTION', pcrdistribution) + options_dict['pcrdistribution']['value'] = pcrdistribution + + # parse pcrdupprob + elif param.startswith('--pcrdupprob=') or param.lstrip().startswith('pcrdupprob='): + try: + pcrdupprob = float(get_option_value(param, origin)) + except: + raise ProgramError('D005', 'pcrdupprob', 0.0, 1.0) + if pcrdupprob < 0.0 or pcrdupprob >= 1.0: + raise ProgramError('D005', 'pcrdupprob', 0.0, 1.0) + options_dict['pcrdupprob']['value'] = pcrdupprob + + # parse readsfile + elif param.startswith('--readsfile=') or param.lstrip().startswith('readsfile='): + readsfile = get_option_value(param, origin) + options_dict['readsfile']['value'] = readsfile + + # parse readsfile1 + elif param.startswith('--readsfile1=') or param.lstrip().startswith('readsfile1='): + readsfile1 = get_option_value(param, origin) + options_dict['readsfile1']['value'] = readsfile1 + + # parse readsfile2 + elif param.startswith('--readsfile2=') or param.lstrip().startswith('readsfile2='): + readsfile2 = get_option_value(param, origin) + options_dict['readsfile2']['value'] = readsfile2 + + # parse readsnum + elif param.startswith('--readsnum=') or param.lstrip().startswith('readsnum='): + try: + readsnum = int(get_option_value(param, origin)) + except: + raise ProgramError('D001', 'readsnum', 0) + if readsnum < 1: + raise ProgramError('D001', 'readsnum', 0) + options_dict['readsnum']['value'] = readsnum + + # parse readtype + elif param.startswith('--readtype=') or param.lstrip().startswith('readtype='): + readtype = get_option_value(param, origin).upper() + if readtype not in ['SE', 'PE']: + raise ProgramError('D204', readtype) + options_dict['readtype']['value'] = readtype + + # parse rsfile + elif param.startswith('--rsfile=') or param.lstrip().startswith('rsfile='): + rsfile = get_option_value(param, origin) + options_dict['rsfile']['value'] = rsfile + + # parse sense + elif param.startswith('--sense=') or param.lstrip().startswith('sense='): + sense = get_option_value(param, origin) + if sense not in ['33', '55']: + raise ProgramError('D205', 'sense', sense) + options_dict['sense']['value'] = sense + + # parse seq + elif param.startswith('--seq=') or param.lstrip().startswith('seq='): + seq = get_option_value(param, origin) + options_dict['seq']['value'] = seq + + # parse technique + elif param.startswith('--technique=') or param.lstrip().startswith('technique='): + technique = get_option_value(param, origin).upper() + if technique not in ['IND1', 'IND1_DBR', 'IND1_IND2', 'IND1_IND2_DBR']: + raise ProgramError('D202', technique) + options_dict['technique']['value'] = technique + + # parse trace + elif param.startswith('--trace=') or param.lstrip().startswith('trace='): + trace = get_option_value(param, origin).upper() + if trace not in ['YES', 'NO']: + raise ProgramError('D205', 'trace', trace) + options_dict['trace']['value'] = trace + + # parse trimfile + elif param.startswith('--trimfile=') or param.lstrip().startswith('trimfile='): + trimfile = get_option_value(param, origin) + options_dict['trimfile']['value'] = trimfile + + # parse verbose + elif param.startswith('--verbose=') or param.lstrip().startswith('verbose='): + verbose = get_option_value(param, origin).upper() + if verbose not in ['YES', 'NO']: + raise ProgramError('D205', 'verbose', verbose) + options_dict['verbose']['value'] = verbose + + # parse wend + elif param.startswith('--wend=') or param.lstrip().startswith('wend='): + wend = get_option_value(param, origin) + options_dict['wend']['value'] = wend + + # another is a mistake + else: + if param.strip() != '' and not param.lstrip().startswith('#'): + raise ProgramError('D201', param) + + # return the dictionary of options + return options_dict + +#------------------------------------------------------------------------------- + +def get_option_value(param, origin): + ''' + Get the value of a option. + ''' + + # remove the comment if it exists + i = param.find('#') + param = param[:i] if i != -1 else param + + # if origin is the config file + if origin == 'CF': + # set the pattern (option=value) + pattern = r'^\w+=(.+)$' + # if origin is input parameters + elif origin == 'IP': + # set the pattern (--option=value) + pattern = r'^\-{2}\w+=(.+)$' + + # extract the data + try: + mo = re.search(pattern, param.strip()) + value = mo.group(1).strip() + except: + raise ProgramError('D101', pattern, param.strip()) + + # return the value + return value + +#------------------------------------------------------------------------------- + +class ProgramError(Exception): + ''' + This class controls various errors that can occur in the execution of the program. + ''' + + #--------------- + + def __init__(self, code_exception, param1='', param2='', param3=''): + ''' + Initialize the object to manage a passed exception. + ''' + + # manage the code of exception + if code_exception == 'D001': + Message.print('error', '*** ERROR {0}: The {1} value must be an integer greater than {2}.'.format(code_exception, param1, param2)) + elif code_exception == 'D002': + Message.print('error', '*** ERROR {0}: The {1} value must be an integer greater or equal than {2} and lower or equal than {3}.'.format(code_exception, param1, param2, param3)) + elif code_exception == 'D003': + Message.print('error', '*** ERROR {0}: The {1} value contained by {2} is not a float number.'.format(code_exception, param1, param2)) + elif code_exception == 'D004': + Message.print('error', '*** ERROR {0}: The {1} value must be a real greater or equal than {2} and lower or equal than {3}.'.format(code_exception, param1, param2, param3)) + elif code_exception == 'D005': + Message.print('error', '*** ERROR {0}: The {1} value must be a real greater or equal than {2} and lower than {3}.'.format(code_exception, param1, param2, param3)) + elif code_exception == 'D006': + Message.print('error', '*** ERROR {0}: The {1} value must be a real greater or equal than {2}.'.format(code_exception, param1, param2)) + elif code_exception == 'D101': + Message.print('error', '*** ERROR {0}: Invalid pattern {1} in string {2}.'.format(code_exception, param1, param2)) + elif code_exception == 'D102': + Message.print('error', '*** ERROR {0}: Invalid pattern of record --->{1}<--- in file {2}.'.format(code_exception, param1, param2)) + elif code_exception == 'D103': + Message.print('error', '*** ERROR {0}: Invalid DNA sequence {1} in file {2}.'.format(code_exception, param1, param2)) + elif code_exception == 'D201': + Message.print('error', '*** ERROR {0}: {1} is an invalid parameter.'.format(code_exception, param1)) + elif code_exception == 'D202': + Message.print('error', '*** ERROR {0}: tecnique {1} is not avaiable.'.format(code_exception, param1)) + elif code_exception == 'D203': + Message.print('error', '*** ERROR {0}: format {1} of output file is wrong. It must be FASTA or FASTQ.'.format(code_exception, param1)) + elif code_exception == 'D204': + Message.print('error', '*** ERROR {0}: read type {1} is wrong. It must be SE or PE.'.format(code_exception, param1)) + elif code_exception == 'D205': + Message.print('error', '*** ERROR {0}: {1} is not a valid value in option {2}. It must be YES or NO.'.format(code_exception, param2, param1)) + elif code_exception == 'D206': + Message.print('error', '*** ERROR {0}: file number {1} is wrong. It must be 1 or 2.'.format(code_exception, param1)) + elif code_exception == 'D301': + Message.print('error', '*** ERROR {0}: Enzyme identification or restriction site sequence {1} is not valid.'.format(code_exception, param1)) + elif code_exception == 'D302': + Message.print('error', ""*** ERROR {0}: The cut mark '*' is not found in the restriction site sequence {1}."".format(code_exception, param1)) + elif code_exception == 'D303': + Message.print('error', '*** ERROR {0}: End identification {1} not found in {2}.'.format(code_exception, param1, param2)) + elif code_exception == 'D304': + Message.print('error', '*** ERROR {0}: {1} sequence has not found in {2} end of the fragment {3}.'.format(code_exception, param1, param2, param3)) + elif code_exception == 'D305': + Message.print('error', ""*** ERROR {0}: The index1 must be represented by one sequence {1} in at the 5' end of the Watson strand."".format(code_exception, param1)) + elif code_exception == 'D306': + Message.print('error', ""*** ERROR {0}: The DBR must be represented by one sequence {1} in at the 5' end of the Watson or Crick strand."".format(code_exception, param1)) + elif code_exception == 'D307': + Message.print('error', ""*** ERROR {0}: The index2 must be represented by one sequence {1} in at the 5' end of the Crick strand."".format(code_exception, param1)) + elif code_exception == 'F001': + Message.print('error', '*** ERROR {0}: {1} can not be created.'.format(code_exception, param1)) + elif code_exception == 'F002': + Message.print('error', '*** ERROR {0}: {1} can not be opened.'.format(code_exception, param1)) + elif code_exception == 'F003': + Message.print('error', '*** ERROR {0}: Format file {1} is not {2}.'.format(code_exception, param1, param2)) + elif code_exception == 'L001': + Message.print('error', '*** ERROR {0}: The length of {1} is not equeal to the length of {2}.'.format(code_exception, param1, param2)) + elif code_exception == 'L002': + Message.print('error', '*** ERROR {0}: {1} is not found in {2}.'.format(code_exception, param1, param2)) + elif code_exception == 'L003': + Message.print('error', '*** ERROR {0}: Reads number of file {1} is not equal to reads number of file {2}.'.format(code_exception, param1, param2)) + elif code_exception == 'L004': + Message.print('error', ""*** ERROR {0}: A {1} is not used by the technique {2} in the file {3}."".format(code_exception, param1, param2, param3)) + elif code_exception == 'L005': + Message.print('error', ""*** ERROR {0}: A {1} is required by the technique {2} in the file {3}."".format(code_exception, param1, param2, param3)) + elif code_exception == 'L006': + Message.print('error', ""*** ERROR {0}: The restriction sites of both enzimes have the same sequence: {1}."".format(code_exception, param1)) + elif code_exception == 'L007': + Message.print('error', ""*** ERROR {0}: The identification of replicated individual {1} is not a identification of individual in the file {2}."".format(code_exception, param1, param2)) + elif code_exception == 'L008': + Message.print('error', ""*** ERROR {0}: The identification of replicated individual {1} is a identification of other replicated individual in the file {2}."".format(code_exception, param1, param2)) + elif code_exception == 'L009': + Message.print('error', ""*** ERROR {0}: {1} must be comma-separated float numbers and they must sum 1.0."".format(code_exception, param1)) + elif code_exception == 'L010': + Message.print('error', ""*** ERROR {0}: If read type is SE, the file number can not be 2."".format(code_exception)) + elif code_exception == 'S001': + Message.print('error', '*** ERROR {0}: OS not detected.'.format(code_exception)) + elif code_exception == 'S002': + Message.print('error', '*** ERROR {0}: Sorting of file {1} has mistakenly finished.'.format(code_exception, param1)) + else: + Message.print('error', '*** ERROR {0}: This exception is not managed.'.format(code_exception)) + + # exit with error + sys.exit(1) + + #--------------- + +#------------------------------------------------------------------------------- + +class Message(): + ''' + This class controls the informative messages printed on the console. + ''' + + #--------------- + + verbose_status = True + trace_status = False + + #--------------- + + def set_verbose_status(status): + ''' + ''' + + Message.verbose_status = status + + #--------------- + + def set_trace_status(status): + ''' + ''' + + Message.trace_status = status + + #--------------- + + def print(message_type, message_text): + ''' + ''' + + if message_type == 'info': + print(message_text, file=sys.stdout) + sys.stdout.flush() + elif message_type == 'verbose' and Message.verbose_status: + sys.stdout.write(message_text) + sys.stdout.flush() + elif message_type == 'trace' and Message.trace_status: + print(message_text, file=sys.stdout) + sys.stdout.flush() + elif message_type == 'error': + print(message_text, file=sys.stderr) + sys.stderr.flush() + + #--------------- + +#------------------------------------------------------------------------------- + +class BreakLoops(Exception): + ''' + This class is used to break out of nested loops + ''' + + pass + +#------------------------------------------------------------------------------- + +if __name__ == '__main__': + print('This file contains the general functions and classes of the ddRADseqTools software package.') + sys.exit(0) + +#------------------------------------------------------------------------------- +","Python" +"In Silico","GGFHF/ddRADseqTools","Package/indsdemultiplexing.py",".py","29476","655","#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +#------------------------------------------------------------------------------- + +'''This software has been developed by: + + GI Genética, Fisiología e Historia Forestal + Dpto. Sistemas y Recursos Naturales + ETSI Montes, Forestal y del Medio Natural + Universidad Politécnica de Madrid + https://github.com/ggfhf/ + + Licence: GNU General Public Licence Version 3 +''' + +#------------------------------------------------------------------------------- + +'''This source contains the program of the ddRADseqTools software package that + demultiplexes 1 file (SE) / 2 files (PE) with reads of n individuals in + n files (SE) / 2n file (PE) containing the reads of each individual. +''' +#------------------------------------------------------------------------------- + +import os.path +import sys + +from genlib import * + +#------------------------------------------------------------------------------- + +def main(argv): + '''Main line of the program.''' + + # build the options dictionary + options_dict = build_options() + + # it has been requested the help or to build a new config file + for param in argv: + # show the help and exit OK + if param.startswith('--help'): + print_help(options_dict) + sys.exit(0) + # build the config file and exit OK + elif param.startswith('--config'): + build_config(options_dict) + sys.exit(0) + + # get the config file + config_file = get_config_file(__file__) + + # get options from the config file and the input parameters + options_dict = get_options(options_dict, config_file, argv) + + # demultiplex individuals + demutiplex_individuals(options_dict) + +#------------------------------------------------------------------------------- + +def demutiplex_individuals(options_dict): + '''Demutiplex individuals of the file(s) with reads of a double digest RADseq saving each one in a specific file.''' + + technique = options_dict['technique']['value'] + format = options_dict['format']['value'] + readtype = options_dict['readtype']['value'] + endsfile = options_dict['endsfile']['value'] + index1len = options_dict['index1len']['value'] + index2len = options_dict['index2len']['value'] + dbrlen = options_dict['dbrlen']['value'] + wend = options_dict['wend']['value'] + cend = options_dict['cend']['value'] + individualsfile = options_dict['individualsfile']['value'] + readsfile1 = options_dict['readsfile1']['value'] + readsfile2 = options_dict['readsfile2']['value'] + verbose = options_dict['verbose']['value'] + trace = options_dict['trace']['value'] + + # set the verbose and trace status + if verbose.upper() == 'YES': + Message.set_verbose_status(True) + else: + Message.set_verbose_status(False) + if trace.upper() == 'YES': + Message.set_trace_status(True) + else: + Message.set_trace_status(False) + + # assign the symbol of the indexes and the DBR + (index1_symbol, index2_symbol, dbr_symbol) = get_symbols() + + # get the end sequences and the DBR strand + (wend_seq, cend_seq, dbr_strand) = get_ends(endsfile, wend, cend, technique, index1len, index1_symbol, index2len, index2_symbol, dbrlen, dbr_symbol) + Message.print('trace', 'wend_seq: {0}'.format(wend_seq)) + Message.print('trace', 'cend_seq: {0}'.format(cend_seq)) + Message.print('trace', 'dbr_strand: {0}'.format(dbr_strand)) + + # get the index1 start position in the wend_seq + index1_start = wend_seq.find(index1_symbol * index1len) + Message.print('trace', 'index1 start: {0}'.format(index1_start)) + + # get the index2 start position in the cend_seq + index2_final = cend_seq.find(index2_symbol * index2len) + Message.print('trace', 'index2 final: {0}'.format(index2_final)) + + # get the individuals data dictionary + individuals_dict = get_individuals(individualsfile, technique) + Message.print('trace', 'individuals_dict: {0}'.format(individuals_dict)) + + # get the extension of the individuals file + extension = '.fasta' if format == 'FASTA' else '.fastq' + + # add the file(s) information of each individual in the individuals dictionary + for individual_key, individual_data in individuals_dict.items(): + individual_file_1 = get_directory(readsfile1) + 'demultiplexed-' + individual_data['individual_id'] + '-1' + extension + individuals_dict[individual_key]['individual_file_1'] = individual_file_1 + if readtype == 'PE': + individual_file_2 = get_directory(readsfile2) + 'demultiplexed-' + individual_data['individual_id'] + '-2' + extension + individuals_dict[individual_key]['individual_file_2'] = individual_file_2 + + # add the file(s) to manage errors in the individuals dictionary + individual_key = 'ERRORS' + individuals_dict[individual_key] = {} + individual_file_1 = get_directory(readsfile1) + 'demultiplexed-errors-1' + extension + individuals_dict[individual_key]['individual_file_1'] = individual_file_1 + if readtype == 'PE': + individual_file_2 = get_directory(readsfile2) + 'demultiplexed-errors-2' + extension + individuals_dict[individual_key]['individual_file_2'] = individual_file_2 + + # open the file(s) with reads of a double digest RADseq + try: + readsfile1_id = open(readsfile1, mode='r', encoding='iso-8859-1') + except: + raise ProgramError('F002', readsfile1) + if readtype == 'PE': + try: + readsfile2_id = open(readsfile2, mode='r', encoding='iso-8859-1') + except: + raise ProgramError('F002', readsfile2) + + # open the individual files + try: + for individual_key, individual_data in individuals_dict.items(): + individual_file_1 = individual_data['individual_file_1'] + individual_file_1_id = open(individual_file_1, mode='w', encoding='iso-8859-1') + individuals_dict[individual_key]['individual_file_1_id'] = individual_file_1_id + except: + raise ProgramError('F002', individual_file_1) + if readtype == 'PE': + try: + for individual_key, individual_data in individuals_dict.items(): + individual_file_2 = individual_data['individual_file_2'] + individual_file_2_id = open(individual_file_2, mode='w', encoding='iso-8859-1') + individuals_dict[individual_key]['individual_file_2_id'] = individual_file_2_id + except: + raise ProgramError('F002', individual_file_2) + + # initialize the count of reads + reads_count = 0 + + # if the readsfile format is FASTA + if format == 'FASTA': + + # set the pattern of the head records (>read_info) + pattern = r'^>(.*)$' + + # if readtype is SE + if readtype == 'SE': + + # read the first record of readsfile1 + record1 = readsfile1_id.readline() + + # while there are records in readsfile1 + while record1 != '': + + # process the head record of readsfile1 + if record1.startswith('>'): + + # extract the data + mo = re.search(pattern, record1) + info1 = mo.group(1).strip() + + # initialize the sequence + seq1 = '' + + # read the next record of readsfile1 + record1 = readsfile1_id.readline() + + else: + + # control the FASTA format + raise ProgramError('F003', readsfile1, 'FASTA') + + # while there are records in readfile1 and they are sequence + while record1 != '' and not record1.startswith('>'): + + # add the record to the sequence + seq1 += record1.strip() + + # read the next record of readsfile1 + record1 = readsfile1_id.readline() + + # search the index1 + index1 = seq1[index1_start:(index1_start + index1len)] + + # search the index2 + if technique == ['IND1', 'IND1_DBR', 'IND1_IND2', 'IND1_IND2_DBR']: + pass + + # compose the individual key + if technique in ['IND1', 'IND1_DBR']: + individual_key = index1.upper() + elif technique in ['IND1_IND2', 'IND1_IND2_DBR']: + individual_key = 'ERRORS' + Message.print('trace', 'individual_key: {0}'.format(individual_key)) + + # get the individual_file_id + individual_data = individuals_dict.get(individual_key, individuals_dict['ERRORS']) + individual_file_1_id = individual_data['individual_file_1_id'] + + # write read in individual file + individual_file_1_id.write('>{0}\n'.format(info1)) + individual_file_1_id.write('{0}\n'.format(seq1)) + + # notify the reads have been processed + reads_count += 1 + Message.print('verbose', '\rProcessed reads: {0:9d}'.format(reads_count)) + + # if readtype is PE + if readtype == 'PE': + + # read the first record of readsfile1 and readsfile2 + record1 = readsfile1_id.readline() + record2 = readsfile2_id.readline() + + # while there are records in readsfile1 and readsfile2 + while record1 != '' and record2 != '': + + # process the head record of readsfile1 + if record1.startswith('>'): + + # extract the data + mo = re.search(pattern, record1) + info1 = mo.group(1).strip() + + # initialize the sequence + seq1 = '' + + # read the next record of readsfile2 + record1 = readsfile1_id.readline() + + else: + + # control the FASTA format + raise ProgramError('F003', readsfile1, 'FASTA') + + # while there are records in readfile1 and they are sequence + while record1 != '' and not record1.startswith('>'): + + # add the record to the sequence + seq1 += record1.strip() + + # read the next record of readsfile1 + record1 = readsfile1_id.readline() + + # process the head record of readsfile2 + if record2.startswith('>'): + + # extract the data + mo = re.search(pattern, record2) + info2 = mo.group(1).strip() + + # initialize the sequence + seq2 = '' + + # read the next record of readsfile2 + record2 = readsfile2_id.readline() + + else: + + # control the FASTA format + raise ProgramError('F003', readsfile2, 'FASTA') + + # while there are records in readfile2 and they are sequence + while record2 != '' and not record2.startswith('>'): + + # add the record to the sequence + seq2 += record2.strip() + + # read the next record of readsfile2 + record2 = readsfile2_id.readline() + + # search the index1 + index1 = seq1[index1_start:(index1_start + index1len)] + + # search the index2 + if technique in ['IND1', 'IND1_DBR']: + pass + elif technique in ['IND1_IND2', 'IND1_IND2_DBR']: + index2 = seq2[index2_final:(index2_final + index2len)] + + # compose the individual key + if technique in ['IND1', 'IND1_DBR']: + individual_key = index1.upper() + elif technique in ['IND1_IND2', 'IND1_IND2_DBR']: + individual_key = '{0}-{1}'.format(index1.upper(), index2.upper()) + Message.print('trace', 'individual_key: {0}'.format(individual_key)) + + # get the individual_file_id + individual_data = individuals_dict.get(individual_key, individuals_dict['ERRORS']) + individual_file_1_id = individual_data['individual_file_1_id'] + individual_file_2_id = individual_data['individual_file_2_id'] + + # write read in individual files + individual_file_1_id.write('>{0}\n'.format(info1)) + individual_file_1_id.write('{0}\n'.format(seq1)) + individual_file_2_id.write('>{0}\n'.format(info2)) + individual_file_2_id.write('{0}\n'.format(seq2)) + + # notify the reads have been processed + reads_count += 1 + Message.print('verbose', '\rProcessed reads: {0:9d}'.format(reads_count)) + + # control there are not records in readsfile1 and readsfile2 + if record1 != '' or record2 != '': + raise ProgramError('L003', readsfile1, readsfile2) + + # if the inputfile format is FASTQ + elif format == 'FASTQ': + + # set the pattern of the head records (@read_info) + pattern = r'^@(.*)$' + + # if readtype is SE + if readtype == 'SE': + + # read the first record of readsfile1 + record1 = readsfile1_id.readline() + + # while there are records in readsfile1 + while record1 != '': + + # process the head record of readsfile1 + if record1.startswith('@'): + # extract the data + mo = re.search(pattern, record1) + info1 = mo.group(1).strip() + else: + # control the FASTQ format + raise ProgramError('F003', readsfile1, 'FASTQ') + + # read next record of readsfile1 and verify record of sequence + record1 = readsfile1_id.readline() + if record1 == '': + # control the FASTQ format + raise ProgramError('F003', readsfile1, 'FASTQ') + + # assign the sequence + seq1 = record1.strip() + + # read next record of readsfile1 and verify record of plus + record1 = readsfile1_id.readline() + if not record1.startswith('+'): + # control the FASTQ format + raise ProgramError('F003', readsfile1, 'FASTQ') + + # read next record of readsfile1 and verify record of quality + record1 = readsfile1_id.readline() + if record1 == '': + # control the FASTQ format + raise ProgramError('F003', readsfile1, 'FASTQ') + + # assign the quality + quality1 = record1.strip() + + # search the codebar + index1 = seq1[index1_start:(index1_start + index1len)] + + # search the index2 + if technique == ['IND1', 'IND_DBR', 'IND1_IND2', 'IND1_IND2_DBR']: + pass + + # compose the individual key + if technique in ['IND1', 'IND1_DBR']: + individual_key = index1.upper() + elif technique in ['IND1_IND2', 'IND1_IND2_DBR']: + individual_key = 'ERRORS' + Message.print('trace', 'individual_key: {0}'.format(individual_key)) + + # get the individual_file_id + individual_data = individuals_dict.get(individual_key, individuals_dict['ERRORS']) + individual_file_1_id = individual_data['individual_file_1_id'] + + # write read in individual file + individual_file_1_id.write('@{0}\n'.format(info1)) + individual_file_1_id.write('{0}\n'.format(seq1)) + individual_file_1_id.write('+\n') + individual_file_1_id.write('{0}\n'.format(quality1)) + + # notify the reads have been processed + reads_count += 1 + Message.print('verbose', '\rProcessed reads: {0:9d}'.format(reads_count)) + + # read the next record of readsfile1 + record1 = readsfile1_id.readline() + + # if readtype is PE + if readtype == 'PE': + + # read the first record of readsfile1 and readsfile2 + record1 = readsfile1_id.readline() + record2 = readsfile2_id.readline() + + # while there are records in readsfile1 and readsfile2 + while record1 != '' and record2 != '': + + # process the head record of readsfile1 + if record1.startswith('@'): + # extract the data + mo = re.search(pattern, record1) + info1 = mo.group(1).strip() + else: + # control the FASTQ format + raise ProgramError('F003', readsfile1, 'FASTQ') + + # read next record of readsfile1 and verify record of sequence + record1 = readsfile1_id.readline() + if record1 == '': + # control the FASTQ format + raise ProgramError('F003', readsfile1, 'FASTQ') + + # assign the sequence + seq1 = record1.strip() + + # read next record of readsfile1 and verify record of plus + record1 = readsfile1_id.readline() + if not record1.startswith('+'): + # control the FASTQ format + raise ProgramError('F003', readsfile1, 'FASTQ') + + # read next record of readsfile1 and verify record of quality + record1 = readsfile1_id.readline() + if record1 == '': + # control the FASTQ format + raise ProgramError('F003', readsfile1, 'FASTQ') + + # assign the quality + quality1 = record1.strip() + + # process the head record of readsfile2 + if record2.startswith('@'): + # extract the data + mo = re.search(pattern, record2) + info2 = mo.group(1).strip() + else: + # control the FASTQ format + raise ProgramError('F003', readsfile2, 'FASTQ') + + # read next record of readsfile2 and verify record of sequence + record2 = readsfile2_id.readline() + if record2 == '': + # control the FASTQ format + raise ProgramError('F003', readsfile2, 'FASTQ') + + # assign the sequence + seq2 = record2.strip() + + # read next record of readsfile2 and verify record of plus + record2 = readsfile2_id.readline() + if not record2.startswith('+'): + # control the FASTQ format + raise ProgramError('F003', readsfile2, 'FASTQ') + + # read next record of readsfile2 and verify record of quality + record2 = readsfile2_id.readline() + if record2 == '': + # control the FASTQ format + raise ProgramError('F003', readsfile2, 'FASTQ') + + # assign the quality + quality2 = record2.strip() + + # search the codebar + index1 = seq1[index1_start:(index1_start + index1len)] + + # search the index2 + if technique in ['IND1', 'IND1_DBR']: + pass + elif technique in ['IND1_IND2', 'IND1_IND2_DBR']: + index2 = seq2[index2_final:(index2_final + index2len)] + + # compose the individual_key + if technique in ['IND1', 'IND1_DBR']: + individual_key = index1.upper() + elif technique in ['IND1_IND2', 'IND1_IND2_DBR']: + individual_key = '{0}-{1}'.format(index1.upper(), index2.upper()) + Message.print('trace', 'individual_key: {0}'.format(individual_key)) + + # get the individual_file_id + individual_data = individuals_dict.get(individual_key, individuals_dict['ERRORS']) + individual_file_1_id = individual_data['individual_file_1_id'] + individual_file_2_id = individual_data['individual_file_2_id'] + + # write read in individual files + individual_file_1_id.write('@{0}\n'.format(info1)) + individual_file_1_id.write('{0}\n'.format(seq1)) + individual_file_1_id.write('+\n') + individual_file_1_id.write('{0}\n'.format(quality1)) + individual_file_2_id.write('@{0}\n'.format(info2)) + individual_file_2_id.write('{0}\n'.format(seq2)) + individual_file_2_id.write('+\n') + individual_file_2_id.write('{0}\n'.format(quality2)) + + # notify the reads have been processed + reads_count += 1 + Message.print('verbose', '\rProcessed reads: {0:9d}'.format(reads_count)) + + # read the next record of readsfile1 and readsfile2 + record1 = readsfile1_id.readline() + record2 = readsfile2_id.readline() + + # control there are not records in readsfile1 and readsfile2 + if record1 != '' or record2 != '': + raise ProgramError('L003', readsfile1, readsfile2) + + # close files + for individual_key, individual_data in individuals_dict.items(): + individual_file_1_id = individual_data['individual_file_1_id'] + individual_file_1_id.close() + if readtype == 'PE': + individual_file_2_id = individual_data['individual_file_2_id'] + individual_file_2_id.close() + + # show OK message + Message.print('verbose', '\n') + if readtype == 'SE': + Message.print('info', 'The files {0}_{1} containing the individuals data are created.'.format(get_file_name_noext(readsfile1), extension)) + elif readtype == 'PE': + Message.print('info', 'The files {0}-{2} and {1}-{2} containing the individuals data are created.'.format(get_file_name_noext(readsfile1), get_file_name_noext(readsfile2), extension)) + +#------------------------------------------------------------------------------- + +def build_options(): + '''Build a dictionary with the program options.''' + + # get all options dictionary + all_options_dict = get_all_options_dict() + + # define the options dictionary + options_dict = { + 'technique': all_options_dict['technique'], + 'format': all_options_dict['format'], + 'readtype': all_options_dict['readtype'], + 'endsfile': all_options_dict['endsfile'], + 'index1len': all_options_dict['index1len'], + 'index2len': all_options_dict['index2len'], + 'dbrlen': all_options_dict['dbrlen'], + 'wend': all_options_dict['wend'], + 'cend': all_options_dict['cend'], + 'individualsfile': all_options_dict['individualsfile'], + 'readsfile1': all_options_dict['readsfile1'], + 'readsfile2': all_options_dict['readsfile2'], + 'verbose': all_options_dict['verbose'], + 'trace': all_options_dict['trace'] + } + + # return the options dictionary + return options_dict + +#------------------------------------------------------------------------------- + +def print_help(options_dict): + '''Print the program help.''' + + # get general data + project_name = get_project_name() + project_version = get_project_version() + program_file = get_file_name(__file__) + config_file = get_config_file(__file__) + + # print the help + Message.print('info', '') + Message.print('info', '{0} version {1}'.format(project_name, project_version)) + Message.print('info', '') + Message.print('info', '{0} ...'.format(program_file)) + Message.print('info', '') + Message.print('info', 'Usage: {0} --help'.format(program_file)) + Message.print('info', '') + Message.print('info', ' Show the help of {0}.'.format(program_file)) + Message.print('info', '') + Message.print('info', ' or: {0} --config'.format(program_file)) + Message.print('info', '') + Message.print('info', ' Create the config file {0} with the default value of the options.'.format(config_file)) + Message.print('info', ' The default value of the options can be modified.'.format(config_file)) + Message.print('info', '') + Message.print('info', ' or: {0} [--option= [--option=, ...]]'.format(program_file)) + Message.print('info', '') + Message.print('info', ' The options values are read from the config file {0}, but they can be'.format(config_file)) + Message.print('info', ' modified in command line. The options are:') + Message.print('info', '') + Message.print('info', ' {0:17} {1}'.format('option', 'value')) + Message.print('info', ' {0:17} {1}'.format('=' * 13, '=' * 95)) + Message.print('info', ' {0:17} {1}'.format('--technique', options_dict['technique']['comment'])) + Message.print('info', ' {0:17} {1}'.format('--format', options_dict['format']['comment'])) + Message.print('info', ' {0:17} {1}'.format('--readtype', options_dict['readtype']['comment'])) + Message.print('info', ' {0:17} {1}'.format('--endsfile', options_dict['endsfile']['comment'])) + Message.print('info', ' {0:17} {1}'.format('--index1len', options_dict['index1len']['comment'])) + Message.print('info', ' {0:17} {1}'.format('--index2len', options_dict['index2len']['comment'])) + Message.print('info', ' {0:17} {1}'.format('--dbrlen', options_dict['dbrlen']['comment'])) + Message.print('info', ' {0:17} {1}'.format('--wend', options_dict['wend']['comment'])) + Message.print('info', ' {0:17} {1}'.format('--cend', options_dict['cend']['comment'])) + Message.print('info', ' {0:17} {1}'.format('--individualsfile', options_dict['individualsfile']['comment'])) + Message.print('info', ' {0:17} {1}'.format('--readsfile1', options_dict['readsfile1']['comment'])) + Message.print('info', ' {0:17} {1}'.format('--readsfile2', options_dict['readsfile2']['comment'])) + Message.print('info', ' {0:17} {1}'.format('--verbose', options_dict['verbose']['comment'])) + Message.print('info', ' {0:17} {1}'.format('--trace', options_dict['trace']['comment'])) + +#------------------------------------------------------------------------------- + +def build_config(options_dict): + '''Build the file with the options by default.''' + + # get the config file + config_file = get_config_file(__file__) + + # create the config file and write the default options + try: + with open(config_file, mode='w', encoding='iso-8859-1') as config_file_id: + config_file_id.write('{0:37} # {1}\n'.format('technique' + '=' + options_dict['technique']['default'], options_dict['technique']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('format' + '=' + options_dict['format']['default'], options_dict['format']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('readtype' + '=' + options_dict['readtype']['default'], options_dict['readtype']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('endsfile' + '=' + options_dict['endsfile']['default'], options_dict['endsfile']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('index1len' + '=' + options_dict['index1len']['default'], options_dict['index1len']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('index2len' + '=' + options_dict['index2len']['default'], options_dict['index2len']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('dbrlen' + '=' + options_dict['dbrlen']['default'], options_dict['dbrlen']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('wend' + '=' + options_dict['wend']['default'], options_dict['wend']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('cend' + '=' + options_dict['cend']['default'], options_dict['cend']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('individualsfile' + '=' + options_dict['individualsfile']['default'], options_dict['individualsfile']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('readsfile1' + '=' + options_dict['readsfile1']['default'], options_dict['readsfile1']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('readsfile2' + '=' + options_dict['readsfile2']['default'], options_dict['readsfile2']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('verbose' + '=' + options_dict['verbose']['default'], options_dict['verbose']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('trace' + '=' + options_dict['trace']['default'], options_dict['trace']['comment'])) + except: + raise ProgramError('F001', config_file) + + # show OK message + Message.print('info', 'The configuration file {0} has been created.'.format(get_file_name(config_file))) + +#------------------------------------------------------------------------------- + +if __name__ == '__main__': + main(sys.argv[1:]) + sys.exit(0) + +#------------------------------------------------------------------------------- +","Python" +"In Silico","GGFHF/ddRADseqTools","Package/fragsgeneration.py",".py","13757","273","#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +#------------------------------------------------------------------------------- + +'''This software has been developed by: + + GI Genética, Fisiología e Historia Forestal + Dpto. Sistemas y Recursos Naturales + ETSI Montes, Forestal y del Medio Natural + Universidad Politécnica de Madrid + https://github.com/ggfhf/ + + Licence: GNU General Public Licence Version 3 +''' + +#------------------------------------------------------------------------------- + +'''This source contains the program of the ddRADseqTools software package that + generates randomly fragments simulating a double digestion and saves them in + a file in FASTA format. +''' +#------------------------------------------------------------------------------- + +import random +import sys + +from genlib import * + +#------------------------------------------------------------------------------- + +def main(argv): + '''Main line of the program.''' + + # build the options dictionary + options_dict = build_options() + + # it has been requested the help or to build a new config file + for param in argv: + # show the help and exit OK + if param.startswith('--help'): + print_help(options_dict) + sys.exit(0) + # build the config file and exit OK + elif param.startswith('--config'): + build_config(options_dict) + sys.exit(0) + + # get the config file + config_file = get_config_file(__file__) + + # get options from the config file and the input parameters + options_dict = get_options(options_dict, config_file, argv) + + # generate randomly fragments and save them in a file in FASTA format + generate_fragments(options_dict) + +#------------------------------------------------------------------------------- + +def generate_fragments(options_dict): + '''Generate randomly fragments ans save them in a file in FASTA format.''' + + fragsfile = options_dict['fragsfile']['value'] + rsfile = options_dict['rsfile']['value'] + enzyme1 = options_dict['enzyme1']['value'] + enzyme2 = options_dict['enzyme2']['value'] + fragsnum = options_dict['fragsnum']['value'] + minfragsize = options_dict['minfragsize']['value'] + maxfragsize = options_dict['maxfragsize']['value'] + fragstfile = options_dict['fragstfile']['value'] + fragstinterval = options_dict['fragstinterval']['value'] + plot = options_dict['plot']['value'] + verbose = options_dict['verbose']['value'] + trace = options_dict['trace']['value'] + + # get the restriction site sequences + (ressite1_seq, ressite1_lcut_seq, ressite1_rcut_seq, ressite2_seq, ressite2_lcut_seq, ressite2_rcut_seq) = get_ressites(rsfile, enzyme1, enzyme2) + Message.print('trace', 'ressite1_seq: {0} - ressite1_lcut_seq: {1} - ressite1_rcut_seq: {2}'.format(ressite1_seq, ressite1_lcut_seq, ressite1_rcut_seq)) + Message.print('trace', 'ressite2_seq: {0} - ressite2_lcut_seq: {1} - ressite2_rcut_seq: {2}'.format(ressite2_seq, ressite2_lcut_seq, ressite2_rcut_seq)) + + # get the restriction_overhangs + if len(ressite1_lcut_seq) >= len(ressite1_rcut_seq): + resoverhang1_seq = get_reverse_complementary_sequence(ressite1_lcut_seq) + else: + resoverhang1_seq = ressite1_rcut_seq + if len(ressite2_lcut_seq) >= len(ressite2_rcut_seq): + resoverhang2_seq = ressite1_lcut_seq + else: + resoverhang2_seq = get_reverse_complementary_sequence(ressite2_rcut_seq) + Message.print('trace', 'resoverhang1_seq: {0}'.format(resoverhang1_seq)) + Message.print('trace', 'resoverhang2_seq: {0}'.format(resoverhang2_seq)) + + # get the list of sequences corresponding to each enzyme + unambiguous_ressite1_seq_list = get_unambiguous_sequence_list(ressite1_seq.upper()) + unambiguous_ressite2_seq_list = get_unambiguous_sequence_list(ressite2_seq.upper()) + Message.print('trace', 'unambiguous_ressite1_seq_list: {0}'.format(unambiguous_ressite1_seq_list)) + Message.print('trace', 'unambiguous_ressite2_seq_list: {0}'.format(unambiguous_ressite2_seq_list)) + + # open the fragments file + try: + fragsfile_id = open(fragsfile, mode='w', encoding='iso-8859-1') + except: + raise ProgramError('F002', fragsfile) + + # initialize the count of written fragments + written_fragments_count = 0 + + # initialize the intervals + intervals_dict = {} + + # initialize the GC distribution + GC_distribution_dict = {} + + # while there are records + while written_fragments_count < fragsnum: + + # add 1 to the count of fragments written + written_fragments_count += 1 + + # get the unambiguous sequences of the restriction sites corresponding to the fragment + unambiguous_ressite1_seq = unambiguous_ressite1_seq_list[random.randrange(0, len(unambiguous_ressite1_seq_list))] + unambiguous_ressite2_seq = unambiguous_ressite2_seq_list[random.randrange(0, len(unambiguous_ressite2_seq_list))] + + # get the sequence of the fragment + fragment_len = random.randrange(minfragsize, maxfragsize + 1) + random_len = fragment_len - len(resoverhang1_seq) - len(resoverhang2_seq) + random_seq = build_random_sequence(random_len, unambiguous_ressite1_seq_list, unambiguous_ressite2_seq_list) + fragment_seq = '{0}{1}{2}'.format(unambiguous_ressite1_seq[len(ressite1_seq)-len(resoverhang1_seq):], random_seq, unambiguous_ressite2_seq[:len(resoverhang2_seq)]) + + # calculate the GC rate and the N count + (GC_rate, N_count) = get_GC_N_data(fragment_seq) + GC_rate_formatted = '{0:3.2f}'.format(GC_rate) + + # write the FASTA head and fragment in the fragments file + fragsfile_id.write('>fragment: {0:d} | length: {1:d} | GC: {2} | locus: fragment generated randomly\n'.format(written_fragments_count, fragment_len, GC_rate_formatted)) + fragsfile_id.write('{0}\n'.format(fragment_seq)) + + # update the GC distribution + GC_distribution_dict[GC_rate_formatted] = GC_distribution_dict.get(GC_rate_formatted, 0) + 1 + + # notify the reads have been written + Message.print('verbose', '\rFragments written: {0:9d}'.format(written_fragments_count)) + + # update the intervals with the fragment length + intervals_dict = update_fragments_intervals(intervals_dict, fragstinterval, fragment_len, N_count) + + # close files + fragsfile_id.close() + + # show OK message + Message.print('verbose', '\n') + Message.print('info', 'The file {0} containing the fragments of the double digest of the genome is created.'.format(get_file_name(fragsfile))) + + # write the statistics and save them in the statistics file + title = 'Distribution of fragments generated randomly' + write_fragments_stats(fragstfile, intervals_dict, written_fragments_count, written_fragments_count, minfragsize, maxfragsize, title) + if plot.upper() == 'YES': + plot_fragments_graphic(fragstfile, intervals_dict, title) + + # write the GC distribution file + write_GC_distribution(fragsfile, GC_distribution_dict) + +#------------------------------------------------------------------------------- + +def build_options(): + '''Build a dictionary with the program options.''' + + # get all options dictionary + all_options_dict = get_all_options_dict() + + # define the options dictionary + options_dict = { + 'fragsfile': all_options_dict['fragsfile'], + 'rsfile': all_options_dict['rsfile'], + 'enzyme1': all_options_dict['enzyme1'], + 'enzyme2': all_options_dict['enzyme2'], + 'enzyme2': all_options_dict['enzyme2'], + 'fragsnum': all_options_dict['fragsnum'], + 'minfragsize': all_options_dict['minfragsize'], + 'maxfragsize': all_options_dict['maxfragsize'], + 'fragstfile': all_options_dict['fragstfile'], + 'fragstinterval': all_options_dict['fragstinterval'], + 'plot': all_options_dict['plot'], + 'verbose': all_options_dict['verbose'], + 'trace': all_options_dict['trace'] + } + + # return the options dictionary + return options_dict + +#------------------------------------------------------------------------------- + +def print_help(options_dict): + '''Print the program help.''' + + # get general data + project_name = get_project_name() + project_version = get_project_version() + program_file = get_file_name(__file__) + config_file = get_config_file(__file__) + + # print the help + Message.print('info', '') + Message.print('info', '{0} version {1}'.format(project_name, project_version)) + Message.print('info', '') + Message.print('info', '{0} generates randomly fragments simulating a double digestion and saves them in a file in FASTA format.'.format(program_file)) + Message.print('info', '') + Message.print('info', 'Usage: {0} --help'.format(program_file)) + Message.print('info', '') + Message.print('info', ' Show the help of {0}.'.format(program_file)) + Message.print('info', '') + Message.print('info', ' or: {0} --config'.format(program_file)) + Message.print('info', '') + Message.print('info', ' Create the config file {0} with the default value of the options.'.format(config_file)) + Message.print('info', ' The default value of the options can be modified.'.format(config_file)) + Message.print('info', '') + Message.print('info', ' or: {0} [--option= [--option=, ...]]'.format(program_file)) + Message.print('info', '') + Message.print('info', ' The options values are read from the config file {0}, but they can be modified'.format(config_file)) + Message.print('info', ' in command line. The options are:') + Message.print('info', '') + Message.print('info', ' {0:16} {1}'.format('option', 'value')) + Message.print('info', ' {0:16} {1}'.format('=' * 16, '=' * 78)) + Message.print('info', ' {0:16} {1}'.format('--fragsfile', options_dict['fragsfile']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--rsfile', options_dict['rsfile']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--enzyme1', options_dict['enzyme1']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--enzyme2', options_dict['enzyme2']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--fragsnum', options_dict['fragsnum']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--minfragsize', options_dict['minfragsize']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--maxfragsize', options_dict['maxfragsize']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--fragstfile', options_dict['fragstfile']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--fragstinterval', options_dict['fragstinterval']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--plot', options_dict['plot']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--verbose', options_dict['verbose']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--trace', options_dict['trace']['comment'])) + +#------------------------------------------------------------------------------- + +def build_config(options_dict): + '''Build the file with the options by default.''' + + # get the config file + config_file = get_config_file(__file__) + + # create the config file and write the default options + try: + with open(config_file, mode='w', encoding='iso-8859-1') as config_file_id: + config_file_id.write('{0:43} # {1}\n'.format('fragsfile' + '=' + options_dict['fragsfile']['default'], options_dict['fragsfile']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('rsfile' + '=' + options_dict['rsfile']['default'], options_dict['rsfile']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('enzyme1' + '=' + options_dict['enzyme1']['default'], options_dict['enzyme1']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('enzyme2' + '=' + options_dict['enzyme2']['default'], options_dict['enzyme2']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('fragsnum' + '=' + options_dict['fragsnum']['default'], options_dict['fragsnum']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('minfragsize' + '=' + options_dict['minfragsize']['default'], options_dict['minfragsize']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('maxfragsize' + '=' + options_dict['maxfragsize']['default'], options_dict['maxfragsize']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('fragstfile' + '=' + options_dict['fragstfile']['default'], options_dict['fragstfile']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('fragstinterval' + '=' + options_dict['fragstinterval']['default'], options_dict['fragstinterval']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('plot' + '=' + options_dict['plot']['default'], options_dict['plot']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('verbose' + '=' + options_dict['verbose']['default'], options_dict['verbose']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('trace' + '=' + options_dict['trace']['default'], options_dict['trace']['comment'])) + except: + raise ProgramError('F001', config_file) + + # show OK message + Message.print('info', 'The configuration file {0} is created.'.format(get_file_name(config_file))) + +#------------------------------------------------------------------------------- + +if __name__ == '__main__': + main(sys.argv[1:]) + sys.exit(0) + +#------------------------------------------------------------------------------- +","Python" +"In Silico","GGFHF/ddRADseqTools","Package/simddradseq.py",".py","38050","622","#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +#------------------------------------------------------------------------------- + +'''This software has been developed by: + + GI Genética, Fisiología e Historia Forestal + Dpto. Sistemas y Recursos Naturales + ETSI Montes, Forestal y del Medio Natural + Universidad Politécnica de Madrid + https://github.com/ggfhf/ + + Licence: GNU General Public Licence Version 3 +''' + +#------------------------------------------------------------------------------- + +'''This source contains the program of the ddRADseqTools software package that + builds a file in FASTA/FASTQ format with simulated reads of a double digest + RADseq. +''' +#------------------------------------------------------------------------------- + +import os.path +import random +import re +import sys + +from genlib import * + +#------------------------------------------------------------------------------- + +def main(argv): + '''Main line of the program.''' + + # build the options dictionary + options_dict = build_options() + + # it has been requested the help or to build a new config file + for param in argv: + # show the help and exit OK + if param.startswith('--help'): + print_help(options_dict) + sys.exit(0) + # build the config file and exit OK + elif param.startswith('--config'): + build_config(options_dict) + sys.exit(0) + + # get the config file + config_file = get_config_file(__file__) + + # get options from the config file and the input parameters + options_dict = get_options(options_dict, config_file, argv) + + # build the file with simulated reads + build_reads(options_dict) + +#------------------------------------------------------------------------------- + +def build_reads(options_dict): + '''Build a file in FASTA/FASTQ format with reads gotten from a file containing a double digest RAD-seq fragments.''' + + fragsfile = options_dict['fragsfile']['value'] + technique = options_dict['technique']['value'] + format = options_dict['format']['value'] + readsfile = options_dict['readsfile']['value'] + readtype = options_dict['readtype']['value'] + rsfile = options_dict['rsfile']['value'] + enzyme1 = options_dict['enzyme1']['value'] + enzyme2 = options_dict['enzyme2']['value'] + endsfile = options_dict['endsfile']['value'] + index1len = options_dict['index1len']['value'] + index2len = options_dict['index2len']['value'] + dbrlen = options_dict['dbrlen']['value'] + wend = options_dict['wend']['value'] + cend = options_dict['cend']['value'] + individualsfile = options_dict['individualsfile']['value'] + locinum = options_dict['locinum']['value'] + readsnum = options_dict['readsnum']['value'] + minreadvar = options_dict['minreadvar']['value'] + maxreadvar = options_dict['maxreadvar']['value'] + insertlen = options_dict['insertlen']['value'] + mutprob = options_dict['mutprob']['value'] + locusmaxmut = options_dict['locusmaxmut']['value'] + indelprob = options_dict['indelprob']['value'] + maxindelsize = options_dict['maxindelsize']['value'] + dropout = options_dict['dropout']['value'] + pcrdupprob = options_dict['pcrdupprob']['value'] + pcrdistribution = options_dict['pcrdistribution']['value'] + multiparam = options_dict['multiparam']['value'] + poissonparam = options_dict['poissonparam']['value'] + gcfactor = options_dict['gcfactor']['value'] + verbose = options_dict['verbose']['value'] + trace = options_dict['trace']['value'] + + # set the verbose and trace status + if verbose.upper() == 'YES': + Message.set_verbose_status(True) + else: + Message.set_verbose_status(False) + if trace.upper() == 'YES': + Message.set_trace_status(True) + else: + Message.set_trace_status(False) + + # assign the symbol of the indexes and the DBR + (index1_symbol, index2_symbol, dbr_symbol) = get_symbols() + + # get the restriction site sequences + (ressite1_seq, ressite1_lcut_seq, ressite1_rcut_seq, ressite2_seq, ressite2_lcut_seq, ressite2_rcut_seq) = get_ressites(rsfile, enzyme1, enzyme2) + Message.print('trace', 'ressite1_seq: {0} - ressite1_lcut_seq: {1} - ressite1_rcut_seq: {2}'.format(ressite1_seq, ressite1_lcut_seq, ressite1_rcut_seq)) + Message.print('trace', 'ressite2_seq: {0} - ressite2_lcut_seq: {1} - ressite2_rcut_seq: {2}'.format(ressite2_seq, ressite2_lcut_seq, ressite2_rcut_seq)) + + # verify that the sequences of the restriction sites are different (double digest) + if ressite1_seq.upper() == ressite2_seq.upper(): + raise ProgramError('L006', ressite1_seq.upper()) + + # get the length of the restriction sites and the cut restriction sites + ressite1_len = len(ressite1_seq) + cut_ressite1_len = max(len(ressite1_lcut_seq), len(ressite1_rcut_seq)) + ressite2_len = len(ressite2_seq) + cut_ressite2_len = max(len(ressite2_lcut_seq), len(ressite2_rcut_seq)) + Message.print('trace', 'ressite1_len: {0} - cut_ressite1_len: {1} - ressite2_len: {2} - cut_ressite2_len: {3}'.format(ressite1_len, cut_ressite1_len, ressite2_len, cut_ressite2_len)) + + # get the list of unambiguous restriction site sequences corresponding to each enzyme + unambiguous_ressite1_seq_list = get_unambiguous_sequence_list(ressite1_seq.upper()) + unambiguous_ressite2_seq_list = get_unambiguous_sequence_list(ressite2_seq.upper()) + Message.print('trace', 'unambiguous_ressite1_seq_list: {0}'.format(unambiguous_ressite1_seq_list)) + Message.print('trace', 'unambiguous_ressite2_seq_list: {0}'.format(unambiguous_ressite2_seq_list)) + + # get the restriction overhang sequences + if len(ressite1_lcut_seq) >= len(ressite1_rcut_seq): + resoverhang1_seq = get_reverse_complementary_sequence(ressite1_lcut_seq) + else: + resoverhang1_seq = ressite1_rcut_seq + if len(ressite2_lcut_seq) >= len(ressite2_rcut_seq): + resoverhang2_seq = ressite1_lcut_seq + else: + resoverhang2_seq = get_reverse_complementary_sequence(ressite2_rcut_seq) + Message.print('trace', 'resoverhang1_seq: {0} - resoverhang2_seq: {1}'.format(resoverhang1_seq, resoverhang2_seq)) + + # get the length of the restriction overhangs + resoverhang1_len = len(resoverhang1_seq) + resoverhang2_len = len(resoverhang2_seq) + Message.print('trace', 'resoverhang1_len: {0} - resoverhang2_len: {1}'.format(resoverhang1_len, resoverhang2_len)) + + # get the list of unambiguous restriction overhang sequences corresponding to each enzyme + unambiguous_resoverhang1_seq_list = get_unambiguous_sequence_list(resoverhang1_seq.upper()) + unambiguous_resoverhang2_seq_list = get_unambiguous_sequence_list(resoverhang2_seq.upper()) + Message.print('trace', 'unambiguous_resoverhang1_seq_list: {0}'.format(unambiguous_resoverhang1_seq_list)) + Message.print('trace', 'unambiguous_resoverhang2_seq_list: {0}'.format(unambiguous_resoverhang2_seq_list)) + + # get the end sequences and the DBR strand + (wend_seq, cend_seq, dbr_strand) = get_ends(endsfile, wend, cend, technique, index1len, index1_symbol, index2len, index2_symbol, dbrlen, dbr_symbol) + Message.print('trace', 'wend_seq: {0}'.format(wend_seq)) + Message.print('trace', 'cend_seq: {0}'.format(cend_seq)) + Message.print('trace', 'dbr_strand: {0}'.format(dbr_strand)) + + # get the individuals dictionary + individuals_dict = get_individuals(individualsfile, technique) + individuals_num = len(individuals_dict) + Message.print('trace', 'Individuals num: {0}'.format(individuals_num)) + Message.print('trace', 'individuals_dict: {0}'.format(individuals_dict)) + + # get the individuals keys list + individual_keys_list = get_individual_keys(individuals_dict) + + # get the GC distribution list + GC_distribution_file = os.path.splitext(fragsfile)[0] + '-GC-distribution.csv' + GC_distribution_list = get_GC_distribution(GC_distribution_file) + + # get the fragments list + fragments_list = get_fragments_list(fragsfile) + + # open the output file(s) + extention = '.fasta' if format == 'FASTA' else '.fastq' + if readtype == 'SE': + readsfile1 = readsfile + extention + elif readtype == 'PE': + readsfile1 = readsfile + '-1' + extention + readsfile2 = readsfile + '-2' + extention + try: + readsfile1_id = open(readsfile1, mode='w', encoding='iso-8859-1') + except: + raise ProgramError('F002', readsfile1) + if readtype == 'PE': + try: + readsfile2_id = open(readsfile2, mode='w', encoding='iso-8859-1') + except: + raise ProgramError('F002', readsfile2) + + # initialize the count of loci + loci_count = 0 + + # initialize the count of total reads + total_reads_count = 0 + + # for fragments in fragments_lis + for data_fragment in fragments_list: + + # assing fragment data + fragment_num = data_fragment[0] + GC_rate = data_fragment[1] + fragment_seq = data_fragment[2] + order = data_fragment[3] + Message.print('trace', 'order: {0} - fragment_num: {1}'.format(order, fragment_num)) + + # verify the restriction overhang sequences of the locus fragment + if fragment_seq[:resoverhang1_len].upper() not in unambiguous_resoverhang1_seq_list: + raise ProgramError('D304', enzyme1, ""5'"", fragment_num) + if fragment_seq[(len(fragment_seq) - resoverhang2_len):].upper() not in unambiguous_resoverhang2_seq_list: + raise ProgramError('D304', enzyme2, ""3'"", fragment_num) + + # get the unambiguous sequences corresponding to each restriction site + unambiguous_resoverhang1_seq = fragment_seq[:resoverhang1_len] + unambiguous_resoverhang2_seq = fragment_seq[(len(fragment_seq) - resoverhang2_len):] + Message.print('trace', 'unambiguous_resoverhang1_seq: {0} - unambiguous_resoverhang2_seq: {1}'.format(unambiguous_resoverhang1_seq, unambiguous_resoverhang2_seq)) + + # get the sequence of the locus fragment + fragment_seq = fragment_seq[resoverhang1_len:(len(fragment_seq) - resoverhang2_len)] + Message.print('trace', 'fragment_seq: {0}'.format(fragment_seq)) + + # control the fragment sequence lenght is greater o equal to insertlen + if len(fragment_seq) < insertlen: + continue + + # add 1 to the count of loci + loci_count += 1 + + # determine if there are PCR duplicates + pcrdup = arethere_pcrdup(pcrdupprob, GC_rate, GC_distribution_list, gcfactor) + + # there are mutations, get the mutations number and a list with mutated sequences of locus fragment + if mutprob > 0: + + # assign the maximum mutated sequences number (usually 1) + max_mutated_seq_num = 1 # always 1 in this version + + # get the mutations number (between 1 and the maximum mutated sequences number) + mutated_seq_num = random.randrange(1, max_mutated_seq_num + 1) + Message.print('trace', 'The fragment of locus {0} has {1} mutation(s) sequence(s).'.format(loci_count, mutated_seq_num)) + + # initialize the fragment sequences list + mutated_seqs_list = [] + + # append mutated sequences + for i in range(mutated_seq_num): + # -- mutated_seq = mutate_sequence(fragment_seq, indelprob, maxindelsize, locusmaxmut, (resoverhang1_len + len(fragment_seq) + resoverhang2_len), unambiguous_ressite1_seq_list, unambiguous_ressite2_seq_list) + mutated_seq = mutate_sequence(fragment_seq, indelprob, maxindelsize, locusmaxmut, (insertlen - resoverhang1_len - resoverhang2_len), unambiguous_ressite1_seq_list, unambiguous_ressite2_seq_list) + mutated_seqs_list.append(mutated_seq) + Message.print('trace', ' Original sequence : {0}'.format(fragment_seq)) + Message.print('trace', ' Mutated sequence {0} : {1}'.format(i, mutated_seqs_list[i])) + Message.print('trace', ' _123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789_123456789') + + # assign data of both alleles + for individual_key in individual_keys_list: + if individuals_dict[individual_key]['replicated_individual_id'].upper() == 'NONE': + + # allele 1 + if mutprob > random.random(): + random_num = random.randrange(0, max_mutated_seq_num) + individuals_dict[individual_key]['allele1_seq'] = mutated_seqs_list[random_num] + individuals_dict[individual_key]['allele1_ismutated'] = True + individuals_dict[individual_key]['allele1_probability'] = random.uniform(0.25, 0.75) + else: + individuals_dict[individual_key]['allele1_seq'] = fragment_seq + individuals_dict[individual_key]['allele1_ismutated'] = False + individuals_dict[individual_key]['allele1_probability'] = random.uniform(0.25, 0.75) + if dropout > random.random(): + individuals_dict[individual_key]['allele1_isthere_dropout'] = True + else: + individuals_dict[individual_key]['allele1_isthere_dropout'] = False + + # allele 2 + if mutprob > random.random(): + random_num = random.randrange(0, max_mutated_seq_num) + individuals_dict[individual_key]['allele2_seq'] = mutated_seqs_list[random_num] + individuals_dict[individual_key]['allele2_ismutated'] = True + else: + individuals_dict[individual_key]['allele2_seq'] = fragment_seq + individuals_dict[individual_key]['allele2_ismutated'] = False + if dropout > random.random(): + individuals_dict[individual_key]['allele2_isthere_dropout'] = True + else: + individuals_dict[individual_key]['allele2_isthere_dropout'] = False + + # assign the sequences of replicated individuals + for individual_key in individual_keys_list: + replicated_individual_id = individuals_dict[individual_key]['replicated_individual_id'] + if replicated_individual_id.upper() != 'NONE': + for individual_key2, individual_data2 in individuals_dict.items(): + if individual_data2['individual_id'] == replicated_individual_id: + individuals_dict[individual_key]['allele1_seq'] = individuals_dict[individual_key2]['allele1_seq'] + individuals_dict[individual_key]['allele1_ismutated'] = individuals_dict[individual_key2]['allele1_ismutated'] + individuals_dict[individual_key]['allele1_probability'] = individuals_dict[individual_key2]['allele1_probability'] + individuals_dict[individual_key]['allele1_isthere_dropout'] = individuals_dict[individual_key2]['allele1_isthere_dropout'] + individuals_dict[individual_key]['allele2_seq'] = individuals_dict[individual_key2]['allele2_seq'] + individuals_dict[individual_key]['allele2_ismutated'] = individuals_dict[individual_key2]['allele2_ismutated'] + individuals_dict[individual_key]['allele2_isthere_dropout'] = individuals_dict[individual_key2]['allele2_isthere_dropout'] + break + + # there are not mutations + else: + + # assign the locus sequence to both alleles + for individual_key in individual_keys_list: + individuals_dict[individual_key]['allele1_seq'] = fragment_seq + individuals_dict[individual_key]['allele1_ismutated'] = False + individuals_dict[individual_key]['allele1_isthere_dropout'] = False + individuals_dict[individual_key]['allele1_probability'] = 1 + individuals_dict[individual_key]['allele2_seq'] = fragment_seq + individuals_dict[individual_key]['allele2_ismutated'] = False + individuals_dict[individual_key]['allele2_isthere_dropout'] = False + + # calculate reads number of this locus + locus_reads_num = calculate_locus_reads_number(readsnum, minreadvar, maxreadvar, locinum) + + # initialize the locus reads count + locus_reads_count = 0 + + #for locus_reads_count in range(1, locus_reads_num + 1): + while (True): + + # get the indivual key of this read + while True: + individual_key = individual_keys_list[random.randrange(0, individuals_num)] + random_number = random.random() + if individuals_dict[individual_key]['allele1_probability'] > random_number: + if not individuals_dict[individual_key]['allele1_isthere_dropout']: + allele = 1 + break + else: + if not individuals_dict[individual_key]['allele2_isthere_dropout']: + allele = 2 + break + + # get data of the individual + individual_id = individuals_dict[individual_key]['individual_id'] + individual_index1_seq = individuals_dict[individual_key]['index1_seq'] + individual_index2_seq = individuals_dict[individual_key]['index2_seq'] + individual_allele1_probability = individuals_dict[individual_key]['allele1_probability'] + if allele == 1: + individual_allele_seq = individuals_dict[individual_key]['allele1_seq'] + individual_allele_ismutated = individuals_dict[individual_key]['allele1_ismutated'] + Message.print('trace', ' Individual: {0:11} - Prob. allele 1: {1:5f} - Random number: {2:5f} - 1er allele - is mutated?: {3:5} - seq: {4}'.format(individual_id, individual_allele1_probability, random_number, 'True' if individual_allele_ismutated else 'False', individual_allele_seq)) + else: + individual_allele_seq = individuals_dict[individual_key]['allele2_seq'] + individual_allele_ismutated = individuals_dict[individual_key]['allele2_ismutated'] + Message.print('trace', ' Individual: {0:11} - Prob. allele 2: {1:5f} - Random number: {2:5f} - 2nd allele - is mutated?: {3:5} - seq: {4}'.format(individual_id, (1 - individual_allele1_probability), random_number, 'True' if individual_allele_ismutated else 'False', individual_allele_seq)) + + # attach the index1 in the 5' end sequence of the Watson strand + merged_wend_seq = merge_sequence(wend_seq, index1_symbol * index1len, individual_index1_seq) + + # attach the index2 in the 5' end sequence of the Crick strand + if technique in ['IND1', 'IND1_DBR']: + merged_cend_seq = cend_seq + elif technique in ['IND1_IND2', 'IND1_IND2_DBR']: + merged_cend_seq = merge_sequence(cend_seq, index2_symbol * index2len, individual_index2_seq) + + # get the degenerate nucleotides to indentify the PCR duplicates and attach it at the end sequence of Crick strand + if technique in ['IND1', 'IND1_IND2']: + pass + elif technique in ['IND1_DBR', 'IND1_IND2_DBR']: + dbr_seq = generate_sequence(dbrlen).lower() + if dbr_strand == 'WEND': + merged_wend_seq = merge_sequence(merged_wend_seq, dbr_symbol * dbrlen, dbr_seq) + elif dbr_strand == 'CEND': + merged_cend_seq = merge_sequence(merged_cend_seq, dbr_symbol * dbrlen, dbr_seq) + + # build the complete read sequence of the Watson strand + watson_strand_seq = merged_wend_seq + unambiguous_resoverhang1_seq + individual_allele_seq[:insertlen - resoverhang1_len:] + Message.print('trace', 'watson_strand_seq: {0}'.format(watson_strand_seq)) + + # if readtype is PE, build the complete read sequence of the Crick strand + if readtype == 'PE': + crick_strand_seq = merged_cend_seq + get_reverse_complementary_sequence(unambiguous_resoverhang2_seq) + get_reverse_complementary_sequence(individual_allele_seq)[:insertlen - resoverhang2_len] + Message.print('trace', 'crick_strand_seq: {0}'.format(crick_strand_seq)) + + # get the PCR duplicates number + pcrdup_num = calculate_pcrdup_num(pcrdup, pcrdistribution, multiparam, poissonparam) + + # write the records and its possible PCR duplicates + for i in range(pcrdup_num + 1): + + # add 1 to the count of total reads + total_reads_count += 1 + + # add 1 to the locus reads count + locus_reads_count += 1 + + # write the record of watson strand sequence and its possible PCR duplicates records in the second output file + if format == 'FASTA': + readsfile1_id.write('>read: {0} | locus: {1} | read in locus: {2} | fragment: {3} | mutated: {4} | individual: {5} | index1: {6} | index2: {7}\n'.format(total_reads_count, loci_count, locus_reads_count, fragment_num, individual_allele_ismutated, individual_id, individual_index1_seq, individual_index2_seq)) + readsfile1_id.write('{0}\n'.format(watson_strand_seq)) + elif format == 'FASTQ': + readsfile1_id.write('@read: {0} | locus: {1} | read in locus: {2} | fragment: {3} | mutated: {4} | individual: {5} | index1: {6} | index2: {7}\n'.format(total_reads_count, loci_count, locus_reads_count, fragment_num, individual_allele_ismutated, individual_id, individual_index1_seq, individual_index2_seq)) + readsfile1_id.write('{0}\n'.format(watson_strand_seq)) + readsfile1_id.write('+\n') + quality = generate_quality(len(watson_strand_seq)) + readsfile1_id.write('{0}\n'.format(quality)) + + # if readtype is PE, write record in the second output file with the reversed complementary sequence + if readtype == 'PE': + + # write the record of crick strand sequence and its possible PCR duplicates records in the second output file + if format == 'FASTA': + readsfile2_id.write('>read: {0} | locus: {1} | read in locus: {2} | fragment: {3} | mutated: {4} | individual: {5} | index1: {6} | index2: {7}\n'.format(total_reads_count, loci_count, locus_reads_count, fragment_num, individual_allele_ismutated, individual_id, individual_index1_seq, individual_index2_seq)) + readsfile2_id.write('{0}\n'.format(crick_strand_seq)) + elif format == 'FASTQ': + readsfile2_id.write('@read: {0} | locus: {1} | read in locus: {2} | fragment: {3} | mutated: {4} | individual: {5} | index1: {6} | index2: {7}\n'.format(total_reads_count, loci_count, locus_reads_count, fragment_num, individual_allele_ismutated, individual_id, individual_index1_seq, individual_index2_seq)) + readsfile2_id.write('{0}\n'.format(crick_strand_seq)) + readsfile2_id.write('+\n') + quality = generate_quality(len(crick_strand_seq)) + readsfile2_id.write('{0}\n'.format(quality)) + + # notify the reads have been written + Message.print('verbose', '\rSimulated sequences reads written: {0:9d}'.format(total_reads_count)) + + # exit of for i when the readsnum has been achieved + if total_reads_count >= readsnum: + break + + # exit of for i when the reads number of this locus has been achieved + if locus_reads_count >= locus_reads_num: + break + + # exit of while True when the readsnum has been achieved + if total_reads_count >= readsnum: + break + + # exit of while True when the reads number of this locus has been achieved + if locus_reads_count >= locus_reads_num: + break + + # exit of for data_fragments when the readsnum has been achieved + if total_reads_count >= readsnum: + break + + # close reads files + readsfile1_id.close() + if readtype == 'PE': + readsfile2_id.close() + + # show OK message + Message.print('verbose', '\n') + if readtype == 'SE': + Message.print('info', 'The file {0} containing the simulated sequences is created.'.format(get_file_name(readsfile1))) + elif readtype == 'PE': + Message.print('info', 'The files {0} and {1} containing the simulated sequences are created.'.format(get_file_name(readsfile1), get_file_name(readsfile2))) + +#------------------------------------------------------------------------------- + +def build_options(): + '''Build a dictionary with the program options.''' + + # get all options dictionary + all_options_dict = get_all_options_dict() + + # define the options dictionary + options_dict = { + 'fragsfile': all_options_dict['fragsfile'], + 'technique': all_options_dict['technique'], + 'format': all_options_dict['format'], + 'readsfile': all_options_dict['readsfile'], + 'readtype': all_options_dict['readtype'], + 'rsfile': all_options_dict['rsfile'], + 'enzyme1': all_options_dict['enzyme1'], + 'enzyme2': all_options_dict['enzyme2'], + 'endsfile': all_options_dict['endsfile'], + 'index1len': all_options_dict['index1len'], + 'index2len': all_options_dict['index2len'], + 'dbrlen': all_options_dict['dbrlen'], + 'wend': all_options_dict['wend'], + 'cend': all_options_dict['cend'], + 'individualsfile': all_options_dict['individualsfile'], + 'locinum': all_options_dict['locinum'], + 'readsnum': all_options_dict['readsnum'], + 'minreadvar': all_options_dict['minreadvar'], + 'maxreadvar': all_options_dict['maxreadvar'], + 'insertlen': all_options_dict['insertlen'], + 'mutprob': all_options_dict['mutprob'], + 'locusmaxmut': all_options_dict['locusmaxmut'], + 'indelprob': all_options_dict['indelprob'], + 'maxindelsize': all_options_dict['maxindelsize'], + 'dropout': all_options_dict['dropout'], + 'pcrdupprob': all_options_dict['pcrdupprob'], + 'pcrdistribution': all_options_dict['pcrdistribution'], + 'multiparam': all_options_dict['multiparam'], + 'poissonparam': all_options_dict['poissonparam'], + 'gcfactor': all_options_dict['gcfactor'], + 'verbose': all_options_dict['verbose'], + 'trace': all_options_dict['trace'] + } + + # return the options dictionary + return options_dict + +#------------------------------------------------------------------------------- + +def print_help(options_dict): + '''Print the program help.''' + + # get general data + project_name = get_project_name() + project_version = get_project_version() + program_file = get_file_name(__file__) + config_file = get_config_file(__file__) + + # print the help + Message.print('info', '') + Message.print('info', '{0} version {1}'.format(project_name, project_version)) + Message.print('info', '') + Message.print('info', '{0} builds a file in FASTA/FASTQ format with simulated reads of a double digest RADseq.'.format(program_file)) + Message.print('info', '') + Message.print('info', 'Usage: {0} --help'.format(program_file)) + Message.print('info', '') + Message.print('info', ' Show the help of {0}.'.format(program_file)) + Message.print('info', '') + Message.print('info', ' or: {0} --config'.format(program_file)) + Message.print('info', '') + Message.print('info', ' Create the config file {0} with the default value of the options.'.format(config_file)) + Message.print('info', ' The default value of the options can be modified.'.format(config_file)) + Message.print('info', '') + Message.print('info', ' or: {0} [--option= [--option=, ...]]'.format(program_file)) + Message.print('info', '') + Message.print('info', ' The options values are read from the config file {0}, but they can be modified'.format(config_file)) + Message.print('info', ' in command line. The options are:') + Message.print('info', '') + Message.print('info', ' {0:18} {1}'.format('option', 'value')) + Message.print('info', ' {0:18} {1}'.format('=' * 14, '=' * 78)) + Message.print('info', ' {0:18} {1}'.format('--fragsfile', options_dict['fragsfile']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--technique', options_dict['technique']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--format', options_dict['format']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--readsfile', options_dict['readsfile']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--readtype', options_dict['readtype']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--rsfile', options_dict['rsfile']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--enzyme1', options_dict['enzyme1']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--enzyme2', options_dict['enzyme2']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--endsfile', options_dict['endsfile']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--index1len', options_dict['index1len']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--index2len', options_dict['index2len']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--dbrlen', options_dict['dbrlen']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--wend', options_dict['wend']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--cend', options_dict['cend']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--individualsfile', options_dict['individualsfile']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--locinum', options_dict['locinum']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--readsnum', options_dict['readsnum']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--minreadvar', options_dict['minreadvar']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--maxreadvar', options_dict['maxreadvar']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--insertlen', options_dict['insertlen']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--mutprob', options_dict['mutprob']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--locusmaxmut', options_dict['locusmaxmut']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--indelprob', options_dict['indelprob']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--maxindelsize', options_dict['maxindelsize']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--dropout', options_dict['dropout']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--pcrdupprob', options_dict['pcrdupprob']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--pcrdistribution', options_dict['pcrdistribution']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--multiparam', options_dict['multiparam']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--poissonparam', options_dict['poissonparam']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--gcfactor', options_dict['gcfactor']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--verbose', options_dict['verbose']['comment'])) + Message.print('info', ' {0:18} {1}'.format('--trace', options_dict['trace']['comment'])) + +#------------------------------------------------------------------------------- + +def build_config(options_dict): + '''Build the file with the options by default.''' + + # get the config file + config_file = get_config_file(__file__) + + # create the config file and write the default options + try: + with open(config_file, mode='w', encoding='iso-8859-1') as config_file_id: + config_file_id.write('{0:43} # {1}\n'.format('fragsfile' + '=' + options_dict['fragsfile']['default'], options_dict['fragsfile']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('technique' + '=' + options_dict['technique']['default'], options_dict['technique']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('format' + '=' + options_dict['format']['default'], options_dict['format']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('readsfile' + '=' + options_dict['readsfile']['default'], options_dict['readsfile']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('readtype' + '=' + options_dict['readtype']['default'], options_dict['readtype']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('rsfile' + '=' + options_dict['rsfile']['default'], options_dict['rsfile']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('enzyme1' + '=' + options_dict['enzyme1']['default'], options_dict['enzyme1']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('enzyme2' + '=' + options_dict['enzyme2']['default'], options_dict['enzyme2']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('endsfile' + '=' + options_dict['endsfile']['default'], options_dict['endsfile']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('index1len' + '=' + options_dict['index1len']['default'], options_dict['index1len']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('index2len' + '=' + options_dict['index2len']['default'], options_dict['index2len']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('dbrlen' + '=' + options_dict['dbrlen']['default'], options_dict['dbrlen']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('wend' + '=' + options_dict['wend']['default'], options_dict['wend']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('cend' + '=' + options_dict['cend']['default'], options_dict['cend']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('individualsfile' + '=' + options_dict['individualsfile']['default'], options_dict['individualsfile']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('locinum' + '=' + options_dict['locinum']['default'], options_dict['locinum']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('readsnum' + '=' + options_dict['readsnum']['default'], options_dict['readsnum']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('minreadvar' + '=' + options_dict['minreadvar']['default'], options_dict['minreadvar']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('maxreadvar' + '=' + options_dict['maxreadvar']['default'], options_dict['maxreadvar']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('insertlen' + '=' + options_dict['insertlen']['default'], options_dict['insertlen']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('mutprob' + '=' + options_dict['mutprob']['default'], options_dict['mutprob']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('locusmaxmut' + '=' + options_dict['locusmaxmut']['default'], options_dict['locusmaxmut']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('indelprob' + '=' + options_dict['indelprob']['default'], options_dict['indelprob']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('maxindelsize' + '=' + options_dict['maxindelsize']['default'], options_dict['maxindelsize']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('dropout' + '=' + options_dict['dropout']['default'], options_dict['dropout']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('pcrdupprob' + '=' + options_dict['pcrdupprob']['default'], options_dict['pcrdupprob']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('pcrdistribution' + '=' + options_dict['pcrdistribution']['default'], options_dict['pcrdistribution']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('multiparam' + '=' + options_dict['multiparam']['default'], options_dict['multiparam']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('poissonparam' + '=' + options_dict['poissonparam']['default'], options_dict['poissonparam']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('gcfactor' + '=' + options_dict['gcfactor']['default'], options_dict['gcfactor']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('verbose' + '=' + options_dict['verbose']['default'], options_dict['verbose']['comment'])) + config_file_id.write('{0:43} # {1}\n'.format('trace' + '=' + options_dict['trace']['default'], options_dict['trace']['comment'])) + except: + raise ProgramError('F001', config_file) + + # show OK message + Message.print('info', 'The configuration file {0} is created.'.format(get_file_name(config_file))) + +#------------------------------------------------------------------------------- + +if __name__ == '__main__': + main(sys.argv[1:]) + sys.exit(0) + +#------------------------------------------------------------------------------- +","Python" +"In Silico","GGFHF/ddRADseqTools","Package/simcasavaids.py",".py","12145","307","#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +#------------------------------------------------------------------------------- + +''' +This source fixes sequence identifiers of a FASTQ read file generated by ddRADseqTools to compatible format with CASAVA. + + Each read entry in a FASTQ file consists of four records: + - Sequence identifier + - Sequence + - Quality score identifier line (consisting of a +) + - Quality score + + In CASAVA, each sequence identifier, the line that precedes the sequence and describes it, needs to be + in the following format: + @:::::: ::: + + Where: + + instrument = Instrument ID (Characters allowed: a-z, A-Z, 0-9 and underscore) + run = Run number on instrument (Numerical) + flowcell = Flowcell ID (Characters allowed: a-z, A-Z, 0-9) + lane = Lane number (Numerical) + tile = Tile number (Numerical) + x_pos = X coordinate of cluster (Numerical) + y_pos = Y coordinate of cluster (Numerical) + + read = Read number. 1 can be single read or read 2 of paired-end (Numerical) + is_filtered = Y if the read is filtered, N otherwise (Y or N) + control = 0 when none of the control bits are on, otherwise it is an even number (Numerical) + index = Index sequence (ACTG) + + Sequence identifier example: + @EAS139:136:FC706VJ:2:5:1000:12850 1:Y:18:ATCACG + @MG00HS20:721:C7JR3ANXX:1:1101:18066:6008 1:N:0:CGATGT +''' + +#------------------------------------------------------------------------------- + +import os +import re +import sys + +from genlib import * + +#------------------------------------------------------------------------------- + +def main(argv): + '''Main line of the program.''' + + # build the options dictionary + options_dict = build_options() + + # it has been requested the help or to build a new config file + for param in argv: + # show the help and exit OK + if param.startswith('--help'): + print_help(options_dict) + sys.exit(0) + # build the config file and exit OK + elif param.startswith('--config'): + build_config(options_dict) + sys.exit(0) + + # get the config file + config_file = get_config_file(__file__) + + # get options from the config file and the input parameters + options_dict = get_options(options_dict, config_file, argv) + + # fix sequence identifiers + fix_identifiers(options_dict) + +#------------------------------------------------------------------------------- + +def fix_identifiers(options_dict): + '''Fixes sequence identifiers to compatible format with CASAVA.''' + + readtype = options_dict['readtype']['value'] + input_readfile = options_dict['input_readfile']['value'] + filenum = options_dict['filenum']['value'] + verbose = options_dict['verbose']['value'] + trace = options_dict['trace']['value'] + + # set the verbose and trace status + if verbose.upper() == 'YES': + Message.set_verbose_status(True) + else: + Message.set_verbose_status(False) + if trace.upper() == 'YES': + Message.set_trace_status(True) + else: + Message.set_trace_status(False) + + # verify if the file number is OK + if filenum == '2' and readtype == 'SE': + raise ProgramError('L010') + + # verify if read file is a GZ file + if input_readfile.endswith('.gz'): + is_gz = True + else: + is_gz = False + + # set the fixed read file path + fixed_readfile = '{0}/fixed-{1}'.format(os.path.dirname(input_readfile), os.path.basename(input_readfile)) + + # open the read file + try: + if is_gz: + readfile_id = gzip.open(input_readfile, mode='rt', encoding='iso-8859-1') + else: + readfile_id = open(input_readfile, mode='r', encoding='iso-8859-1') + except: + raise ProgramException('F002', input_readfile) + + # open the fixed read file + try: + if is_gz: + fixed_readfile_id = gzip.open(fixed_readfile, mode='wt', encoding='iso-8859-1') + else: + fixed_readfile_id = open(fixed_readfile, mode='w', encoding='iso-8859-1') + except: + raise ProgramError('F002', fixed_readfile) + + # set the pattern of the sequence identifier record + if readtype == 'SE': + pattern = r'^@read: (\d+) \| locus: (\d+) \| read in locus: (\d+) \| fragment: (\d+) \| mutated: (.+) \| individual: (.+) \| index1: (.+) \| index2:$' + elif readtype == 'PE': + pattern = r'^@read: (\d+) \| locus: (\d+) \| read in locus: (\d+) \| fragment: (\d+) \| mutated: (.+) \| individual: (.+) \| index1: (.+) \| index2: (.+)$' + + # initialize the count of reads + reads_count = 0 + + # read the first record of readfile + record = readfile_id.readline() + + # while there are records in readfile + while record != '': + + # process the sequence identifier record + if record.startswith('@'): + + # extract the data + mo = re.search(pattern, record) + read_num = mo.group(1) + locus_num = mo.group(2) + read_in_locus_num = mo.group(3) + fragment_num = mo.group(4) + is_mutated = mo.group(5) + individual_id = mo.group(6) + index1_seq = mo.group(7) + if readtype == 'SE': + index2_seq = '' + elif readtype == 'PE': + index2_seq = mo.group(8) + + # build the fixed sequence identifier record + instrument = 'ddRADseqTool' + run = 1 + flowcell = individual_id + lane = locus_num + tile = fragment_num + x_pos = read_num + y_pos = read_in_locus_num + is_filtered = 'N' + control = 0 + index = index1_seq if readtype == 'SE' else '{0}+{1}'.format(index1_seq, index2_seq) + fixed_record = '@{0}:{1}:{2}:{3}:{4}:{5}:{6} {7}:{8}:{9}:{10}\n'.format(instrument, run, flowcell, lane, tile, x_pos, y_pos, filenum, is_filtered, control, index) + + # write the fixed sequence identifier record + fixed_readfile_id.write(fixed_record) + + else: + # control the FASTQ format + raise ProgramError('F003', readsfile, 'FASTQ') + + # read next record and process the sequence record + record = readfile_id.readline() + if record != '': + fixed_readfile_id.write(record) + else: + # control the FASTQ format + raise ProgramError('F003', readsfile, 'FASTQ') + + # read next record and process quality score identifier record + record = readfile_id.readline() + if record.startswith('+'): + fixed_readfile_id.write(record) + else: + # control the FASTQ format + raise ProgramError('F003', readsfile, 'FASTQ') + + # read next record and process quality score record + record = readfile_id.readline() + if record != '': + fixed_readfile_id.write(record) + else: + # control the FASTQ format + raise ProgramError('F003', readsfile, 'FASTQ') + + # notify the reads have been processed + reads_count += 1 + Message.print('verbose', '\rProcessed reads: {0:9d}'.format(reads_count)) + + # read the next record + record = readfile_id.readline() + + # close files + readfile_id.close() + fixed_readfile_id.close() + + # show OK message + Message.print('verbose', '\n') + print('The file {0} with fixed sequence identifiers has been created.'.format(fixed_readfile)) + +#------------------------------------------------------------------------------- + +def build_options(): + '''Build a dictionary with the program options.''' + + # get all options dictionary + all_options_dict = get_all_options_dict() + + # define the options dictionary + options_dict = { + 'readtype': all_options_dict['readtype'], + 'input_readfile': all_options_dict['input_readfile'], + 'filenum': all_options_dict['filenum'], + 'verbose': all_options_dict['verbose'], + 'trace': all_options_dict['trace'] + } + + # return the options dictionary + return options_dict + +#------------------------------------------------------------------------------- + +def print_help(options_dict): + '''Print the program help.''' + + # get general data + project_name = get_project_name() + project_version = get_project_version() + program_file = get_file_name(__file__) + config_file = get_config_file(__file__) + + # print the help + Message.print('info', '') + Message.print('info', '{0} version {1}'.format(project_name, project_version)) + Message.print('info', '') + Message.print('info', '{0} fixes sequence identifiers of a FASTQ read file generated by ddRADseqTools to compatible format with CASAVA.'.format(program_file)) + Message.print('info', '') + Message.print('info', 'Usage: {0} --help'.format(program_file)) + Message.print('info', '') + Message.print('info', ' Show the help of {0}.'.format(program_file)) + Message.print('info', '') + Message.print('info', ' or: {0} --config'.format(program_file)) + Message.print('info', '') + Message.print('info', ' Create the config file {0} with the default value of the options.'.format(config_file)) + Message.print('info', ' The default value of the options can be modified.'.format(config_file)) + Message.print('info', '') + Message.print('info', ' or: {0} [--option= [--option=, ...]]'.format(program_file)) + Message.print('info', '') + Message.print('info', ' The options values are read from the config file {0}, but they can be modified'.format(config_file)) + Message.print('info', ' in command line. The options are:') + Message.print('info', '') + Message.print('info', ' {0:16} {1}'.format('option', 'value')) + Message.print('info', ' {0:16} {1}'.format('=' * 16, '=' * 78)) + Message.print('info', ' {0:16} {1}'.format('--readtype', options_dict['readtype']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--input_readfile', options_dict['input_readfile']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--filenum', options_dict['filenum']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--verbose', options_dict['verbose']['comment'])) + Message.print('info', ' {0:16} {1}'.format('--trace', options_dict['trace']['comment'])) + +#------------------------------------------------------------------------------- + +def build_config(options_dict): + '''Build the file with the options by default.''' + + # get the config file + config_file = get_config_file(__file__) + + # create the config file and write the default options + try: + with open(config_file, mode='w', encoding='iso-8859-1') as config_file_id: + config_file_id.write('{0:41} # {1}\n'.format('readtype' + '=' + options_dict['readtype']['default'], options_dict['readtype']['comment'])) + config_file_id.write('{0:41} # {1}\n'.format('input_readfile' + '=' + options_dict['input_readfile']['default'], options_dict['input_readfile']['comment'])) + config_file_id.write('{0:41} # {1}\n'.format('filenum' + '=' + options_dict['filenum']['default'], options_dict['filenum']['comment'])) + config_file_id.write('{0:41} # {1}\n'.format('verbose' + '=' + options_dict['verbose']['default'], options_dict['verbose']['comment'])) + config_file_id.write('{0:41} # {1}\n'.format('trace' + '=' + options_dict['trace']['default'], options_dict['trace']['comment'])) + except: + raise ProgramError('F001', config_file) + + # show OK message + Message.print('info', 'The configuration file {0} is created.'.format(get_file_name(config_file))) + +#------------------------------------------------------------------------------- + +if __name__ == '__main__': + + main(sys.argv[1:]) + sys.exit(0) + +#------------------------------------------------------------------------------- +","Python" +"In Silico","GGFHF/ddRADseqTools","Package/readstrim.py",".py","16186","376","#!/usr/bin/env python3 +# -*- coding: utf-8 -*- + +#------------------------------------------------------------------------------- + +'''This software has been developed by: + + GI Genética, Fisiología e Historia Forestal + Dpto. Sistemas y Recursos Naturales + ETSI Montes, Forestal y del Medio Natural + Universidad Politécnica de Madrid + https://github.com/ggfhf/ + + Licence: GNU General Public Licence Version 3 +''' + +#------------------------------------------------------------------------------- + +'''This source contains the program of the ddRADseqTools software package that + trims the ends of 1 file (SE) / 2 files (PE) of reads, i. e. cuts the + adapters +''' +#------------------------------------------------------------------------------- + +import os.path +import sys + +from genlib import * + +#------------------------------------------------------------------------------- + +def main(argv): + '''Main line of the program.''' + + # build the options dictionary + options_dict = build_options() + + # it has been requested the help or to build a new config file + for param in argv: + # show the help and exit OK + if param.startswith('--help'): + print_help(options_dict) + sys.exit(0) + # build the config file and exit OK + elif param.startswith('--config'): + build_config(options_dict) + sys.exit(0) + + # get the config file + config_file = get_config_file(__file__) + + # get options from the config file and the input parameters + options_dict = get_options(options_dict, config_file, argv) + + # trim files + trim_files(options_dict) + +#------------------------------------------------------------------------------- + +def trim_files(options_dict): + '''Trim the ends of 1 file (SE) / 2 files (PE) of reads.''' + + technique = options_dict['technique']['value'] + format = options_dict['format']['value'] + readtype = options_dict['readtype']['value'] + endsfile = options_dict['endsfile']['value'] + index1len = options_dict['index1len']['value'] + index2len = options_dict['index2len']['value'] + dbrlen = options_dict['dbrlen']['value'] + wend = options_dict['wend']['value'] + cend = options_dict['cend']['value'] + readsfile1 = options_dict['readsfile1']['value'] + readsfile2 = options_dict['readsfile2']['value'] + trimfile = options_dict['trimfile']['value'] + verbose = options_dict['verbose']['value'] + trace = options_dict['trace']['value'] + + # set the verbose and trace status + if verbose.upper() == 'YES': + Message.set_verbose_status(True) + else: + Message.set_verbose_status(False) + if trace.upper() == 'YES': + Message.set_trace_status(True) + else: + Message.set_trace_status(False) + + # assign the symbol of the indexes and the DBR + (index1_symbol, index2_symbol, dbr_symbol) = get_symbols() + + # get the end sequences and the DBR strand + (wend_seq, cend_seq, dbr_strand) = get_ends(endsfile, wend, cend, technique, index1len, index1_symbol, index2len, index2_symbol, dbrlen, dbr_symbol) + Message.print('trace', 'wend_seq: {0}'.format(wend_seq)) + Message.print('trace', 'cend_seq: {0}'.format(cend_seq)) + Message.print('trace', 'dbr_strand: {0}'.format(dbr_strand)) + + # assign the end lenght + wend_seq_len = len(wend_seq) + cend_seq_len = len(cend_seq) + + # trim the file(s) + + if format == 'FASTA': + if readtype == 'SE': + trim_fasta_file(readsfile1, trimfile, readtype, 1, wend_seq_len, cend_seq_len) + elif readtype == 'PE': + trim_fasta_file(readsfile1, trimfile, readtype, 1, wend_seq_len, cend_seq_len) + trim_fasta_file(readsfile2, trimfile, readtype, 2, wend_seq_len, cend_seq_len) + elif format == 'FASTQ': + if readtype == 'SE': + trim_fastq_file(readsfile1, trimfile, readtype, 1, wend_seq_len, cend_seq_len) + elif readtype == 'PE': + trim_fastq_file(readsfile1, trimfile, readtype, 1, wend_seq_len, cend_seq_len) + trim_fastq_file(readsfile2, trimfile, readtype, 2, wend_seq_len, cend_seq_len) + +#------------------------------------------------------------------------------- + +def trim_fasta_file(readsfile, trimfile, readtype, file_number, wend_seq_len, cend_seq_len): + + # assign the output file(s) name + extention = '.fasta' + if readtype == 'SE': + trimfile = trimfile + extention + elif readtype == 'PE': + if file_number == 1: + trimfile += '-1' + extention + elif file_number == 2: + trimfile += '-2' + extention + + # open the file with complete reads + try: + readsfile_id = open(readsfile, mode='r', encoding='iso-8859-1') + except: + raise ProgramError('F002', readsfile1) + + # open the file with trimmed reads + try: + trimfile_id = open(trimfile, mode='w', encoding='iso-8859-1') + except: + raise ProgramError('F002', trimfile) + + # read the first record of readsfile + record = readsfile_id.readline() + + # while there are records in readsfile + while record != '': + + # process the head record + if record.startswith('>'): + trimfile_id.write(record) + else: + # control the FASTA format + raise ProgramError('F003', readsfile, 'FASTA') + + # read next record and process the sequence + record = readsfile_id.readline() + if record != '': + # write the trimmed sequence + seq = record.strip() + if file_number == 1: + trimfile_id.write('{0}\n'.format(seq[wend_seq_len:len(record) - 1])) + elif file_number == 2: + trimfile_id.write('{0}\n'.format(seq[cend_seq_len:len(record) - 1])) + else: + # control the FASTA format + raise ProgramError('F003', readsfile, 'FASTA') + + # read the next record + record = readsfile_id.readline() + + # close files + readsfile_id.close() + trimfile_id.close() + + # show OK message + Message.print('info', 'The file {0} with trimmed reads is created.'.format(get_file_name(trimfile))) + +#------------------------------------------------------------------------------- + +def trim_fastq_file(readsfile, trimfile, readtype, file_number, wend_seq_len, cend_seq_len): + + # assign the output file(s) name + extention = '.fastq' + if readtype == 'SE': + trimfile = trimfile + extention + elif readtype == 'PE': + if file_number == 1: + trimfile += '-1' + extention + elif file_number == 2: + trimfile += '-2' + extention + + # open the file with complete reads + try: + readsfile_id = open(readsfile, mode='r', encoding='iso-8859-1') + except: + raise ProgramError('F002', readsfile) + + # open the file with trimmed reads + try: + trimfile_id = open(trimfile, mode='w', encoding='iso-8859-1') + except: + raise ProgramError('F002', trimfile) + + # read the first record of readsfile + record = readsfile_id.readline() + + # while there are records in readsfile + while record != '': + + # process the head record + if record.startswith('@'): + trimfile_id.write(record) + else: + # control the FASTQ format + raise ProgramError('F003', readsfile, 'FASTQ') + + # read next record and process the sequence + record = readsfile_id.readline() + if record != '': + # write the trimmed sequence + seq = record.strip() + if file_number == 1: + trimfile_id.write('{0}\n'.format(seq[wend_seq_len:len(record) - 1])) + elif file_number == 2: + trimfile_id.write('{0}\n'.format(seq[cend_seq_len:len(record) - 1])) + else: + # control the FASTQ format + raise ProgramError('F003', readsfile, 'FASTQ') + + # read next record and process the plus with optional information + record = readsfile_id.readline() + if record.startswith('+'): + trimfile_id.write(record) + else: + # control the FASTQ format + raise ProgramError('F003', readsfile, 'FASTQ') + + # read next record and process the quality + record = readsfile_id.readline() + if record != '': + # write the trimmed quality + quality = record.strip() + if file_number == 1: + trimfile_id.write('{0}\n'.format(quality[wend_seq_len:len(record) - 1])) + elif file_number == 2: + trimfile_id.write('{0}\n'.format(quality[cend_seq_len:len(record) - 1])) + else: + # control the FASTQ format + raise ProgramError('F003', readsfile, 'FASTQ') + + # read the next record + record = readsfile_id.readline() + + # close files + readsfile_id.close() + trimfile_id.close() + + # show OK message + Message.print('info', 'The file {0} with trimmed reads is created.'.format(get_file_name(trimfile))) + +#------------------------------------------------------------------------------- + +def build_options(): + '''Build a dictionary with the program options.''' + + # get all options dictionary + all_options_dict = get_all_options_dict() + + # define the options dictionary + options_dict = { + 'technique': all_options_dict['technique'], + 'format': all_options_dict['format'], + 'readtype': all_options_dict['readtype'], + 'endsfile': all_options_dict['endsfile'], + 'index1len': all_options_dict['index1len'], + 'index2len': all_options_dict['index2len'], + 'dbrlen': all_options_dict['dbrlen'], + 'wend': all_options_dict['wend'], + 'cend': all_options_dict['cend'], + 'readsfile1': all_options_dict['readsfile1'], + 'readsfile2': all_options_dict['readsfile2'], + 'trimfile': all_options_dict['trimfile'], + 'verbose': all_options_dict['verbose'], + 'trace': all_options_dict['trace'] + } + + # return the options dictionary + return options_dict + +#------------------------------------------------------------------------------- + +def print_help(options_dict): + '''Print the program help.''' + + # get general data + project_name = get_project_name() + project_version = get_project_version() + program_file = get_file_name(__file__) + config_file = get_config_file(__file__) + + # print the help + Message.print('info', '') + Message.print('info', '{0} version {1}'.format(project_name, project_version)) + Message.print('info', '') + Message.print('info', '{0} trims the ends of 1 file (SE) / 2 files (PE) of reads, i. e. cuts the adapters'.format(program_file)) + Message.print('info', '') + Message.print('info', 'Usage: {0} --help'.format(program_file)) + Message.print('info', '') + Message.print('info', ' Show the help of {0}.'.format(program_file)) + Message.print('info', '') + Message.print('info', ' or: {0} --config'.format(program_file)) + Message.print('info', '') + Message.print('info', ' Create the config file {0} with the default value of the options.'.format(config_file)) + Message.print('info', ' The default value of the options can be modified.'.format(config_file)) + Message.print('info', '') + Message.print('info', ' or: {0} [--option= [--option=, ...]]'.format(program_file)) + Message.print('info', '') + Message.print('info', ' The options values are read from the config file {0}, but they can be'.format(config_file)) + Message.print('info', ' modified in command line. The options are:') + Message.print('info', '') + Message.print('info', ' {0:12} {1}'.format('option', 'value')) + Message.print('info', ' {0:12} {1}'.format('=' * 12, '=' * 88)) + Message.print('info', ' {0:12} {1}'.format('--technique', options_dict['technique']['comment'])) + Message.print('info', ' {0:12} {1}'.format('--format', options_dict['format']['comment'])) + Message.print('info', ' {0:12} {1}'.format('--readtype', options_dict['readtype']['comment'])) + Message.print('info', ' {0:12} {1}'.format('--endsfile', options_dict['endsfile']['comment'])) + Message.print('info', ' {0:12} {1}'.format('--index1len', options_dict['index1len']['comment'])) + Message.print('info', ' {0:12} {1}'.format('--index2len', options_dict['index2len']['comment'])) + Message.print('info', ' {0:12} {1}'.format('--dbrlen', options_dict['dbrlen']['comment'])) + Message.print('info', ' {0:12} {1}'.format('--wend', options_dict['wend']['comment'])) + Message.print('info', ' {0:12} {1}'.format('--cend', options_dict['cend']['comment'])) + Message.print('info', ' {0:12} {1}'.format('--readsfile1', options_dict['readsfile1']['comment'])) + Message.print('info', ' {0:12} {1}'.format('--readsfile2', options_dict['readsfile2']['comment'])) + Message.print('info', ' {0:12} {1}'.format('--trimfile', options_dict['trimfile']['comment'])) + Message.print('info', ' {0:12} {1}'.format('--verbose', options_dict['verbose']['comment'])) + Message.print('info', ' {0:12} {1}'.format('--trace', options_dict['trace']['comment'])) + +#------------------------------------------------------------------------------- + +def build_config(options_dict): + '''Build the file with the options by default.''' + + # get the config file + config_file = get_config_file(__file__) + + # create the config file and write the default options + try: + with open(config_file, mode='w', encoding='iso-8859-1') as config_file_id: + config_file_id.write('{0:37} # {1}\n'.format('technique' + '=' + options_dict['technique']['default'], options_dict['technique']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('format' + '=' + options_dict['format']['default'], options_dict['format']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('readtype' + '=' + options_dict['readtype']['default'], options_dict['readtype']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('endsfile' + '=' + options_dict['endsfile']['default'], options_dict['endsfile']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('index1len' + '=' + options_dict['index1len']['default'], options_dict['index1len']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('index2len' + '=' + options_dict['index2len']['default'], options_dict['index2len']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('dbrlen' + '=' + options_dict['dbrlen']['default'], options_dict['dbrlen']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('wend' + '=' + options_dict['wend']['default'], options_dict['wend']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('cend' + '=' + options_dict['cend']['default'], options_dict['cend']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('readsfile1' + '=' + options_dict['readsfile1']['default'], options_dict['readsfile1']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('readsfile2' + '=' + options_dict['readsfile2']['default'], options_dict['readsfile2']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('trimfile' + '=' + options_dict['trimfile']['default'], options_dict['trimfile']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('verbose' + '=' + options_dict['verbose']['default'], options_dict['verbose']['comment'])) + config_file_id.write('{0:37} # {1}\n'.format('trace' + '=' + options_dict['trace']['default'], options_dict['trace']['comment'])) + except: + raise ProgramError('F001', config_file) + + # show OK message + Message.print('info', 'The configuration file {0} is created.'.format(get_file_name(config_file))) + +#------------------------------------------------------------------------------- + +if __name__ == '__main__': + main(sys.argv[1:]) + sys.exit(0) + +#------------------------------------------------------------------------------- +","Python" +"In Silico","GGFHF/ddRADseqTools","Package/simulation-scripts/simulation-pcrdupprob.sh",".sh","5091","151","#!/bin/bash + +#------------------------------------------------------------------------------- + +# This software has been developed by Forest Genetics and Physiology Research Group, +# Technical University of Madrid (UPM) + +# Licence: GNU General Public Licence Version 3 + +#------------------------------------------------------------------------------- + +# This script analyses the effect of the probability of PCR duplicates on the +# number of reads to generate + +#------------------------------------------------------------------------------- + +# Control parameters + +if [ -n ""$*"" ]; then echo 'This script has not parameters'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Set run environment + +DDRADSEQTOOLSDIR=$TRABAJO/ddRADseqTools # ddRADseqTools programs directory +GENOMESDIR=$TRABAJO/ddRADseqTools/genomes # genomes file directory +FRAGSDIR=$TRABAJO/ddRADseqTools/fragments # fragments directory +READSDIR=$TRABAJO/ddRADseqTools/reads # reads directory +STATSDIR=$TRABAJO/ddRADseqTools/statistics # statistics directory + +if [ ! -d ""$READSDIR"" ]; then mkdir $READSDIR; else rm -f $READSDIR/*; fi +if [ ! -d ""$STATSDIR"" ]; then mkdir $STATSDIR; else rm -f $STATSDIR/*; fi + +GENOME=GCF_000146045.2_R64_genomic.fna.gz # Saccharomyces cerevisiae genome +ENZYME1=EcoRI +ENZYME2=MseI +TECHNIQUE=IND1_IND2_DBR +FORMAT=FASTQ +READTYPE=PE +INDEX1LEN=6 +INDEX2LEN=6 +DBRLEN=4 +WEND=end91 +CEND=end92 +INDIVIDUALSFILE=individuals-8index1-6index2.txt + +READSNUM=(300000 600000 1200000 2400000) # readsnum values +PCRDUPPROB=(0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9) # pcrdupprob values + +if [ `ulimit -n` -lt 1024 ]; then ulimit -n 1024; fi + +#------------------------------------------------------------------------------- + +# Generate genome fragments and get statistics + +echo '**************************************************' +echo 'GENOME FRAGMENTS ARE BEING GENERATED FROM GENOME ...' + +$DDRADSEQTOOLSDIR/rsitesearch.py \ + --genfile=$GENOMESDIR/$GENOME \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --minfragsize=101 \ + --maxfragsize=300 \ + --fragstfile=$STATSDIR/fragments-genome-stats.txt \ + --fragstinterval=25 \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +for I in ""${READSNUM[@]}"" +do + for J in ""${PCRDUPPROB[@]}"" + do + + echo '**************************************************' + echo ""READSNUM=$I AND PCRDUPPROB=$J"" + + # Generate ddRADseq simulated reads + + echo '--------------------------------------------------' + echo 'SIMULATED READS ARE BEING GENERATED ...' + + $DDRADSEQTOOLSDIR/simddradseq.py \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readsfile=$READSDIR/'reads-'$I'-'$J \ + --readtype=$READTYPE \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=EcoRI \ + --enzyme2=MseI \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --locinum=3000 \ + --readsnum=$I \ + --minreadvar=0.8 \ + --maxreadvar=1.2 \ + --insertlen=100 \ + --mutprob=0.2 \ + --locusmaxmut=1 \ + --indelprob=0.1 \ + --maxindelsize=10 \ + --dropout=0.0 \ + --pcrdupprob=$J \ + --pcrdistribution=MULTINOMIAL \ + --multiparam=0.167,0.152,0.136,0.121,0.106,0.091,0.076,0.061,0.045,0.030,0.015 \ + --poissonparam=1.0 \ + --gcfactor=0.2 \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # Remove the PCR duplicates + + echo '--------------------------------------------------' + echo 'REMOVING PCR DUPLICATES ...' + + $DDRADSEQTOOLSDIR/pcrdupremoval.py \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --readsfile1=$READSDIR/'reads-'$I'-'$J'-1.fastq' \ + --readsfile2=$READSDIR/'reads-'$I'-'$J'-2.fastq' \ + --clearfile=$READSDIR/'reads-cleared-'$I'-'$J \ + --dupstfile=$STATSDIR/'pcrduplicates-stats-'$I'-'$J'.txt' \ + --plot=YES \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + done +done + +#------------------------------------------------------------------------------- + +# End +echo '**************************************************' +exit 0 + +#------------------------------------------------------------------------------- +","Shell" +"In Silico","GGFHF/ddRADseqTools","Package/simulation-scripts/simulation-pipeline-Bnapus-pe.sh",".sh","11043","327","#!/bin/bash + +#------------------------------------------------------------------------------- + +# This script generates fragments from the Brassica napus genome, simulates +# a double digest, generates their PE reads, demultiplexes the individuals, +# trims the adapters and other Illumina specific sequences, aligns the reads +# and gets SAM, BAM, BED and VCF format files to study and visualize +# alignments + +#------------------------------------------------------------------------------- + +# WARNING + +# This script uses the following bioinformatics tools: +# - BWA v0.7.13 (http://bio-bwa.sourceforge.net/) +# - SAMtools & BCFtools v0.1.19 (http://www.htslib.org/) +# - BEDtools v2.25.0 (http://bedtools.readthedocs.io/) +# - VCFtools v0.1.14-14 (https://vcftools.github.io/) + +#------------------------------------------------------------------------------- + +# Control parameters + +if [ -n ""$*"" ]; then echo 'This script has not parameters.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Set run environment + +SAMTOOLSDIR=/usr/share/samtools # SAMTools directory + +DDRADSEQTOOLSDIR=$TRABAJO/ddRADseqTools # ddRADseqTools programs directory +GENOMESDIR=$TRABAJO/ddRADseqTools/genomes # genomes file directory +FRAGSDIR=$TRABAJO/ddRADseqTools/fragments # fragments directory +READSDIR=$TRABAJO/ddRADseqTools/reads # reads directory +STATSDIR=$TRABAJO/ddRADseqTools/statistics # statistics directory +ALIGNDIR=$TRABAJO/ddRADseqTools/alignments # alignments directory + +if [ ! -d ""$FRAGSDIR"" ]; then mkdir $FRAGSDIR; fi +if [ ! -d ""$READSDIR"" ]; then mkdir $READSDIR; else rm -f $READSDIR/*; fi +if [ ! -d ""$STATSDIR"" ]; then mkdir $STATSDIR; else rm -f $STATSDIR/*; fi +if [ ! -d ""$ALIGNDIR"" ]; then mkdir $ALIGNDIR; else rm -f $ALIGNDIR/*; fi + +GENOME=GCF_000686985.1_Brassica_napus_assembly_v1.0_genomic.fna.gz # Brassica napus genome + +ENZYME1=SacI +ENZYME2=MseI +TECHNIQUE=IND1_IND2 +FORMAT=FASTQ +READTYPE=PE +INDEX1LEN=5 +INDEX2LEN=5 +DBRLEN=0 +WEND=end73 +CEND=end74 +INDIVIDUALSFILE=individuals-19index1-10index2.txt + +if [ `ulimit -n` -lt 1024 ]; then ulimit -n 1024; fi + +#------------------------------------------------------------------------------- + +# Generate genome fragments and get statistics + +echo '**************************************************' +echo 'GENOME FRAGMENTS ARE BEING GENERATED FROM GENOME ...' + +$DDRADSEQTOOLSDIR/rsitesearch.py \ + --genfile=$GENOMESDIR/$GENOME \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --minfragsize=140 \ + --maxfragsize=420 \ + --fragstfile=$STATSDIR/fragments-genome-stats.txt \ + --fragstinterval=25 \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Generate ddRADseq simulated reads + +echo '**************************************************' +echo 'DDRADSEQ SIMULATED READS ARE BEING GENERATED ...' + +$DDRADSEQTOOLSDIR/simddradseq.py \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readsfile=$READSDIR/reads \ + --readtype=$READTYPE \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --locinum=110400 \ + --readsnum=506810000 \ + --minreadvar=0.8 \ + --maxreadvar=1.2 \ + --insertlen=80 \ + --mutprob=0.2 \ + --locusmaxmut=1 \ + --indelprob=0.1 \ + --maxindelsize=10 \ + --dropout=0.05 \ + --pcrdupprob=0.0 \ + --pcrdistribution=MULTINOMIAL \ + --multiparam=0.167,0.152,0.136,0.121,0.106,0.091,0.076,0.061,0.045,0.030,0.015 \ + --poissonparam=1.0 \ + --gcfactor=0.2 \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Remove the PCR duplicates (this step is only used for statistics) + +echo '**************************************************' +echo 'THE PRC DUPLICATES ARE BEING REMOVED ...' + +$DDRADSEQTOOLSDIR/pcrdupremoval.py \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --readsfile1=$READSDIR/reads-1.fastq \ + --readsfile2=$READSDIR/reads-2.fastq \ + --clearfile=$READSDIR/reads-cleared \ + --dupstfile=$STATSDIR/pcrduplicates-stats.txt \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Demultiplex the individual files (all reads including duplicates) + +echo '**************************************************' +echo 'INDIVIDUAL FILES ARE BEING DEMULTIPLEXED ...' + +$DDRADSEQTOOLSDIR/indsdemultiplexing.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --readsfile1=$READSDIR/reads-1.fastq \ + --readsfile2=$READSDIR/reads-2.fastq \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Trim adapters and other Illumina-specific sequences from reads + +echo '**************************************************' +echo 'ADAPTERS AND OTHER ILLUMINA SPECIFIC SEQUENCES ARE BEING TRIMMED IN INDIVIDUAL FILES ...' + +ls $READSDIR/demultiplexed-*-1.fastq > $READSDIR/reads-files.txt + +while read FILE_1; do + + if [[ $FILE_1 =~ .*errors.* ]]; then continue; fi + + FILE_2=`echo $FILE_1 | sed 's/-1.fastq/-2.fastq/g'` + FILE_TRIMMED=`echo $FILE_1 | sed 's/-1.fastq/-trimmed/g'` + + $DDRADSEQTOOLSDIR/readstrim.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN + --wend=$WEND \ + --cend=$CEND \ + --readsfile1=$FILE_1 \ + --readsfile2=$FILE_2 \ + --trimfile=$FILE_TRIMMED \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $READSDIR/reads-files.txt + +#------------------------------------------------------------------------------- + +# Index the genome + +echo '**************************************************' +echo 'GENOME IS BEING INDEXED ...' + + +bwa index -a bwtsw $GENOMESDIR/$GENOME +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + +#------------------------------------------------------------------------------- + +# Align sequences of individual files in SAM format + +echo '**************************************************' +echo 'SEQUENCES OF INDIVIDUAL FILES ARE BEING ALIGNED IN SAM FORMAT ...' + +ls $READSDIR/demultiplexed-*-trimmed-1.fastq > $READSDIR/reads-trimmed-files.txt + +while read FILE1_TRIM; do + + FILE2_TRIM=`echo $FILE1_TRIM | sed 's/-trimmed-1.fastq/-trimmed-2.fastq/g'` + FILE_SAM=`echo $FILE1_TRIM | sed 's/-1.fastq/.sam/g' | sed ""s|$READSDIR|$ALIGNDIR|g""` + bwa mem $GENOMESDIR/$GENOME $FILE1_TRIM $FILE2_TRIM > $FILE_SAM + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $READSDIR/reads-trimmed-files.txt + +#------------------------------------------------------------------------------- + +# Convert SAM files to BED, BAM and VCF format + +echo '**************************************************' +echo 'SAM FILES ARE BEING CONVERTED IN BAM, BED AND VCF FORMAT ...' + +ls $ALIGNDIR/*.sam > $ALIGNDIR/sam-files.txt + +while read FILE_SAM; do + + FILE_BAM=`echo $FILE_SAM | sed 's/.sam/.bam/g'` + FILE_BAM_STATS=`echo $FILE_SAM | sed 's/.sam/-stats-bam.txt/g'` + FILE_BED=`echo $FILE_SAM | sed 's/.sam/.bed/g'` + FILE_SORTED=`echo $FILE_SAM | sed 's/.sam/.sorted/g'` + FILE_SORTED_BAM=`echo $FILE_SAM | sed 's/.sam/.sorted.bam/g'` + FILE_VCF=`echo $FILE_SAM | sed 's/.sam/.vcf/g'` + FILE_VCF_STATS1=`echo $FILE_SAM | sed 's/.sam/-stats-vcf-1.txt/g'` + FILE_VCF_STATS2=`echo $FILE_SAM | sed 's/.sam/-stats-vcf-2.txt/g'` + + # convert SAM file to BAM format + samtools view -bS $FILE_SAM >$FILE_BAM + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # get aligment statistic in a file + samtools flagstat $FILE_BAM >$FILE_BAM_STATS + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # convert BAM file to BED format + bedtools bamtobed -i $FILE_BAM > $FILE_BED + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # sort the BAM file + samtools sort $FILE_BAM $FILE_SORTED + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # index the BAM file + samtools index $FILE_SORTED_BAM + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # convert BAM file to VCF format + samtools mpileup -uf $GENOMESDIR/$GENOME $FILE_SORTED_BAM | bcftools view -vcg - > $FILE_VCF + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # get variant statistic in a file with SAMtools + $SAMTOOLSDIR/vcfutils.pl qstats $FILE_VCF > $FILE_VCF_STATS1 + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # get variant statistic in a file with VCFtools + vcftools --vcf $FILE_VCF > $FILE_VCF_STATS2 + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $ALIGNDIR/sam-files.txt + +#------------------------------------------------------------------------------- + +# Get the distinct loci list with mutations + +echo '**************************************************' +echo 'THE DISTINCT LOCI LIST WITH MUTATIONS ARE BEING GOT ...' + +LOCI_FILE=$ALIGNDIR/loci.txt +cat >$LOCI_FILE < $ALIGNDIR/vcf-files.txt + +while read FILE_VCF; do + + while read -r LINE; do + + if [[ $LINE =~ ^#.*$ ]]; then continue; fi + + echo ""$LINE"" | cut -f 1,2 >> $LOCI_FILE + + done < $FILE_VCF + +done < $ALIGNDIR/vcf-files.txt + +sort -u $LOCI_FILE > $DISTINCT_LOCI_FILE + +DISTINCT_LOCI_TOTAL=`wc -l $DISTINCT_LOCI_FILE | cut -f1 -d' '` +echo ""The dictinct loci list contains $DISTINCT_LOCI_TOTAL loci."" +echo ""$DISTINCT_LOCI_TOTAL"" > $DISTINCT_LOCI_TOTAL_FILE + +#------------------------------------------------------------------------------- + +# End +echo '**************************************************' +exit 0 + +#------------------------------------------------------------------------------- +","Shell" +"In Silico","GGFHF/ddRADseqTools","Package/simulation-scripts/simulation-ddradseq.sh",".sh","10282","278","#!/bin/bash + +#------------------------------------------------------------------------------- + +# This software has been developed by Forest Genetics and Physiology Research Group, +# Technical University of Madrid (UPM) + +# Licence: GNU General Public Licence Version 3 + +#------------------------------------------------------------------------------- + +# This script simulates PE reads of a ddRADseq gotten from fragments previously +# obtained of the digest of the genome of Saccharomyces cerevisiae, Homo sapiens +# and Pinus taeda varing two options: number of reads to generate and probability +# of loci bearing PCR duplicates + +#------------------------------------------------------------------------------- + +# Control parameters + +if [ -n ""$*"" ]; then echo 'This script has not parameters'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Set run environment + +DDRADSEQTOOLSDIR=$TRABAJO/ddRADseqTools # ddRADseqTools programs directory +FRAGSDIR=$TRABAJO/ddRADseqTools/fragments # fragments directory +READSDIR=$TRABAJO/ddRADseqTools/reads # reads directory +STATSDIR=$TRABAJO/ddRADseqTools/statistics # statistics directory + +if [ ! -d ""$READSDIR"" ]; then mkdir $READSDIR; else rm -f $READSDIR/*; fi +if [ ! -d ""$STATSDIR"" ]; then mkdir $STATSDIR; else rm -f $STATSDIR/*; fi + +SCEREVISIAE='Scerevisiae' # Saccharomyces cerevisiae +SCEREVISIAE_FRAGS_FILE=$SCEREVISIAE'-fragments-EcoRI-MseI.fasta' # Saccharomyces cerevisiae framents gotten by EcoI and MseI digest +SCEREVISIAE_READSNUM=(300000 600000 1200000 2400000) # Saccharomyces cerevisiae readsnum values +SCEREVISIAE_PCRDUPPROB=(0.2 0.4 0.6) # Saccharomyces cerevisiae pcrdupprob values + +HSAPIENS='Hsapiens' # Homo sapiens +HSAPIENS_FRAGS_FILE=$HSAPIENS'-fragments-SbfI-MseI.fasta' # Homo sapiens framents gotten by SbfI and MseI digest +HSAPIENS_READSNUM=(2000000 4000000 8100000 16100000) # Homo sapiens readsnum values +HSAPIENS_PCRDUPPROB=(0.2 0.4 0.6) # Homo sapiens pcrdupprob values + +PTAEDA='Ptaeda' # Pinus taeda +PTAEDA_FRAGS_FILE=$PTAEDA'-fragments-SbfI-MseI.fasta' # Pinus taeda framents gotten by SbfI and MseI digest +PTAEDA_READSNUM=(2500000 5100000 10200000 20400000) # Pinus taeda readsnum values +PTAEDA_PCRDUPPROB=(0.2 0.4 0.6) # Pinus taeda pcrdupprob values + +TECHNIQUE=IND1_IND2_DBR +FORMAT=FASTQ +READTYPE=PE +INDEX1LEN=6 +INDEX2LEN=6 +DBRLEN=4 +WEND=end31 +CEND=end32 +INDIVIDUALSFILE=individuals-8index1-6index2.txt + +#------------------------------------------------------------------------------- + +# Saccharomyces cerevisiae + +echo '**************************************************' +echo 'SACCHAROMYCES CEREVISIAE' + +for I in ""${SCEREVISIAE_READSNUM[@]}"" +do + for J in ""${SCEREVISIAE_PCRDUPPROB[@]}"" + do + + # Generate ddRADseq simulated reads + + echo '--------------------------------------------------' + echo ""SIMULATED READS ARE BEING GENERATED WITH READSNUM=$I AND PCRDUPPROB=$J ..."" + + $DDRADSEQTOOLSDIR/simddradseq.py \ + --fragsfile=$FRAGSDIR/$SCEREVISIAE_FRAGS_FILE \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readsfile=$READSDIR/$SCEREVISIAE'-reads-'$I'-'$J \ + --readtype=$READTYPE \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=EcoRI \ + --enzyme2=MseI \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --locinum=3000 \ + --readsnum=$I \ + --minreadvar=0.8 \ + --maxreadvar=1.2 \ + --insertlen=100 \ + --mutprob=0.2 \ + --locusmaxmut=1 \ + --indelprob=0.1 \ + --maxindelsize=10 \ + --dropout=0.0 \ + --pcrdupprob=$J \ + --pcrdistribution=MULTINOMIAL \ + --multiparam=0.167,0.152,0.136,0.121,0.106,0.091,0.076,0.061,0.045,0.030,0.015 \ + --poissonparam=1.0 \ + --gcfactor=0.2 \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # Remove the PCR duplicates + + echo '--------------------------------------------------' + echo ""REMOVING PCR DUPLICATES ..."" + + $DDRADSEQTOOLSDIR/pcrdupremoval.py \ + --readsfile1=$READSDIR/$SCEREVISIAE'-reads-'$I'-'$J'-1.fastq' \ + --readsfile2=$READSDIR/$SCEREVISIAE'-reads-'$I'-'$J'-2.fastq' \ + --clearfile=$READSDIR/$SCEREVISIAE'-reads-cleared-'$I'-'$J \ + --dupstfile=$STATSDIR/$SCEREVISIAE'-pcrduplicates-stats-'$I'-'$J'.txt' \ + --plot=YES \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + done +done + +#------------------------------------------------------------------------------- + +# Homo sapiens + +echo '**************************************************' +echo 'HOMO SAPIENS' + +for I in ""${HSAPIENS_READSNUM[@]}"" +do + for J in ""${HSAPIENS_PCRDUPPROB[@]}"" + do + + # Generate ddRADseq simulated reads + + echo '--------------------------------------------------' + echo ""SIMULATED READS ARE BEING GENERATED WITH READSNUM=$I AND PCRDUPPROB=$J ..."" + + $DDRADSEQTOOLSDIR/simddradseq.py \ + --fragsfile=$FRAGSDIR/$HSAPIENS_FRAGS_FILE \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readsfile=$READSDIR/$HSAPIENS'-reads-'$I'-'$J \ + --readtype=$READTYPE \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=SbfI \ + --enzyme2=MseI \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --locinum=20700 \ + --readsnum=$I \ + --minreadvar=0.8 \ + --maxreadvar=1.2 \ + --insertlen=100 \ + --mutprob=0.2 \ + --locusmaxmut=1 \ + --indelprob=0.1 \ + --maxindelsize=10 \ + --dropout=0.0 \ + --pcrdupprob=$J \ + --pcrdistribution=MULTINOMIAL \ + --multiparam=0.167;0.152;0.136;0.121;0.106;0.091;0.076;0.061;0.045;0.030;0.015 \ + --poissonparam=1.0 \ + --gcfactor=0.2 \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # Remove the PCR duplicates + + echo '--------------------------------------------------' + echo ""REMOVING PCR DUPLICATES ..."" + + $DDRADSEQTOOLSDIR/pcrdupremoval.py \ + --readsfile1=$READSDIR/$HSAPIENS'-reads-'$I'-'$J'-1.fastq' \ + --readsfile2=$READSDIR/$HSAPIENS'-reads-'$I'-'$J'-2.fastq' \ + --clearfile=$READSDIR/$HSAPIENS'-reads-cleared-'$I'-'$J \ + --dupstfile=$STATSDIR/$HSAPIENS'-pcrduplicates-stats-'$I'-'$J'.txt' \ + --plot=YES \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + done +done + +#------------------------------------------------------------------------------- + +# Pinus taeda + +echo '**************************************************' +echo 'PINUS TAEDA' + +for I in ""${PTAEDA_READSNUM[@]}"" +do + for J in ""${PTAEDA_PCRDUPPROB[@]}"" + do + + # Generate ddRADseq simulated reads + + echo '--------------------------------------------------' + echo ""SIMULATED READS ARE BEING GENERATED WITH READSNUM=$I AND PCRDUPPROB=$J ..."" + + $DDRADSEQTOOLSDIR/simddradseq.py \ + --fragsfile=$FRAGSDIR/$PTAEDA_FRAGS_FILE \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readsfile=$READSDIR/$PTAEDA'-reads-'$I'-'$J \ + --readtype=$READTYPE \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=SbfI \ + --enzyme2=MseI \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --locinum=26000 \ + --readsnum=$I \ + --minreadvar=0.8 \ + --maxreadvar=1.2 \ + --insertlen=100 \ + --mutprob=0.2 \ + --locusmaxmut=1 \ + --indelprob=0.1 \ + --maxindelsize=10 \ + --dropout=0.0 \ + --pcrdupprob=$J \ + --pcrdistribution=MULTINOMIAL \ + --multiparam=0.167;0.152;0.136;0.121;0.106;0.091;0.076;0.061;0.045;0.030;0.015 \ + --poissonparam=1.0 \ + --gcfactor=0.2 \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + + # Remove the PCR duplicates + + echo '--------------------------------------------------' + echo ""REMOVING PCR DUPLICATES ..."" + + $DDRADSEQTOOLSDIR/pcrdupremoval.py \ + --readsfile1=$READSDIR/$PTAEDA'-reads-'$I'-'$J'-1.fastq' \ + --readsfile2=$READSDIR/$PTAEDA'-reads-'$I'-'$J'-2.fastq' \ + --clearfile=$READSDIR/$PTAEDA'-reads-cleared-'$I'-'$J \ + --dupstfile=$STATSDIR/$PTAEDA'-pcrduplicates-stats-'$I'-'$J'.txt' \ + --plot=YES \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + done +done + +#------------------------------------------------------------------------------- + +# End +echo '**************************************************' +exit 0 + +#------------------------------------------------------------------------------- +","Shell" +"In Silico","GGFHF/ddRADseqTools","Package/simulation-scripts/simulation-unequal-coverage.sh",".sh","5032","150","#!/bin/bash + +#------------------------------------------------------------------------------- + +# This software has been developed by Forest Genetics and Physiology Research Group, +# Technical University of Madrid (UPM) + +# Licence: GNU General Public Licence Version 3 + +#------------------------------------------------------------------------------- + +# This script analyses the coverage variation among individuals across loci. + +#------------------------------------------------------------------------------- + +# Control parameters + +if [ -n ""$*"" ]; then echo 'This script has not parameters'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Set run environment + +DDRADSEQTOOLSDIR=$TRABAJO/ddRADseqTools # ddRADseqTools programs directory +GENOMESDIR=$TRABAJO/ddRADseqTools/genomes # genomes file directory +FRAGSDIR=$TRABAJO/ddRADseqTools/fragments # fragments directory +READSDIR=$TRABAJO/ddRADseqTools/reads # reads directory +STATSDIR=$TRABAJO/ddRADseqTools/statistics # statistics directory + +if [ ! -d ""$READSDIR"" ]; then mkdir $READSDIR; else rm -f $READSDIR/*; fi +if [ ! -d ""$STATSDIR"" ]; then mkdir $STATSDIR; else rm -f $STATSDIR/*; fi + +GENOME=GCF_000146045.2_R64_genomic.fna.gz # Saccharomyces cerevisiae genome +ENZYME1=EcoRI +ENZYME2=MseI +TECHNIQUE=IND1_IND2 +FORMAT=FASTQ +READTYPE=PE +INDEX1LEN=6 +INDEX2LEN=6 +DBRLEN=0 +WEND=end71 +CEND=end72 +INDIVIDUALSFILE=individuals-8index1-6index2.txt + +READSNUM=(300000 600000 1200000 2400000) # readsnum values +PCRDUPPROB=(0.0) # pcrdupprob values + +if [ `ulimit -n` -lt 1024 ]; then ulimit -n 1024; fi + +#------------------------------------------------------------------------------- + +# Generate genome fragments and get statistics + +echo '**************************************************' +echo 'GENOME FRAGMENTS ARE BEING GENERATED FROM GENOME ...' + +$DDRADSEQTOOLSDIR/rsitesearch.py \ + --genfile=$GENOMESDIR/$GENOME \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --minfragsize=101 \ + --maxfragsize=300 \ + --fragstfile=$STATSDIR/fragments-genome-stats.txt \ + --fragstinterval=25 \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +for I in ""${READSNUM[@]}"" +do + for J in ""${PCRDUPPROB[@]}"" + do + + echo '**************************************************' + echo ""READSNUM=$I AND PCRDUPPROB=$J"" + + # Generate ddRADseq simulated reads + + echo '--------------------------------------------------' + echo 'SIMULATED READS ARE BEING GENERATED ...' + + $DDRADSEQTOOLSDIR/simddradseq.py \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readsfile=$READSDIR/'reads-'$I'-'$J \ + --readtype=$READTYPE \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=EcoRI \ + --enzyme2=MseI \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --locinum=3000 \ + --readsnum=$I \ + --minreadvar=0.8 \ + --maxreadvar=1.2 \ + --insertlen=100 \ + --mutprob=0.2 \ + --locusmaxmut=1 \ + --indelprob=0.1 \ + --maxindelsize=10 \ + --dropout=0.0 \ + --pcrdupprob=$J \ + --pcrdistribution=MULTINOMIAL \ + --multiparam=0.167,0.152,0.136,0.121,0.106,0.091,0.076,0.061,0.045,0.030,0.015 \ + --poissonparam=1.0 \ + --gcfactor=0.2 \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # Remove the PCR duplicates + + echo '--------------------------------------------------' + echo 'REMOVING PCR DUPLICATES ...' + + $DDRADSEQTOOLSDIR/pcrdupremoval.py \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --readsfile1=$READSDIR/'reads-'$I'-'$J'-1.fastq' \ + --readsfile2=$READSDIR/'reads-'$I'-'$J'-2.fastq' \ + --clearfile=$READSDIR/'reads-cleared-'$I'-'$J \ + --dupstfile=$STATSDIR/'pcrduplicates-stats-'$I'-'$J'.txt' \ + --plot=YES \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + done +done + +#------------------------------------------------------------------------------- + +# End +echo '**************************************************' +exit 0 + +#------------------------------------------------------------------------------- +","Shell" +"In Silico","GGFHF/ddRADseqTools","Package/simulation-scripts/simulation-pipeline.sh",".sh","12714","345","#!/bin/bash + +#------------------------------------------------------------------------------- + +# This software has been developed by Forest Genetics and Physiology Research Group, +# Technical University of Madrid (UPM) + +# Licence: GNU General Public Licence Version 3 + +#------------------------------------------------------------------------------- + +# This script generates fragments from a genome; it simulates a double digest +# and generates their PE reads; it quantifies and removes PCR duplicates and +# calculates the loci number without data; it demultiplexes the individuals; it +# trims the adapters and other Illumina specific sequences; it aligns the reads +# and gets SAM, BAM, BED and VCF format files to study and visualize alignments; +# and it gets the distinct loci list with mutations. + +#------------------------------------------------------------------------------- + +# WARNING + +# This script uses the following bioinformatics tools: +# - BWA v0.7.13 (http://bio-bwa.sourceforge.net/) +# - SAMtools & BCFtools v0.1.19 (http://www.htslib.org/) +# - BEDtools v2.25.0 (http://bedtools.readthedocs.io/) +# - VCFtools v0.1.14-14 (https://vcftools.github.io/) + +#------------------------------------------------------------------------------- + +# Control parameters + +if [ -n ""$*"" ]; then echo 'This script has not parameters.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Set run environment + +BWADIR=$APPS/BWA # BWA 0.7.13 programs directory +SAMTOOLSDIR=$APPS/SAMtools-0 # SAMTools 0.0.19 programs directory +BCFTOOLSDIR=$APPS/BCFtools-0 # BCFTools 0.1.19 programs directory +BEDTOOLSDIR=$APPS/BEDtools/bin # BEDTools 2.25.0 programs directory +#VCFTOOLSDIR=$APPS/VCFtools # VCFTools 0.1.14-14 programs directory + +DDRADSEQTOOLSDIR=$TRABAJO/ddRADseqTools # ddRADseqTools programs directory +GENOMESDIR=$TRABAJO/ddRADseqTools/genomes # genomes file directory +FRAGSDIR=$TRABAJO/ddRADseqTools/fragments # fragments directory +READSDIR=$TRABAJO/ddRADseqTools/reads # reads directory +STATSDIR=$TRABAJO/ddRADseqTools/statistics # statistics directory +ALIGNDIR=$TRABAJO/ddRADseqTools/alignments # alignments directory + +if [ ! -d ""$FRAGSDIR"" ]; then mkdir $FRAGSDIR; fi +if [ ! -d ""$READSDIR"" ]; then mkdir $READSDIR; else rm -f $READSDIR/*; fi +if [ ! -d ""$STATSDIR"" ]; then mkdir $STATSDIR; else rm -f $STATSDIR/*; fi +if [ ! -d ""$ALIGNDIR"" ]; then mkdir $ALIGNDIR; else rm -f $ALIGNDIR/*; fi + +GENOME_SCEREVISIAE=GCF_000146045.2_R64_genomic.fna.gz # Saccharomyces cerevisiae genome +GENOME_CELEGANS=GCF_000002985.6_WBcel235_genomic.fna.gz # Caenorhabditis elegans genome +GENOME_DMELANOGASTER=GCF_000001215.4_Release_6_plus_ISO1_MT_genomic.fna.gz # Drosophila melanogaster genome +GENOME_WAUROPUNCTATA=GCF_000956235.1_wasmannia.A_1.0_genomic.fna.gz # Wasmannia auropunctata genome +GENOME_VBERUS=GCA_000800605.1_Vber.be_1.0_genomic.fna.gz # Vipera berus genome +GENOME_HSAPIENS=GCF_000001405.29_GRCh38.p3_genomic.fna.gz # Homo sapiens genome +GENOME_BNAPUS=GCF_000686985.1_Brassica_napus_assembly_v1.0_genomic.fna.gz # Brassica napus genome +GENOME_QROBUR=ena.fasta # Quercus robur genome +GENOME_PTAEDA=ptaeda.v1.01.scaffolds.fasta.gz # Pinus taeda genome +GENOME=$GENOME_SCEREVISIAE # genome used in this run + +ENZYME1=EcoRI +ENZYME2=MseI +TECHNIQUE=IND1_IND2_DBR +FORMAT=FASTQ +READTYPE=PE +INDEX1LEN=6 +INDEX2LEN=6 +DBRLEN=4 +WEND=end91 +CEND=end92 +INDIVIDUALSFILE=individuals-8index1-6index2.txt + +if [ `ulimit -n` -lt 1024 ]; then ulimit -n 1024; fi + +#------------------------------------------------------------------------------- + +# Generate genome fragments and get statistics + +echo '**************************************************' +echo 'GENOME FRAGMENTS ARE BEING GENERATED FROM GENOME ...' + +$DDRADSEQTOOLSDIR/rsitesearch.py \ + --genfile=$GENOMESDIR/$GENOME \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --minfragsize=101 \ + --maxfragsize=300 \ + --fragstfile=$STATSDIR/fragments-genome-stats.txt \ + --fragstinterval=25 \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Generate ddRADseq simulated reads + +echo '**************************************************' +echo 'DDRADSEQ SIMULATED READS ARE BEING GENERATED ...' + +$DDRADSEQTOOLSDIR/simddradseq.py \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readsfile=$READSDIR/reads \ + --readtype=$READTYPE \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --locinum=3000 \ + --readsnum=300000 \ + --minreadvar=0.8 \ + --maxreadvar=1.2 \ + --insertlen=100 \ + --mutprob=0.2 \ + --locusmaxmut=1 \ + --indelprob=0.1 \ + --maxindelsize=10 \ + --dropout=0.05 \ + --pcrdupprob=0.2 \ + --pcrdistribution=MULTINOMIAL \ + --multiparam=0.167,0.152,0.136,0.121,0.106,0.091,0.076,0.061,0.045,0.030,0.015 \ + --poissonparam=1.0 \ + --gcfactor=0.2 \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Remove the PCR duplicates + +echo '**************************************************' +echo 'THE PRC DUPLICATES ARE BEING REMOVED ...' + +$DDRADSEQTOOLSDIR/pcrdupremoval.py \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --readsfile1=$READSDIR/reads-1.fastq \ + --readsfile2=$READSDIR/reads-2.fastq \ + --clearfile=$READSDIR/reads-cleared \ + --dupstfile=$STATSDIR/pcrduplicates-stats.txt \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Demultiplex the individual files + +echo '**************************************************' +echo 'INDIVIDUAL FILES ARE BEING DEMULTIPLEXED ...' + +$DDRADSEQTOOLSDIR/indsdemultiplexing.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --readsfile1=$READSDIR/reads-cleared-1.fastq \ + --readsfile2=$READSDIR/reads-cleared-2.fastq \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Trim adapters and other Illumina-specific sequences from reads + +echo '**************************************************' +echo 'ADAPTERS AND OTHER ILLUMINA SPECIFIC SEQUENCES ARE BEING TRIMMED IN INDIVIDUAL FILES ...' + +ls $READSDIR/demultiplexed-ind*-1.fastq > $READSDIR/reads-files.txt + +while read FILE_1; do + + FILE_2=`echo $FILE_1 | sed 's/-1.fastq/-2.fastq/g'` + FILE_TRIMMED=`echo $FILE_1 | sed 's/-1.fastq/-trimmed/g'` + + $DDRADSEQTOOLSDIR/readstrim.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --readsfile1=$FILE_1 \ + --readsfile2=$FILE_2 \ + --trimfile=$FILE_TRIMMED \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $READSDIR/reads-files.txt + +#------------------------------------------------------------------------------- + +# Index the genome + +echo '**************************************************' +echo 'GENOME IS BEING INDEXED ...' + +$BWADIR/bwa index -a bwtsw $GENOMESDIR/$GENOME +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + +#------------------------------------------------------------------------------- + +# Align sequences of individual files in SAM format + +echo '**************************************************' +echo 'SEQUENCES OF INDIVIDUAL FILES ARE BEING ALIGNED IN SAM FORMAT ...' + +ls $READSDIR/demultiplexed-ind*-trimmed-1.fastq > $READSDIR/reads-trimmed-files.txt + +while read FILE1_TRIM; do + + FILE2_TRIM=`echo $FILE1_TRIM | sed 's/-trimmed-1.fastq/-trimmed-2.fastq/g'` + FILE_SAM=`echo $FILE1_TRIM | sed 's/-1.fastq/.sam/g' | sed ""s|$READSDIR|$ALIGNDIR|g""` + $BWADIR/bwa mem $GENOMESDIR/$GENOME $FILE1_TRIM $FILE2_TRIM > $FILE_SAM + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $READSDIR/reads-trimmed-files.txt + +#------------------------------------------------------------------------------- + +# Convert SAM files to BED, BAM and VCF format + +echo '**************************************************' +echo 'SAM FILES ARE BEING CONVERTED IN BAM, BED AND VCF FORMAT ...' + +ls $ALIGNDIR/*.sam > $ALIGNDIR/sam-files.txt + +while read FILE_SAM; do + + FILE_BAM=`echo $FILE_SAM | sed 's/.sam/.bam/g'` + FILE_BAM_STATS=`echo $FILE_SAM | sed 's/.sam/-stats-bam.txt/g'` + FILE_BED=`echo $FILE_SAM | sed 's/.sam/.bed/g'` + FILE_SORTED=`echo $FILE_SAM | sed 's/.sam/.sorted/g'` + FILE_SORTED_BAM=`echo $FILE_SAM | sed 's/.sam/.sorted.bam/g'` + FILE_VCF=`echo $FILE_SAM | sed 's/.sam/.vcf/g'` + FILE_VCF_STATS1=`echo $FILE_SAM | sed 's/.sam/-stats-vcf-1.txt/g'` + FILE_VCF_STATS2=`echo $FILE_SAM | sed 's/.sam/-stats-vcf-2.txt/g'` + + # convert SAM file to BAM format + $SAMTOOLSDIR/samtools view -Sb -o $FILE_BAM $FILE_SAM + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # get the aligment statistic in a file + $SAMTOOLSDIR/samtools flagstat $FILE_BAM >$FILE_BAM_STATS + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # convert the BAM file to BED format + $BEDTOOLSDIR/bedtools bamtobed -i $FILE_BAM > $FILE_BED + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # sort the BAM file + $SAMTOOLSDIR/samtools sort $FILE_BAM $FILE_SORTED + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # index the BAM file + $SAMTOOLSDIR/samtools index $FILE_SORTED_BAM + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # convert the BAM file to VCF format + $SAMTOOLSDIR/samtools mpileup -uf $GENOMESDIR/$GENOME $FILE_SORTED_BAM | $BCFTOOLSDIR/bcftools view -vcg - > $FILE_VCF + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # get the variant statistic in a file with SAMtools + $BCFTOOLSDIR/vcfutils.pl qstats $FILE_VCF > $FILE_VCF_STATS1 + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # get the variant statistic in a file with VCFtools + vcftools --vcf $FILE_VCF > $FILE_VCF_STATS2 + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $ALIGNDIR/sam-files.txt + +#------------------------------------------------------------------------------- + +# Get the distinct loci list with mutations + +echo '**************************************************' +echo 'THE DISTINCT LOCI LIST WITH MUTATIONS ARE BEING GOT ...' + +LOCI_FILE=$ALIGNDIR/loci.txt +cat >$LOCI_FILE < $ALIGNDIR/vcf-files.txt + +while read FILE_VCF; do + + while read -r LINE; do + + if [[ $LINE =~ ^#.*$ ]]; then continue; fi + + echo ""$LINE"" | cut -f 1,2 >> $LOCI_FILE + + done < $FILE_VCF + +done < $ALIGNDIR/vcf-files.txt + +sort -u $LOCI_FILE > $DISTINCT_LOCI_FILE + +DISTINCT_LOCI_TOTAL=`wc -l $DISTINCT_LOCI_FILE | cut -f1 -d' '` +echo ""The dictinct loci list contains $DISTINCT_LOCI_TOTAL loci."" +echo ""$DISTINCT_LOCI_TOTAL"" > $DISTINCT_LOCI_TOTAL_FILE + +#------------------------------------------------------------------------------- + +# End +echo '**************************************************' +exit 0 + +#------------------------------------------------------------------------------- +","Shell" +"In Silico","GGFHF/ddRADseqTools","Package/simulation-scripts/simulation-test-se-fasta.sh",".sh","9592","269","#!/bin/bash + +#------------------------------------------------------------------------------- + +# This software has been developed by Forest Genetics and Physiology Research Group, +# Technical University of Madrid (UPM) + +# Licence: GNU General Public Licence Version 3 + +#------------------------------------------------------------------------------- + +# This script executes a test of each program of the software package ddRADseqTools + +#------------------------------------------------------------------------------- + +# Control parameters + +if [ -n ""$*"" ]; then echo 'This script has not parameters.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Set run environment + +DDRADSEQTOOLSDIR=$TRABAJO/ddRADseqTools # ddRADseqTools programs directory +GENOMESDIR=$TRABAJO/ddRADseqTools/genomes # genomes file directory +FRAGSDIR=$TRABAJO/ddRADseqTools/fragments # fragments directory +READSDIR=$TRABAJO/ddRADseqTools/reads # reads directory +STATSDIR=$TRABAJO/ddRADseqTools/statistics # statistics directory + +if [ ! -d ""$FRAGSDIR"" ]; then mkdir $FRAGSDIR; fi +if [ ! -d ""$READSDIR"" ]; then mkdir $READSDIR; else rm -f $READSDIR/*; fi +if [ ! -d ""$STATSDIR"" ]; then mkdir $STATSDIR; else rm -f $STATSDIR/*; fi + +GENOME_SCEREVISIAE=GCF_000146045.2_R64_genomic.fna.gz # Saccharomyces cerevisiae genome +GENOME_CELEGANS=GCF_000002985.6_WBcel235_genomic.fna.gz # Caenorhabditis elegans genome +GENOME_DMELANOGASTERe=GCF_000001215.4_Release_6_plus_ISO1_MT_genomic.fna.gz # Drosophila melanogaster genome +GENOME_HSAPIENS=GCF_000001405.29_GRCh38.p3_genomic.fna.gz # Homo sapiens genome +GENOME_QROBUR=ena.fasta # Quercus robur genome +GENOME_PTAEDA=ptaeda.v1.01.scaffolds.fasta.gz # Pinus taeda genome +GENOME=$GENOME_SCEREVISIAE # genome used in this run + +ENZYME1=EcoRI +ENZYME2=MseI +TECHNIQUE=IND1_DBR +FORMAT=FASTA +READTYPE=SE +INDEX1LEN=6 +INDEX2LEN=0 +DBRLEN=4 +WEND=end61 +CEND=end62 +INDIVIDUALSFILE=individuals-24index1.txt + +if [ `ulimit -n` -lt 1024 ]; then ulimit -n 1024; fi + +#------------------------------------------------------------------------------- + +# Generate genome fragments and get statistics + +echo '**************************************************' +echo 'GENOME FRAGMENTS ARE BEING GENERATED FROM GENOME ...' + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/rsitesearch.py \ + --genfile=$GENOMESDIR/$GENOME \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --minfragsize=101 \ + --maxfragsize=300 \ + --fragstfile=$STATSDIR/fragments-genome-stats.txt \ + --fragstinterval=25 \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Generate random fragments and get statistics + +echo '**************************************************' +echo 'GENOME FRAGMENTS ARE BEING GENERATED RANDOMLY ...' + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/fragsgeneration.py \ + --fragsfile=$FRAGSDIR/fragments-random.fasta \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --fragsnum=3103 \ + --minfragsize=101 \ + --maxfragsize=300 \ + --fragstfile=$STATSDIR/fragments-random-stats.txt \ + --fragstinterval=25 \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Locate several sequences into the genome + +echo '**************************************************' +echo 'SEVERAL SEQUENCES ARE BEING LOCATED ...' + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/seqlocation.py \ + --genfile=$GENOMESDIR/$GENOME \ + --seq=aattcTGGGTGGAACTAGTAGCTGGAGATGCGTTCTAAAGGATCTAAAATCAGACTCACCCCAAAAACCAAAATTTTGATATTCAACTTTAGTATTAGCCAGTCt + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/seqlocation.py \ + --genfile=$GENOMESDIR/$GENOME \ + --seq=aattcAAGAACATCTCGAAGCCAGAATTGAGCATCATATATTCGAGCTGTACAAACATCATGGCCTACAACTATCGTATTTGTAAGTTTTTTTAGAGGTTTTCATATTTGTt + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/seqlocation.py \ + --genfile=$GENOMESDIR/$GENOME \ + --seq=aattcGAAGTAGTGTACCACATTTGTAAGTTTAGATGCCTATTGGAAATGAGCGGGTACAAAAATGACGGGCTTTATTATGCTGTTTGACATAGTATACACAGCAGTTGTGGTGt + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/seqlocation.py \ + --genfile=$GENOMESDIR/$GENOME \ + --seq=aattcTTTATAATCCAGACCTCCCAAAAGAGGCAATCGTCAACTTCTGTCAATCTATTCTAGATGCTACTATCTCTGATTCAGCAAAATACCAAATTGGTAATACCAAAATTTTCTt + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Generate ddRADseq simulated reads + +echo '**************************************************' +echo 'DDRADSEQ SIMULATED READS ARE BEING GENERATED ...' + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/simddradseq.py \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readsfile=$READSDIR/reads \ + --readtype=$READTYPE \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --locinum=3000 \ + --readsnum=300000 \ + --minreadvar=0.8 \ + --maxreadvar=1.2 \ + --insertlen=100 \ + --mutprob=0.2 \ + --locusmaxmut=1 \ + --indelprob=0.1 \ + --maxindelsize=10 \ + --dropout=0.0 \ + --pcrdupprob=0.2 \ + --pcrdistribution=MULTINOMIAL \ + --multiparam=0.167,0.152,0.136,0.121,0.106,0.091,0.076,0.061,0.045,0.030,0.015 \ + --poissonparam=1.0 \ + --gcfactor=0.2 \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Remove the PCR duplicates + +echo '**************************************************' +echo 'THE PRC DUPLICATES ARE BEING REMOVED ...' + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/pcrdupremoval.py \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --readsfile1=$READSDIR/reads.fasta \ + --readsfile2=NONE \ + --clearfile=$READSDIR/reads-cleared \ + --dupstfile=$STATSDIR/pcrduplicates-stats.txt \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Demultiplex the individual files + +echo '**************************************************' +echo 'INDIVIDUAL FILES ARE BEING DEMULTIPLEXED ...' + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/indsdemultiplexing.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --readsfile1=$READSDIR/reads-cleared.fasta \ + --readsfile2=NONE \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Trim adapters and other Illumina-specific sequences from reads + +echo '**************************************************' +echo 'ADAPTERS AND OTHER ILLUMINA SPECIFIC SEQUENCES ARE BEING TRIMMED IN INDIVIDUAL FILES ...' + +ls $READSDIR/demultiplexed-ind*-1.fasta > $READSDIR/reads-files.txt + +while read FILE_1; do + + FILE_TRIMMED=`echo $FILE_1 | sed 's/-1.fasta/-trimmed/g'` + + /usr/bin/time \ + $DDRADSEQTOOLSDIR/readstrim.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --readsfile1=$FILE_1 \ + --readsfile2=NONE \ + --trimfile=$FILE_TRIMMED \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $READSDIR/reads-files.txt + +#------------------------------------------------------------------------------- + +# End +echo '**************************************************' +exit 0 + +#------------------------------------------------------------------------------- +","Shell" +"In Silico","GGFHF/ddRADseqTools","Package/simulation-scripts/simulation-mutations.sh",".sh","6729","194","#!/bin/bash + +#------------------------------------------------------------------------------- + +# This script generates fragments from a genome, simulates a double digest, +# generates their reads, removes PCR duplicates, demultiplexes the individuals +# calcultes a statistics of mutated reads and no mutared reads of each individual + +#------------------------------------------------------------------------------- + +# Control parameters + +if [ -n ""$*"" ]; then echo 'This script has not parameters.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Set run environment + +SAMTOOLSDIR=/usr/share/samtools # SAMTools directory + +DDRADSEQTOOLSDIR=$TRABAJO/ddRADseqTools/Exe # ddRADseqTools programs directory +FRAGSDIR=$TRABAJO/ddRADseqTools/Fragments # fragments directory +READSDIR=$TRABAJO/ddRADseqTools/Reads # reads directory +STATSDIR=$TRABAJO/ddRADseqTools/Statistics # statistics directory +ALIGNDIR=$TRABAJO/ddRADseqTools/Alignments # alignments directory + +if [ ! -d ""$FRAGSDIR"" ]; then mkdir $FRAGSDIR; fi +if [ ! -d ""$READSDIR"" ]; then mkdir $READSDIR; else rm -f $READSDIR/*; fi +if [ ! -d ""$STATSDIR"" ]; then mkdir $STATSDIR; else rm -f $STATSDIR/*; fi +if [ ! -d ""$ALIGNDIR"" ]; then mkdir $ALIGNDIR; else rm -f $ALIGNDIR/*; fi + +SCEREVISIAE='Scerevisiae' # Saccharomyces cerevisiae +SCEREVISIAE_FRAGS_FILE=$SCEREVISIAE'-fragments-EcoRI-MseI.fasta' # Saccharomyces cerevisiae framents gotten by EcoI and MseI digest +MUTPROB=(0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9) + +ENZYME1=EcoRI +ENZYME2=MseI +TECHNIQUE=IND1_IND2_DBR +FORMAT=FASTQ +READTYPE=PE +INDEX1LEN=6 +INDEX2LEN=6 +DBRLEN=4 +WEND=end31 +CEND=end32 +INDIVIDUALSFILE=individuals-8index1-6index2.txt + +if [ `ulimit -n` -lt 1024 ]; then ulimit -n 1024; fi + +#------------------------------------------------------------------------------- + +echo '**************************************************' +echo 'GENERATION OF READS AND STATISTICS' + +for I in ""${MUTPROB[@]}"" +do + + # Generate ddRADseq simulated reads + + echo '--------------------------------------------------' + echo ""DDRADSEQ SIMULATED READS ARE BEING GENERATED WITH MUTPROB=$I ..."" + + $DDRADSEQTOOLSDIR/simddradseq.py \ + --fragsfile=$FRAGSDIR/$SCEREVISIAE_FRAGS_FILE \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readsfile=$READSDIR/$SCEREVISIAE'-reads-'$I \ + --readtype=$READTYPE \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --locinum=3000 \ + --readsnum=300000 \ + --minreadvar=0.8 \ + --maxreadvar=1.2 \ + --insertlen=100 \ + --mutprob=$I \ + --locusmaxmut=1 \ + --indelprob=0.1 \ + --maxindelsize=10 \ + --dropout=0.0 \ + --pcrdupprob=0.2 \ + --pcrdistribution=MULTINOMIAL \ + --multiparam=0.167,0.152,0.136,0.121,0.106,0.091,0.076,0.061,0.045,0.030,0.015 \ + --poissonparam=1.0 \ + --gcfactor=0.2 \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # Remove the PCR duplicates + + echo '--------------------------------------------------' + echo 'THE PRC DUPLICATES ARE BEING REMOVED ...' + + $DDRADSEQTOOLSDIR/pcrdupremoval.py \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --readsfile1=$READSDIR/$SCEREVISIAE'-reads-'$I'-1.fastq' \ + --readsfile2=$READSDIR/$SCEREVISIAE'-reads-'$I'-2.fastq' \ + --clearfile=$READSDIR/$SCEREVISIAE'-reads-cleared-'$I \ + --dupstfile=$STATSDIR/$SCEREVISIAE'-pcrduplicates-stats-'$I'.txt' \ + --plot=YES \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # Demultiplex the individual files + + echo '--------------------------------------------------' + echo 'INDIVIDUAL FILES ARE BEING DEMULTIPLEXED ...' + + $DDRADSEQTOOLSDIR/indsdemultiplexing.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --readsfile1=$READSDIR/$SCEREVISIAE'-reads-cleared-'$I'-1.fastq' \ + --readsfile2=$READSDIR/$SCEREVISIAE'-reads-cleared-'$I'-2.fastq' \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + ls $READSDIR/demultiplexed-*-1.fastq > $READSDIR/reads-files.txt + + while read FILE_1; do + + FILE_1_R=`echo $FILE_1 | sed 's/demultiplexed/'$SCEREVISIAE'-demultiplexed-'$I'/g'` + FILE_2=`echo $FILE_1 | sed 's/-1.fastq/-2.fastq/g'` + FILE_2_R=`echo $FILE_2 | sed 's/demultiplexed/'$SCEREVISIAE'-demultiplexed-'$I'/g'` + + mv $FILE_1 $FILE_1_R + mv $FILE_2 $FILE_2_R + + done < $READSDIR/reads-files.txt + + # Calcultes a statistics of mutated reads and no mutared reads of each individual + + echo '--------------------------------------------------' + echo 'MUTATION STATISTICS ARE BEING CALCULATED ...' + + FILE_STATS=$STATSDIR/$SCEREVISIAE'-mutations-stats-'$I'.csv' +cat >$FILE_STATS < $READSDIR/reads-files.txt + + while read FILE_1; do + + gawk 'function ltrim(s) { sub(/^[ \t\r\n]+/, """", s); return s } + + function rtrim(s) { sub(/[ \t\r\n]+$/, """", s); return s } + + function trim(s) { return rtrim(ltrim(s)) } + + BEGIN { FS = ""|""; mutated_reads = 0; no_mutated_reads = 0 } + + /@/ { if (FNR = 1) individual = trim(substr($6, 14, length($6))) } + + /mutated: True/ { ++mutated_reads } + + /mutated: False/ { ++no_mutated_reads } + + END { printf ""%s;%d;%d;\n"", individual, no_mutated_reads, mutated_reads } + + ' $FILE_1 >> $FILE_STATS + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + done < $READSDIR/reads-files.txt + +done + +#------------------------------------------------------------------------------- + +# End +echo '**************************************************' +exit 0 + +#------------------------------------------------------------------------------- +","Shell" +"In Silico","GGFHF/ddRADseqTools","Package/simulation-scripts/simulation-test-pe-fastq.sh",".sh","9713","270","#!/bin/bash + +#------------------------------------------------------------------------------- + +# This software has been developed by Forest Genetics and Physiology Research Group, +# Technical University of Madrid (UPM) + +# Licence: GNU General Public Licence Version 3 + +#------------------------------------------------------------------------------- + +# This script executes a test of each program of the software package ddRADseqTools + +#------------------------------------------------------------------------------- + +# Control parameters + +if [ -n ""$*"" ]; then echo 'This script has not parameters.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Set run environment + +DDRADSEQTOOLSDIR=$TRABAJO/ddRADseqTools # ddRADseqTools programs directory +GENOMESDIR=$TRABAJO/ddRADseqTools/genomes # genomes file directory +FRAGSDIR=$TRABAJO/ddRADseqTools/fragments # fragments directory +READSDIR=$TRABAJO/ddRADseqTools/reads # reads directory +STATSDIR=$TRABAJO/ddRADseqTools/statistics # statistics directory + +if [ ! -d ""$FRAGSDIR"" ]; then mkdir $FRAGSDIR; fi +if [ ! -d ""$READSDIR"" ]; then mkdir $READSDIR; else rm -f $READSDIR/*; fi +if [ ! -d ""$STATSDIR"" ]; then mkdir $STATSDIR; else rm -f $STATSDIR/*; fi + +GENOME_SCEREVISIAE=GCF_000146045.2_R64_genomic.fna.gz # Saccharomyces cerevisiae genome +GENOME_CELEGANS=GCF_000002985.6_WBcel235_genomic.fna.gz # Caenorhabditis elegans genome +GENOME_DMELANOGASTERe=GCF_000001215.4_Release_6_plus_ISO1_MT_genomic.fna.gz # Drosophila melanogaster genome +GENOME_HSAPIENS=GCF_000001405.29_GRCh38.p3_genomic.fna.gz # Homo sapiens genome +GENOME_QROBUR=ena.fasta # Quercus robur genome +GENOME_PTAEDA=ptaeda.v1.01.scaffolds.fasta.gz # Pinus taeda genome +GENOME=$GENOME_SCEREVISIAE # genome used in this run + +ENZYME1=EcoRI +ENZYME2=MseI +TECHNIQUE=IND1_IND2_DBR +FORMAT=FASTQ +READTYPE=PE +INDEX1LEN=6 +INDEX2LEN=6 +DBRLEN=4 +WEND=end91 +CEND=end92 +INDIVIDUALSFILE=individuals-8index1-6index2.txt + +if [ `ulimit -n` -lt 1024 ]; then ulimit -n 1024; fi + +#------------------------------------------------------------------------------- + +# Generate genome fragments and get statistics + +echo '**************************************************' +echo 'GENOME FRAGMENTS ARE BEING GENERATED FROM GENOME ...' + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/rsitesearch.py \ + --genfile=$GENOMESDIR/$GENOME \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --minfragsize=101 \ + --maxfragsize=300 \ + --fragstfile=$STATSDIR/fragments-genome-stats.txt \ + --fragstinterval=25 \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Generate random fragments and get statistics + +echo '**************************************************' +echo 'GENOME FRAGMENTS ARE BEING GENERATED RANDOMLY ...' + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/fragsgeneration.py \ + --fragsfile=$FRAGSDIR/fragments-random.fasta \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --fragsnum=3103 \ + --minfragsize=101 \ + --maxfragsize=300 \ + --fragstfile=$STATSDIR/fragments-random-stats.txt \ + --fragstinterval=25 \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Locate several sequences into the genome + +echo '**************************************************' +echo 'SEVERAL SEQUENCES ARE BEING LOCATED ...' + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/seqlocation.py \ + --genfile=$GENOMESDIR/$GENOME \ + --seq=aattcTGGGTGGAACTAGTAGCTGGAGATGCGTTCTAAAGGATCTAAAATCAGACTCACCCCAAAAACCAAAATTTTGATATTCAACTTTAGTATTAGCCAGTCt + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/seqlocation.py \ + --genfile=$GENOMESDIR/$GENOME \ + --seq=aattcAAGAACATCTCGAAGCCAGAATTGAGCATCATATATTCGAGCTGTACAAACATCATGGCCTACAACTATCGTATTTGTAAGTTTTTTTAGAGGTTTTCATATTTGTt + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/seqlocation.py \ + --genfile=$GENOMESDIR/$GENOME \ + --seq=aattcGAAGTAGTGTACCACATTTGTAAGTTTAGATGCCTATTGGAAATGAGCGGGTACAAAAATGACGGGCTTTATTATGCTGTTTGACATAGTATACACAGCAGTTGTGGTGt + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/seqlocation.py \ + --genfile=$GENOMESDIR/$GENOME \ + --seq=aattcTTTATAATCCAGACCTCCCAAAAGAGGCAATCGTCAACTTCTGTCAATCTATTCTAGATGCTACTATCTCTGATTCAGCAAAATACCAAATTGGTAATACCAAAATTTTCTt + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Generate ddRADseq simulated reads + +echo '**************************************************' +echo 'DDRADSEQ SIMULATED READS ARE BEING GENERATED ...' + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/simddradseq.py \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readsfile=$READSDIR/reads \ + --readtype=$READTYPE \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --locinum=3000 \ + --readsnum=300000 \ + --minreadvar=0.8 \ + --maxreadvar=1.2 \ + --insertlen=100 \ + --mutprob=0.2 \ + --locusmaxmut=1 \ + --indelprob=0.1 \ + --maxindelsize=10 \ + --dropout=0.0 \ + --pcrdupprob=0.2 \ + --pcrdistribution=MULTINOMIAL \ + --multiparam=0.167,0.152,0.136,0.121,0.106,0.091,0.076,0.061,0.045,0.030,0.015 \ + --poissonparam=1.0 \ + --gcfactor=0.2 \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Remove the PCR duplicates + +echo '**************************************************' +echo 'THE PRC DUPLICATES ARE BEING REMOVED ...' + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/pcrdupremoval.py \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --readsfile1=$READSDIR/reads-1.fastq \ + --readsfile2=$READSDIR/reads-2.fastq \ + --clearfile=$READSDIR/reads-cleared \ + --dupstfile=$STATSDIR/pcrduplicates-stats.txt \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Demultiplex the individual files + +echo '**************************************************' +echo 'INDIVIDUAL FILES ARE BEING DEMULTIPLEXED ...' + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/indsdemultiplexing.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --readsfile1=$READSDIR/reads-cleared-1.fastq \ + --readsfile2=$READSDIR/reads-cleared-2.fastq \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Trim adapters and other Illumina-specific sequences from reads + +echo '**************************************************' +echo 'ADAPTERS AND OTHER ILLUMINA SPECIFIC SEQUENCES ARE BEING TRIMMED IN INDIVIDUAL FILES ...' + +ls $READSDIR/demultiplexed-ind*-1.fastq > $READSDIR/reads-files.txt + +while read FILE_1; do + + FILE_2=`echo $FILE_1 | sed 's/-1.fastq/-2.fastq/g'` + FILE_TRIMMED=`echo $FILE_1 | sed 's/-1.fastq/-trimmed/g'` + + /usr/bin/time \ + $DDRADSEQTOOLSDIR/readstrim.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --readsfile1=$FILE_1 \ + --readsfile2=$FILE_2 \ + --trimfile=$FILE_TRIMMED \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $READSDIR/reads-files.txt + +#------------------------------------------------------------------------------- + +# End +echo '**************************************************' +exit 0 + +#------------------------------------------------------------------------------- +","Shell" +"In Silico","GGFHF/ddRADseqTools","Package/simulation-scripts/simulation-pipeline-Hsapiens-pe.sh",".sh","10981","327","#!/bin/bash + +#------------------------------------------------------------------------------- + +# This script generates fragments from the Homo sapiens, simulates a double +# digest, generates their PE reads, removes PCR duplicates, demultiplexes +# the individuals, trims the adapters and other Illumina specific sequences, aligns +# the reads and gets SAM, BAM, BED and VCF format files to study and visualize +# alignments + +#------------------------------------------------------------------------------- + +# WARNING + +# This script uses the following bioinformatics tools: +# - BWA v0.7.13 (http://bio-bwa.sourceforge.net/) +# - SAMtools & BCFtools v0.1.19 (http://www.htslib.org/) +# - BEDtools v2.25.0 (http://bedtools.readthedocs.io/) +# - VCFtools v0.1.14-14 (https://vcftools.github.io/) + +#------------------------------------------------------------------------------- + +# Control parameters + +if [ -n ""$*"" ]; then echo 'This script has not parameters.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Set run environment + +SAMTOOLSDIR=/usr/share/samtools # SAMTools directory + +DDRADSEQTOOLSDIR=$TRABAJO/ddRADseqTools # ddRADseqTools programs directory +GENOMESDIR=$TRABAJO/ddRADseqTools/genomes # genomes file directory +FRAGSDIR=$TRABAJO/ddRADseqTools/fragments # fragments directory +READSDIR=$TRABAJO/ddRADseqTools/reads # reads directory +STATSDIR=$TRABAJO/ddRADseqTools/statistics # statistics directory +ALIGNDIR=$TRABAJO/ddRADseqTools/alignments # alignments directory + +if [ ! -d ""$FRAGSDIR"" ]; then mkdir $FRAGSDIR; fi +if [ ! -d ""$READSDIR"" ]; then mkdir $READSDIR; else rm -f $READSDIR/*; fi +if [ ! -d ""$STATSDIR"" ]; then mkdir $STATSDIR; else rm -f $STATSDIR/*; fi +if [ ! -d ""$ALIGNDIR"" ]; then mkdir $ALIGNDIR; else rm -f $ALIGNDIR/*; fi + +GENOME=GCF_000001405.29_GRCh38.p3_genomic.fna.gz # Homo sapiens genome + +ENZYME1=SbfI +ENZYME2=MseI +TECHNIQUE=IND1_IND2_DBR +FORMAT=FASTQ +READTYPE=PE +INDEX1LEN=6 +INDEX2LEN=6 +DBRLEN=4 +WEND=end31 +CEND=end32 +INDIVIDUALSFILE=individuals-8index1-6index2.txt + +if [ `ulimit -n` -lt 1024 ]; then ulimit -n 1024; fi + +#------------------------------------------------------------------------------- + +# Generate genome fragments and get statistics + +echo '**************************************************' +echo 'GENOME FRAGMENTS ARE BEING GENERATED FROM GENOME ...' + +$DDRADSEQTOOLSDIR/rsitesearch.py \ + --genfile=$GENOMESDIR/$GENOME \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --minfragsize=201 \ + --maxfragsize=300 \ + --fragstfile=$STATSDIR/fragments-genome-stats.txt \ + --fragstinterval=25 \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Generate ddRADseq simulated reads + +echo '**************************************************' +echo 'DDRADSEQ SIMULATED READS ARE BEING GENERATED ...' + +$DDRADSEQTOOLSDIR/simddradseq.py \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readsfile=$READSDIR/reads \ + --readtype=$READTYPE \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --locinum=3000 \ + --readsnum=300000 \ + --minreadvar=0.8 \ + --maxreadvar=1.2 \ + --insertlen=100 \ + --mutprob=0.2 \ + --locusmaxmut=1 \ + --indelprob=0.1 \ + --maxindelsize=10 \ + --dropout=0.05 \ + --pcrdupprob=0.2 \ + --pcrdistribution=MULTINOMIAL \ + --multiparam=0.167,0.152,0.136,0.121,0.106,0.091,0.076,0.061,0.045,0.030,0.015 \ + --poissonparam=1.0 \ + --gcfactor=0.2 \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Remove the PCR duplicates + +echo '**************************************************' +echo 'THE PRC DUPLICATES ARE BEING REMOVED ...' + +$DDRADSEQTOOLSDIR/pcrdupremoval.py \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --readsfile1=$READSDIR/reads-1.fastq \ + --readsfile2=$READSDIR/reads-2.fastq \ + --clearfile=$READSDIR/reads-cleared \ + --dupstfile=$STATSDIR/pcrduplicates-stats.txt \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Demultiplex the individual files + +echo '**************************************************' +echo 'INDIVIDUAL FILES ARE BEING DEMULTIPLEXED ...' + +$DDRADSEQTOOLSDIR/indsdemultiplexing.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --readsfile1=$READSDIR/reads-cleared-1.fastq \ + --readsfile2=$READSDIR/reads-cleared-2.fastq \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Trim adapters and other Illumina-specific sequences from reads + +echo '**************************************************' +echo 'ADAPTERS AND OTHER ILLUMINA SPECIFIC SEQUENCES ARE BEING TRIMMED IN INDIVIDUAL FILES ...' + +ls $READSDIR/demultiplexed-*-1.fastq > $READSDIR/reads-files.txt + +while read FILE_1; do + + if [[ $FILE_1 =~ .*errors.* ]]; then continue; fi + + FILE_2=`echo $FILE_1 | sed 's/-1.fastq/-2.fastq/g'` + FILE_TRIMMED=`echo $FILE_1 | sed 's/-1.fastq/-trimmed/g'` + + $DDRADSEQTOOLSDIR/readstrim.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --readsfile1=$FILE_1 \ + --readsfile2=$FILE_2 \ + --trimfile=$FILE_TRIMMED \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $READSDIR/reads-files.txt + +#------------------------------------------------------------------------------- + +# Index the genome + +echo '**************************************************' +echo 'GENOME IS BEING INDEXED ...' + + +bwa index -a bwtsw $GENOMESDIR/$GENOME +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + +#------------------------------------------------------------------------------- + +# Align sequences of individual files in SAM format + +echo '**************************************************' +echo 'SEQUENCES OF INDIVIDUAL FILES ARE BEING ALIGNED IN SAM FORMAT ...' + +ls $READSDIR/demultiplexed-*-trimmed-1.fastq > $READSDIR/reads-trimmed-files.txt + +while read FILE1_TRIM; do + + FILE2_TRIM=`echo $FILE1_TRIM | sed 's/-trimmed-1.fastq/-trimmed-2.fastq/g'` + FILE_SAM=`echo $FILE1_TRIM | sed 's/-1.fastq/.sam/g' | sed ""s|$READSDIR|$ALIGNDIR|g""` + bwa mem $GENOMESDIR/$GENOME $FILE1_TRIM $FILE2_TRIM > $FILE_SAM + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $READSDIR/reads-trimmed-files.txt + +#------------------------------------------------------------------------------- + +# Convert SAM files to BED, BAM and VCF format + +echo '**************************************************' +echo 'SAM FILES ARE BEING CONVERTED IN BAM, BED AND VCF FORMAT ...' + +ls $ALIGNDIR/*.sam > $ALIGNDIR/sam-files.txt + +while read FILE_SAM; do + + FILE_BAM=`echo $FILE_SAM | sed 's/.sam/.bam/g'` + FILE_BAM_STATS=`echo $FILE_SAM | sed 's/.sam/-stats-bam.txt/g'` + FILE_BED=`echo $FILE_SAM | sed 's/.sam/.bed/g'` + FILE_SORTED=`echo $FILE_SAM | sed 's/.sam/.sorted/g'` + FILE_SORTED_BAM=`echo $FILE_SAM | sed 's/.sam/.sorted.bam/g'` + FILE_VCF=`echo $FILE_SAM | sed 's/.sam/.vcf/g'` + FILE_VCF_STATS1=`echo $FILE_SAM | sed 's/.sam/-stats-vcf-1.txt/g'` + FILE_VCF_STATS2=`echo $FILE_SAM | sed 's/.sam/-stats-vcf-2.txt/g'` + + # convert SAM file to BAM format + samtools view -bS $FILE_SAM >$FILE_BAM + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # get aligment statistic in a file + samtools flagstat $FILE_BAM >$FILE_BAM_STATS + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # convert BAM file to BED format + bedtools bamtobed -i $FILE_BAM > $FILE_BED + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # sort the BAM file + samtools sort $FILE_BAM $FILE_SORTED + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # index the BAM file + samtools index $FILE_SORTED_BAM + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # convert BAM file to VCF format + samtools mpileup -uf $GENOMESDIR/$GENOME $FILE_SORTED_BAM | bcftools view -vcg - > $FILE_VCF + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # get variant statistic in a file with SAMtools + $SAMTOOLSDIR/vcfutils.pl qstats $FILE_VCF > $FILE_VCF_STATS1 + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # get variant statistic in a file with VCFtools + vcftools --vcf $FILE_VCF > $FILE_VCF_STATS2 + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $ALIGNDIR/sam-files.txt + +#------------------------------------------------------------------------------- + +# Get the distinct loci list with mutations + +echo '**************************************************' +echo 'THE DISTINCT LOCI LIST WITH MUTATIONS ARE BEING GOT ...' + +LOCI_FILE=$ALIGNDIR/loci.txt +cat >$LOCI_FILE < $ALIGNDIR/vcf-files.txt + +while read FILE_VCF; do + + while read -r LINE; do + + if [[ $LINE =~ ^#.*$ ]]; then continue; fi + + echo ""$LINE"" | cut -f 1,2 >> $LOCI_FILE + + done < $FILE_VCF + +done < $ALIGNDIR/vcf-files.txt + +sort -u $LOCI_FILE > $DISTINCT_LOCI_FILE + +DISTINCT_LOCI_TOTAL=`wc -l $DISTINCT_LOCI_FILE | cut -f1 -d' '` +echo ""The dictinct loci list contains $DISTINCT_LOCI_TOTAL loci."" +echo ""$DISTINCT_LOCI_TOTAL"" > $DISTINCT_LOCI_TOTAL_FILE + +#------------------------------------------------------------------------------- + +# End +echo '**************************************************' +exit 0 + +#------------------------------------------------------------------------------- +","Shell" +"In Silico","GGFHF/ddRADseqTools","Package/simulation-scripts/simulation-poissonparam.sh",".sh","4795","124","#!/bin/bash + +#------------------------------------------------------------------------------- + +# This script analyses the effect of parameter lambda of Poisson distribution in +# the calculation of the PCR duplicates number of each locus of each individual. + +#------------------------------------------------------------------------------- + +# Control parameters + +if [ -n ""$*"" ]; then echo 'This script has not parameters'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Set run environment + +DDRADSEQTOOLSDIR=$TRABAJO/ddRADseqTools/Exe # ddRADseqTools programs directory +FRAGSDIR=$TRABAJO/ddRADseqTools/Fragments # fragments directory +READSDIR=$TRABAJO/ddRADseqTools/Reads # reads directory +STATSDIR=$TRABAJO/ddRADseqTools/Statistics # statistics directory + +if [ ! -d ""$READSDIR"" ]; then mkdir $READSDIR; else rm -f $READSDIR/*; fi +if [ ! -d ""$STATSDIR"" ]; then mkdir $STATSDIR; else rm -f $STATSDIR/*; fi + +SCEREVISIAE='Scerevisiae' # Saccharomyces cerevisiae +SCEREVISIAE_FRAGS_FILE=$SCEREVISIAE'-fragments-EcoRI-MseI.fasta' # Saccharomyces cerevisiae framents gotten by EcoI and MseI digest +SCEREVISIAE_READSNUM=(600000 1200000) # Saccharomyces cerevisiae readsnum values +SCEREVISIAE_PCRDUPPROB=(0.2 0.4 0.6) # Saccharomyces cerevisiae pcrdupprob values +SCEREVISIAE_POISSONPARAM=(0.2 0.4 0.6 0.8 1.0 1.2 1.4 1.6 1.8 2.0) # Saccharomyces cerevisiae parameter lambda values + +TECHNIQUE=IND1_IND2_DBR +FORMAT=FASTQ +READTYPE=PE +INDEX1LEN=6 +INDEX2LEN=6 +DBRLEN=4 +WEND=end31 +CEND=end32 +INDIVIDUALSFILE=individuals-8index1-6index2.txt + +#------------------------------------------------------------------------------- + +# Generate ddRADseq simulated reads of Saccharomyces cerevisiae + +echo '**************************************************' +echo 'SACCHAROMYCES CEREVISIAE' + +for I in ""${SCEREVISIAE_READSNUM[@]}"" +do + for J in ""${SCEREVISIAE_PCRDUPPROB[@]}"" + do + for K in ""${SCEREVISIAE_POISSONPARAM[@]}"" + do + + # Generate ddRADseq simulated reads + + echo '--------------------------------------------------' + echo ""SIMULATION WITH READSNUM=$I AND PCRDUPPROB=$J AND POISSONPARAM=$K ..."" + + $DDRADSEQTOOLSDIR/simddradseq.py \ + --fragsfile=$FRAGSDIR/$SCEREVISIAE_FRAGS_FILE \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readsfile=$READSDIR/$SCEREVISIAE'-reads-'$I'-'$J'-'$K \ + --readtype=$READTYPE \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=EcoRI \ + --enzyme2=MseI \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --locinum=3000 \ + --readsnum=$I \ + --minreadvar=0.8 \ + --maxreadvar=1.2 \ + --insertlen=100 \ + --mutprob=0.2 \ + --locusmaxmut=1 \ + --indelprob=0.1 \ + --maxindelsize=10 \ + --dropout=0.0 \ + --pcrdupprob=$J \ + --pcrdistribution=POISSON \ + --multiparam=0.333,0.267,0.200,0.133,0.067 \ + --poissonparam=$K \ + --gcfactor=0.2 \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # Remove the PCR duplicates + + echo '--------------------------------------------------' + echo ""REMOVING PCR DUPLICATES ..."" + + $DDRADSEQTOOLSDIR/pcrdupremoval.py \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --readsfile1=$READSDIR/$SCEREVISIAE'-reads-'$I'-'$J'-'$K'-1.fastq' \ + --readsfile2=$READSDIR/$SCEREVISIAE'-reads-'$I'-'$J'-'$K'-2.fastq' \ + --clearfile=$READSDIR/$SCEREVISIAE'-reads-cleared-'$I'-'$J'-'$K \ + --dupstfile=$STATSDIR/$SCEREVISIAE'-pcrduplicates-stats-'$I'-'$J'-'$K'.txt' \ + --plot=YES \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + done + done +done + +#------------------------------------------------------------------------------- + +# End +echo '**************************************************' +exit 0 + +#------------------------------------------------------------------------------- +","Shell" +"In Silico","GGFHF/ddRADseqTools","Package/simulation-scripts/simulation-test-pe-fasta.sh",".sh","9713","270","#!/bin/bash + +#------------------------------------------------------------------------------- + +# This software has been developed by Forest Genetics and Physiology Research Group, +# Technical University of Madrid (UPM) + +# Licence: GNU General Public Licence Version 3 + +#------------------------------------------------------------------------------- + +# This script executes a test of each program of the software package ddRADseqTools + +#------------------------------------------------------------------------------- + +# Control parameters + +if [ -n ""$*"" ]; then echo 'This script has not parameters.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Set run environment + +DDRADSEQTOOLSDIR=$TRABAJO/ddRADseqTools # ddRADseqTools programs directory +GENOMESDIR=$TRABAJO/ddRADseqTools/genomes # genomes file directory +FRAGSDIR=$TRABAJO/ddRADseqTools/fragments # fragments directory +READSDIR=$TRABAJO/ddRADseqTools/reads # reads directory +STATSDIR=$TRABAJO/ddRADseqTools/statistics # statistics directory + +if [ ! -d ""$FRAGSDIR"" ]; then mkdir $FRAGSDIR; fi +if [ ! -d ""$READSDIR"" ]; then mkdir $READSDIR; else rm -f $READSDIR/*; fi +if [ ! -d ""$STATSDIR"" ]; then mkdir $STATSDIR; else rm -f $STATSDIR/*; fi + +GENOME_SCEREVISIAE=GCF_000146045.2_R64_genomic.fna.gz # Saccharomyces cerevisiae genome +GENOME_CELEGANS=GCF_000002985.6_WBcel235_genomic.fna.gz # Caenorhabditis elegans genome +GENOME_DMELANOGASTERe=GCF_000001215.4_Release_6_plus_ISO1_MT_genomic.fna.gz # Drosophila melanogaster genome +GENOME_HSAPIENS=GCF_000001405.29_GRCh38.p3_genomic.fna.gz # Homo sapiens genome +GENOME_QROBUR=ena.fasta # Quercus robur genome +GENOME_PTAEDA=ptaeda.v1.01.scaffolds.fasta.gz # Pinus taeda genome +GENOME=$GENOME_SCEREVISIAE # genome used in this run + +ENZYME1=EcoRI +ENZYME2=MseI +TECHNIQUE=IND1_IND2_DBR +FORMAT=FASTA +READTYPE=PE +INDEX1LEN=6 +INDEX2LEN=6 +DBRLEN=4 +WEND=end91 +CEND=end92 +INDIVIDUALSFILE=individuals-8index1-6index2.txt + +if [ `ulimit -n` -lt 1024 ]; then ulimit -n 1024; fi + +#------------------------------------------------------------------------------- + +# Generate genome fragments and get statistics + +echo '**************************************************' +echo 'GENOME FRAGMENTS ARE BEING GENERATED FROM GENOME ...' + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/rsitesearch.py \ + --genfile=$GENOMESDIR/$GENOME \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --minfragsize=101 \ + --maxfragsize=300 \ + --fragstfile=$STATSDIR/fragments-genome-stats.txt \ + --fragstinterval=25 \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Generate random fragments and get statistics + +echo '**************************************************' +echo 'GENOME FRAGMENTS ARE BEING GENERATED RANDOMLY ...' + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/fragsgeneration.py \ + --fragsfile=$FRAGSDIR/fragments-random.fasta \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --fragsnum=3103 \ + --minfragsize=101 \ + --maxfragsize=300 \ + --fragstfile=$STATSDIR/fragments-random-stats.txt \ + --fragstinterval=25 \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Locate several sequences into the genome + +echo '**************************************************' +echo 'SEVERAL SEQUENCES ARE BEING LOCATED ...' + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/seqlocation.py \ + --genfile=$GENOMESDIR/$GENOME \ + --seq=aattcTGGGTGGAACTAGTAGCTGGAGATGCGTTCTAAAGGATCTAAAATCAGACTCACCCCAAAAACCAAAATTTTGATATTCAACTTTAGTATTAGCCAGTCt + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/seqlocation.py \ + --genfile=$GENOMESDIR/$GENOME \ + --seq=aattcAAGAACATCTCGAAGCCAGAATTGAGCATCATATATTCGAGCTGTACAAACATCATGGCCTACAACTATCGTATTTGTAAGTTTTTTTAGAGGTTTTCATATTTGTt + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/seqlocation.py \ + --genfile=$GENOMESDIR/$GENOME \ + --seq=aattcGAAGTAGTGTACCACATTTGTAAGTTTAGATGCCTATTGGAAATGAGCGGGTACAAAAATGACGGGCTTTATTATGCTGTTTGACATAGTATACACAGCAGTTGTGGTGt + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/seqlocation.py \ + --genfile=$GENOMESDIR/$GENOME \ + --seq=aattcTTTATAATCCAGACCTCCCAAAAGAGGCAATCGTCAACTTCTGTCAATCTATTCTAGATGCTACTATCTCTGATTCAGCAAAATACCAAATTGGTAATACCAAAATTTTCTt + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Generate ddRADseq simulated reads + +echo '**************************************************' +echo 'DDRADSEQ SIMULATED READS ARE BEING GENERATED ...' + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/simddradseq.py \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readsfile=$READSDIR/reads \ + --readtype=$READTYPE \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --locinum=3000 \ + --readsnum=300000 \ + --minreadvar=0.8 \ + --maxreadvar=1.2 \ + --insertlen=100 \ + --mutprob=0.2 \ + --locusmaxmut=1 \ + --indelprob=0.1 \ + --maxindelsize=10 \ + --dropout=0.0 \ + --pcrdupprob=0.2 \ + --pcrdistribution=MULTINOMIAL \ + --multiparam=0.167,0.152,0.136,0.121,0.106,0.091,0.076,0.061,0.045,0.030,0.015 \ + --poissonparam=1.0 \ + --gcfactor=0.2 \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Remove the PCR duplicates + +echo '**************************************************' +echo 'THE PRC DUPLICATES ARE BEING REMOVED ...' + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/pcrdupremoval.py \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --readsfile1=$READSDIR/reads-1.fasta \ + --readsfile2=$READSDIR/reads-2.fasta \ + --clearfile=$READSDIR/reads-cleared \ + --dupstfile=$STATSDIR/pcrduplicates-stats.txt \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Demultiplex the individual files + +echo '**************************************************' +echo 'INDIVIDUAL FILES ARE BEING DEMULTIPLEXED ...' + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/indsdemultiplexing.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --readsfile1=$READSDIR/reads-cleared-1.fasta \ + --readsfile2=$READSDIR/reads-cleared-2.fasta \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Trim adapters and other Illumina-specific sequences from reads + +echo '**************************************************' +echo 'ADAPTERS AND OTHER ILLUMINA SPECIFIC SEQUENCES ARE BEING TRIMMED IN INDIVIDUAL FILES ...' + +ls $READSDIR/demultiplexed-ind*-1.fasta > $READSDIR/reads-files.txt + +while read FILE_1; do + + FILE_2=`echo $FILE_1 | sed 's/-1.fasta/-2.fasta/g'` + FILE_TRIMMED=`echo $FILE_1 | sed 's/-1.fasta/-trimmed/g'` + + /usr/bin/time \ + $DDRADSEQTOOLSDIR/readstrim.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --readsfile1=$FILE_1 \ + --readsfile2=$FILE_2 \ + --trimfile=$FILE_TRIMMED \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $READSDIR/reads-files.txt + +#------------------------------------------------------------------------------- + +# End +echo '**************************************************' +exit 0 + +#------------------------------------------------------------------------------- +","Shell" +"In Silico","GGFHF/ddRADseqTools","Package/simulation-scripts/simulation-pipeline-Wauropunctata-pe.sh",".sh","11146","328","#!/bin/bash + +#------------------------------------------------------------------------------- + +# This script generates fragments from the Wasmannia auropunctata genome; it +# simulates a double digest and generates their PE reads; it quantifies and +# removes PCR duplicates and calculates the loci number without data; it +# demultiplexes the individuals; it trims the adapters and other Illumina specific +# sequences; it aligns the reads and gets SAM, BAM, BED and VCF format files to +# study and visualize alignments; and it gets the distinct loci list with mutations. + +#------------------------------------------------------------------------------- + +# WARNING + +# This script uses the following bioinformatics tools: +# - BWA v0.7.13 (http://bio-bwa.sourceforge.net/) +# - SAMtools & BCFtools v0.1.19 (http://www.htslib.org/) +# - BEDtools v2.25.0 (http://bedtools.readthedocs.io/) +# - VCFtools v0.1.14-14 (https://vcftools.github.io/) + +#------------------------------------------------------------------------------- + +# Control parameters + +if [ -n ""$*"" ]; then echo 'This script has not parameters.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Set run environment + +SAMTOOLSDIR=/usr/share/samtools # SAMTools directory + +DDRADSEQTOOLSDIR=$TRABAJO/ddRADseqTools # ddRADseqTools programs directory +GENOMESDIR=$TRABAJO/ddRADseqTools/genomes # genomes file directory +FRAGSDIR=$TRABAJO/ddRADseqTools/fragments # fragments directory +READSDIR=$TRABAJO/ddRADseqTools/reads # reads directory +STATSDIR=$TRABAJO/ddRADseqTools/statistics # statistics directory +ALIGNDIR=$TRABAJO/ddRADseqTools/alignments # alignments directory + +if [ ! -d ""$FRAGSDIR"" ]; then mkdir $FRAGSDIR; fi +if [ ! -d ""$READSDIR"" ]; then mkdir $READSDIR; else rm -f $READSDIR/*; fi +if [ ! -d ""$STATSDIR"" ]; then mkdir $STATSDIR; else rm -f $STATSDIR/*; fi +if [ ! -d ""$ALIGNDIR"" ]; then mkdir $ALIGNDIR; else rm -f $ALIGNDIR/*; fi + +GENOME=GCF_000956235.1_wasmannia.A_1.0_genomic.fna.gz # Wasmannia auropunctata genome + +ENZYME1=EcoRI +ENZYME2=MseI +TECHNIQUE=IND1_IND2_DBR +FORMAT=FASTQ +READTYPE=PE +INDEX1LEN=7 +INDEX2LEN=7 +DBRLEN=4 +WEND=end93 +CEND=end94 +INDIVIDUALSFILE=individuals-1index1-5index2.txt + +if [ `ulimit -n` -lt 1024 ]; then ulimit -n 1024; fi + +#------------------------------------------------------------------------------- + +# Generate genome fragments and get statistics + +echo '**************************************************' +echo 'GENOME FRAGMENTS ARE BEING GENERATED FROM GENOME ...' + +$DDRADSEQTOOLSDIR/rsitesearch.py \ + --genfile=$GENOMESDIR/$GENOME \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --minfragsize=187 \ + --maxfragsize=287 \ + --fragstfile=$STATSDIR/fragments-genome-stats.txt \ + --fragstinterval=25 \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Generate ddRADseq simulated reads + +echo '**************************************************' +echo 'DDRADSEQ SIMULATED READS ARE BEING GENERATED ...' + +$DDRADSEQTOOLSDIR/simddradseq.py \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readsfile=$READSDIR/reads \ + --readtype=$READTYPE \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --locinum=18150 \ + --readsnum=7000000 \ + --minreadvar=0.8 \ + --maxreadvar=1.2 \ + --insertlen=25 \ + --mutprob=0.2 \ + --locusmaxmut=1 \ + --indelprob=0.1 \ + --maxindelsize=10 \ + --dropout=0.05 \ + --pcrdupprob=0.5 \ + --pcrdistribution=MULTINOMIAL \ + --multiparam=0.167,0.152,0.136,0.121,0.106,0.091,0.076,0.061,0.045,0.030,0.015 \ + --poissonparam=1.0 \ + --gcfactor=0.2 \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Remove the PCR duplicates + +echo '**************************************************' +echo 'THE PRC DUPLICATES ARE BEING REMOVED ...' + +$DDRADSEQTOOLSDIR/pcrdupremoval.py \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --readsfile1=$READSDIR/reads-1.fastq \ + --readsfile2=$READSDIR/reads-2.fastq \ + --clearfile=$READSDIR/reads-cleared \ + --dupstfile=$STATSDIR/pcrduplicates-stats.txt \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Demultiplex the individual files + +echo '**************************************************' +echo 'INDIVIDUAL FILES ARE BEING DEMULTIPLEXED ...' + +$DDRADSEQTOOLSDIR/indsdemultiplexing.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --readsfile1=$READSDIR/reads-cleared-1.fastq \ + --readsfile2=$READSDIR/reads-cleared-2.fastq \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Trim adapters and other Illumina-specific sequences from reads + +echo '**************************************************' +echo 'ADAPTERS AND OTHER ILLUMINA SPECIFIC SEQUENCES ARE BEING TRIMMED IN INDIVIDUAL FILES ...' + +ls $READSDIR/demultiplexed-*-1.fastq > $READSDIR/reads-files.txt + +while read FILE_1; do + + if [[ $FILE_1 =~ .*errors.* ]]; then continue; fi + + FILE_2=`echo $FILE_1 | sed 's/-1.fastq/-2.fastq/g'` + FILE_TRIMMED=`echo $FILE_1 | sed 's/-1.fastq/-trimmed/g'` + + $DDRADSEQTOOLSDIR/readstrim.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --readsfile1=$FILE_1 \ + --readsfile2=$FILE_2 \ + --trimfile=$FILE_TRIMMED \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $READSDIR/reads-files.txt + +#------------------------------------------------------------------------------- + +# Index the genome + +echo '**************************************************' +echo 'GENOME IS BEING INDEXED ...' + + +bwa index -a bwtsw $GENOMESDIR/$GENOME +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + +#------------------------------------------------------------------------------- + +# Align sequences of individual files in SAM format + +echo '**************************************************' +echo 'SEQUENCES OF INDIVIDUAL FILES ARE BEING ALIGNED IN SAM FORMAT ...' + +ls $READSDIR/demultiplexed-*-trimmed-1.fastq > $READSDIR/reads-trimmed-files.txt + +while read FILE1_TRIM; do + + FILE2_TRIM=`echo $FILE1_TRIM | sed 's/-trimmed-1.fastq/-trimmed-2.fastq/g'` + FILE_SAM=`echo $FILE1_TRIM | sed 's/-1.fastq/.sam/g' | sed ""s|$READSDIR|$ALIGNDIR|g""` + bwa mem $GENOMESDIR/$GENOME $FILE1_TRIM $FILE2_TRIM > $FILE_SAM + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $READSDIR/reads-trimmed-files.txt + +#------------------------------------------------------------------------------- + +# Convert SAM files to BED, BAM and VCF format + +echo '**************************************************' +echo 'SAM FILES ARE BEING CONVERTED IN BAM, BED AND VCF FORMAT ...' + +ls $ALIGNDIR/*.sam > $ALIGNDIR/sam-files.txt + +while read FILE_SAM; do + + FILE_BAM=`echo $FILE_SAM | sed 's/.sam/.bam/g'` + FILE_BAM_STATS=`echo $FILE_SAM | sed 's/.sam/-stats-bam.txt/g'` + FILE_BED=`echo $FILE_SAM | sed 's/.sam/.bed/g'` + FILE_SORTED=`echo $FILE_SAM | sed 's/.sam/.sorted/g'` + FILE_SORTED_BAM=`echo $FILE_SAM | sed 's/.sam/.sorted.bam/g'` + FILE_VCF=`echo $FILE_SAM | sed 's/.sam/.vcf/g'` + FILE_VCF_STATS1=`echo $FILE_SAM | sed 's/.sam/-stats-vcf-1.txt/g'` + FILE_VCF_STATS2=`echo $FILE_SAM | sed 's/.sam/-stats-vcf-2.txt/g'` + + # convert SAM file to BAM format + samtools view -bS $FILE_SAM >$FILE_BAM + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # get aligment statistic in a file + samtools flagstat $FILE_BAM >$FILE_BAM_STATS + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # convert BAM file to BED format + bedtools bamtobed -i $FILE_BAM > $FILE_BED + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # sort the BAM file + samtools sort $FILE_BAM $FILE_SORTED + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # index the BAM file + samtools index $FILE_SORTED_BAM + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # convert BAM file to VCF format + samtools mpileup -uf $GENOMESDIR/$GENOME $FILE_SORTED_BAM | bcftools view -vcg - > $FILE_VCF + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # get variant statistic in a file with SAMtools + $SAMTOOLSDIR/vcfutils.pl qstats $FILE_VCF > $FILE_VCF_STATS1 + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # get variant statistic in a file with VCFtools + vcftools --vcf $FILE_VCF > $FILE_VCF_STATS2 + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $ALIGNDIR/sam-files.txt + +#------------------------------------------------------------------------------- + +# Get the distinct loci list with mutations + +echo '**************************************************' +echo 'THE DISTINCT LOCI LIST WITH MUTATIONS ARE BEING GOT ...' + +LOCI_FILE=$ALIGNDIR/loci.txt +cat >$LOCI_FILE < $ALIGNDIR/vcf-files.txt + +while read FILE_VCF; do + + while read -r LINE; do + + if [[ $LINE =~ ^#.*$ ]]; then continue; fi + + echo ""$LINE"" | cut -f 1,2 >> $LOCI_FILE + + done < $FILE_VCF + +done < $ALIGNDIR/vcf-files.txt + +sort -u $LOCI_FILE > $DISTINCT_LOCI_FILE + +DISTINCT_LOCI_TOTAL=`wc -l $DISTINCT_LOCI_FILE | cut -f1 -d' '` +echo ""The dictinct loci list contains $DISTINCT_LOCI_TOTAL loci."" +echo ""$DISTINCT_LOCI_TOTAL"" > $DISTINCT_LOCI_TOTAL_FILE + +#------------------------------------------------------------------------------- + +# End +echo '**************************************************' +exit 0 + +#------------------------------------------------------------------------------- +","Shell" +"In Silico","GGFHF/ddRADseqTools","Package/simulation-scripts/simulation-pipeline-Scerevisiae-se.sh",".sh","10931","327","#!/bin/bash + +#------------------------------------------------------------------------------- + +# This script generates fragments from the Saccharomyces cerevisiae genome; it +# simulates a double digest and generates their SE reads; it quantifies and +# removes PCR duplicates and calculates the loci number without data; it +# demultiplexes the individuals; it trims the adapters and other Illumina specific +# sequences; it aligns the reads and gets SAM, BAM, BED and VCF format files to +# study and visualize alignments; and it gets the distinct loci list with mutations. + +#------------------------------------------------------------------------------- + +# WARNING + +# This script uses the following bioinformatics tools: +# - BWA v0.7.13 (http://bio-bwa.sourceforge.net/) +# - SAMtools & BCFtools v0.1.19 (http://www.htslib.org/) +# - BEDtools v2.25.0 (http://bedtools.readthedocs.io/) +# - VCFtools v0.1.14-14 (https://vcftools.github.io/) + +#------------------------------------------------------------------------------- + +# Control parameters + +if [ -n ""$*"" ]; then echo 'This script has not parameters.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Set run environment + +SAMTOOLSDIR=/usr/share/samtools # SAMTools directory + +DDRADSEQTOOLSDIR=$TRABAJO/ddRADseqTools # ddRADseqTools programs directory +GENOMESDIR=$TRABAJO/ddRADseqTools/genomes # genomes file directory +FRAGSDIR=$TRABAJO/ddRADseqTools/fragments # fragments directory +READSDIR=$TRABAJO/ddRADseqTools/reads # reads directory +STATSDIR=$TRABAJO/ddRADseqTools/statistics # statistics directory +ALIGNDIR=$TRABAJO/ddRADseqTools/alignments # alignments directory + +if [ ! -d ""$FRAGSDIR"" ]; then mkdir $FRAGSDIR; fi +if [ ! -d ""$READSDIR"" ]; then mkdir $READSDIR; else rm -f $READSDIR/*; fi +if [ ! -d ""$STATSDIR"" ]; then mkdir $STATSDIR; else rm -f $STATSDIR/*; fi +if [ ! -d ""$ALIGNDIR"" ]; then mkdir $ALIGNDIR; else rm -f $ALIGNDIR/*; fi + +GENOME=GCF_000146045.2_R64_genomic.fna.gz # Saccharomyces cerevisiae genome + +ENZYME1=EcoRI +ENZYME2=MseI +TECHNIQUE=IND1_DBR +FORMAT=FASTQ +READTYPE=SE +INDEX1LEN=7 +INDEX2LEN=0 +DBRLEN=4 +WEND=end63 +CEND=end64 +INDIVIDUALSFILE=individuals-5index1.txt + +if [ `ulimit -n` -lt 1024 ]; then ulimit -n 1024; fi + +#------------------------------------------------------------------------------- + +# Generate genome fragments and get statistics + +echo '**************************************************' +echo 'GENOME FRAGMENTS ARE BEING GENERATED FROM GENOME ...' + +$DDRADSEQTOOLSDIR/rsitesearch.py \ + --genfile=$GENOMESDIR/$GENOME \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --minfragsize=230 \ + --maxfragsize=630 \ + --fragstfile=$STATSDIR/fragments-genome-stats.txt \ + --fragstinterval=25 \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Generate ddRADseq simulated reads + +echo '**************************************************' +echo 'DDRADSEQ SIMULATED READS ARE BEING GENERATED ...' + +$DDRADSEQTOOLSDIR/simddradseq.py \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readsfile=$READSDIR/reads \ + --readtype=$READTYPE \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --locinum=1720 \ + --readsnum=5500000 \ + --minreadvar=0.8 \ + --maxreadvar=1.2 \ + --insertlen=50 \ + --mutprob=0.4 \ + --locusmaxmut=1 \ + --indelprob=0.1 \ + --maxindelsize=10 \ + --dropout=0.05 \ + --pcrdupprob=0.5 \ + --pcrdistribution=MULTINOMIAL \ + --multiparam=0.167,0.152,0.136,0.121,0.106,0.091,0.076,0.061,0.045,0.030,0.015 \ + --poissonparam=1.0 \ + --gcfactor=0.2 \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Remove the PCR duplicates + +echo '**************************************************' +echo 'THE PRC DUPLICATES ARE BEING REMOVED ...' + +$DDRADSEQTOOLSDIR/pcrdupremoval.py \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --readsfile1=$READSDIR/reads.fastq \ + --readsfile2=NONE \ + --clearfile=$READSDIR/reads-cleared \ + --dupstfile=$STATSDIR/pcrduplicates-stats.txt \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Demultiplex the individual files + +echo '**************************************************' +echo 'INDIVIDUAL FILES ARE BEING DEMULTIPLEXED ...' + +$DDRADSEQTOOLSDIR/indsdemultiplexing.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --readsfile1=$READSDIR/reads-cleared.fastq \ + --readsfile2=NONE \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Trim adapters and other Illumina-specific sequences from reads + +echo '**************************************************' +echo 'ADAPTERS AND OTHER ILLUMINA SPECIFIC SEQUENCES ARE BEING TRIMMED IN INDIVIDUAL FILES ...' + +ls $READSDIR/demultiplexed-*.fastq > $READSDIR/reads-files.txt + +while read FILE_1; do + + if [[ $FILE_1 =~ .*errors.* ]]; then continue; fi + + FILE_2=NONE + FILE_TRIMMED=`echo $FILE_1 | sed 's/.fastq/-trimmed/g'` + + $DDRADSEQTOOLSDIR/readstrim.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --readsfile1=$FILE_1 \ + --readsfile2=$FILE_2 \ + --trimfile=$FILE_TRIMMED \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $READSDIR/reads-files.txt + +#------------------------------------------------------------------------------- + +# Index the genome + +echo '**************************************************' +echo 'GENOME IS BEING INDEXED ...' + + +bwa index -a bwtsw $GENOMESDIR/$GENOME +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + +#------------------------------------------------------------------------------- + +# Align sequences of individual files in SAM format + +echo '**************************************************' +echo 'SEQUENCES OF INDIVIDUAL FILES ARE BEING ALIGNED IN SAM FORMAT ...' + +ls $READSDIR/demultiplexed-*-trimmed.fastq > $READSDIR/reads-trimmed-files.txt + +while read FILE_TRIM; do + + FILE_SAM=`echo $FILE_TRIM | sed 's/.fastq/.sam/g' | sed ""s|$READSDIR|$ALIGNDIR|g""` + bwa mem $GENOMESDIR/$GENOME $FILE_TRIM > $FILE_SAM + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $READSDIR/reads-trimmed-files.txt + +#------------------------------------------------------------------------------- + +# Convert SAM files to BED, BAM and VCF format + +echo '**************************************************' +echo 'SAM FILES ARE BEING CONVERTED IN BAM, BED AND VCF FORMAT ...' + +ls $ALIGNDIR/*.sam > $ALIGNDIR/sam-files.txt + +while read FILE_SAM; do + + FILE_BAM=`echo $FILE_SAM | sed 's/.sam/.bam/g'` + FILE_BAM_STATS=`echo $FILE_SAM | sed 's/.sam/-stats-bam.txt/g'` + FILE_BED=`echo $FILE_SAM | sed 's/.sam/.bed/g'` + FILE_SORTED=`echo $FILE_SAM | sed 's/.sam/.sorted/g'` + FILE_SORTED_BAM=`echo $FILE_SAM | sed 's/.sam/.sorted.bam/g'` + FILE_VCF=`echo $FILE_SAM | sed 's/.sam/.vcf/g'` + FILE_VCF_STATS1=`echo $FILE_SAM | sed 's/.sam/-stats-vcf-1.txt/g'` + FILE_VCF_STATS2=`echo $FILE_SAM | sed 's/.sam/-stats-vcf-2.txt/g'` + + # convert SAM file to BAM format + samtools view -bS $FILE_SAM >$FILE_BAM + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # get aligment statistic in a file + samtools flagstat $FILE_BAM >$FILE_BAM_STATS + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # convert BAM file to BED format + bedtools bamtobed -i $FILE_BAM > $FILE_BED + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # sort the BAM file + samtools sort $FILE_BAM $FILE_SORTED + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # index the BAM file + samtools index $FILE_SORTED_BAM + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # convert BAM file to VCF format + samtools mpileup -uf $GENOMESDIR/$GENOME $FILE_SORTED_BAM | bcftools view -vcg - > $FILE_VCF + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # get variant statistic in a file with SAMtools + $SAMTOOLSDIR/vcfutils.pl qstats $FILE_VCF > $FILE_VCF_STATS1 + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # get variant statistic in a file with VCFtools + vcftools --vcf $FILE_VCF > $FILE_VCF_STATS2 + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $ALIGNDIR/sam-files.txt + +#------------------------------------------------------------------------------- + +# Get the distinct loci list with mutations + +echo '**************************************************' +echo 'THE DISTINCT LOCI LIST WITH MUTATIONS ARE BEING GOT ...' + +LOCI_FILE=$ALIGNDIR/loci.txt +cat >$LOCI_FILE < $ALIGNDIR/vcf-files.txt + +while read FILE_VCF; do + + while read -r LINE; do + + if [[ $LINE =~ ^#.*$ ]]; then continue; fi + + echo ""$LINE"" | cut -f 1,2 >> $LOCI_FILE + + done < $FILE_VCF + +done < $ALIGNDIR/vcf-files.txt + +sort -u $LOCI_FILE > $DISTINCT_LOCI_FILE + +DISTINCT_LOCI_TOTAL=`wc -l $DISTINCT_LOCI_FILE | cut -f1 -d' '` +echo ""The dictinct loci list contains $DISTINCT_LOCI_TOTAL loci."" +echo ""$DISTINCT_LOCI_TOTAL"" > $DISTINCT_LOCI_TOTAL_FILE + +#------------------------------------------------------------------------------- + +# End +echo '**************************************************' +exit 0 + +#------------------------------------------------------------------------------- +","Shell" +"In Silico","GGFHF/ddRADseqTools","Package/simulation-scripts/simulation-test-se-fastq.sh",".sh","9592","269","#!/bin/bash + +#------------------------------------------------------------------------------- + +# This software has been developed by Forest Genetics and Physiology Research Group, +# Technical University of Madrid (UPM) + +# Licence: GNU General Public Licence Version 3 + +#------------------------------------------------------------------------------- + +# This script executes a test of each program of the software package ddRADseqTools + +#------------------------------------------------------------------------------- + +# Control parameters + +if [ -n ""$*"" ]; then echo 'This script has not parameters.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Set run environment + +DDRADSEQTOOLSDIR=$TRABAJO/ddRADseqTools # ddRADseqTools programs directory +GENOMESDIR=$TRABAJO/ddRADseqTools/genomes # genomes file directory +FRAGSDIR=$TRABAJO/ddRADseqTools/fragments # fragments directory +READSDIR=$TRABAJO/ddRADseqTools/reads # reads directory +STATSDIR=$TRABAJO/ddRADseqTools/statistics # statistics directory + +if [ ! -d ""$FRAGSDIR"" ]; then mkdir $FRAGSDIR; fi +if [ ! -d ""$READSDIR"" ]; then mkdir $READSDIR; else rm -f $READSDIR/*; fi +if [ ! -d ""$STATSDIR"" ]; then mkdir $STATSDIR; else rm -f $STATSDIR/*; fi + +GENOME_SCEREVISIAE=GCF_000146045.2_R64_genomic.fna.gz # Saccharomyces cerevisiae genome +GENOME_CELEGANS=GCF_000002985.6_WBcel235_genomic.fna.gz # Caenorhabditis elegans genome +GENOME_DMELANOGASTERe=GCF_000001215.4_Release_6_plus_ISO1_MT_genomic.fna.gz # Drosophila melanogaster genome +GENOME_HSAPIENS=GCF_000001405.29_GRCh38.p3_genomic.fna.gz # Homo sapiens genome +GENOME_QROBUR=ena.fasta # Quercus robur genome +GENOME_PTAEDA=ptaeda.v1.01.scaffolds.fasta.gz # Pinus taeda genome +GENOME=$GENOME_SCEREVISIAE # genome used in this run + +ENZYME1=EcoRI +ENZYME2=MseI +TECHNIQUE=IND1_DBR +FORMAT=FASTQ +READTYPE=SE +INDEX1LEN=6 +INDEX2LEN=0 +DBRLEN=4 +WEND=end61 +CEND=end62 +INDIVIDUALSFILE=individuals-24index1.txt + +if [ `ulimit -n` -lt 1024 ]; then ulimit -n 1024; fi + +#------------------------------------------------------------------------------- + +# Generate genome fragments and get statistics + +echo '**************************************************' +echo 'GENOME FRAGMENTS ARE BEING GENERATED FROM GENOME ...' + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/rsitesearch.py \ + --genfile=$GENOMESDIR/$GENOME \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --minfragsize=101 \ + --maxfragsize=300 \ + --fragstfile=$STATSDIR/fragments-genome-stats.txt \ + --fragstinterval=25 \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Generate random fragments and get statistics + +echo '**************************************************' +echo 'GENOME FRAGMENTS ARE BEING GENERATED RANDOMLY ...' + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/fragsgeneration.py \ + --fragsfile=$FRAGSDIR/fragments-random.fasta \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --fragsnum=3103 \ + --minfragsize=101 \ + --maxfragsize=300 \ + --fragstfile=$STATSDIR/fragments-random-stats.txt \ + --fragstinterval=25 \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Locate several sequences into the genome + +echo '**************************************************' +echo 'SEVERAL SEQUENCES ARE BEING LOCATED ...' + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/seqlocation.py \ + --genfile=$GENOMESDIR/$GENOME \ + --seq=aattcTGGGTGGAACTAGTAGCTGGAGATGCGTTCTAAAGGATCTAAAATCAGACTCACCCCAAAAACCAAAATTTTGATATTCAACTTTAGTATTAGCCAGTCt + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/seqlocation.py \ + --genfile=$GENOMESDIR/$GENOME \ + --seq=aattcAAGAACATCTCGAAGCCAGAATTGAGCATCATATATTCGAGCTGTACAAACATCATGGCCTACAACTATCGTATTTGTAAGTTTTTTTAGAGGTTTTCATATTTGTt + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/seqlocation.py \ + --genfile=$GENOMESDIR/$GENOME \ + --seq=aattcGAAGTAGTGTACCACATTTGTAAGTTTAGATGCCTATTGGAAATGAGCGGGTACAAAAATGACGGGCTTTATTATGCTGTTTGACATAGTATACACAGCAGTTGTGGTGt + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/seqlocation.py \ + --genfile=$GENOMESDIR/$GENOME \ + --seq=aattcTTTATAATCCAGACCTCCCAAAAGAGGCAATCGTCAACTTCTGTCAATCTATTCTAGATGCTACTATCTCTGATTCAGCAAAATACCAAATTGGTAATACCAAAATTTTCTt + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Generate ddRADseq simulated reads + +echo '**************************************************' +echo 'DDRADSEQ SIMULATED READS ARE BEING GENERATED ...' + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/simddradseq.py \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readsfile=$READSDIR/reads \ + --readtype=$READTYPE \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --locinum=3000 \ + --readsnum=300000 \ + --minreadvar=0.8 \ + --maxreadvar=1.2 \ + --insertlen=100 \ + --mutprob=0.2 \ + --locusmaxmut=1 \ + --indelprob=0.1 \ + --maxindelsize=10 \ + --dropout=0.0 \ + --pcrdupprob=0.2 \ + --pcrdistribution=MULTINOMIAL \ + --multiparam=0.167,0.152,0.136,0.121,0.106,0.091,0.076,0.061,0.045,0.030,0.015 \ + --poissonparam=1.0 \ + --gcfactor=0.2 \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Remove the PCR duplicates + +echo '**************************************************' +echo 'THE PRC DUPLICATES ARE BEING REMOVED ...' + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/pcrdupremoval.py \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --readsfile1=$READSDIR/reads.fastq \ + --readsfile2=NONE \ + --clearfile=$READSDIR/reads-cleared \ + --dupstfile=$STATSDIR/pcrduplicates-stats.txt \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Demultiplex the individual files + +echo '**************************************************' +echo 'INDIVIDUAL FILES ARE BEING DEMULTIPLEXED ...' + +/usr/bin/time \ + $DDRADSEQTOOLSDIR/indsdemultiplexing.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --readsfile1=$READSDIR/reads-cleared.fastq \ + --readsfile2=NONE \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Trim adapters and other Illumina-specific sequences from reads + +echo '**************************************************' +echo 'ADAPTERS AND OTHER ILLUMINA SPECIFIC SEQUENCES ARE BEING TRIMMED IN INDIVIDUAL FILES ...' + +ls $READSDIR/demultiplexed-ind*-1.fastq > $READSDIR/reads-files.txt + +while read FILE_1; do + + FILE_TRIMMED=`echo $FILE_1 | sed 's/-1.fastq/-trimmed/g'` + + /usr/bin/time \ + $DDRADSEQTOOLSDIR/readstrim.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --readsfile1=$FILE_1 \ + --readsfile2=NONE \ + --trimfile=$FILE_TRIMMED \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $READSDIR/reads-files.txt + +#------------------------------------------------------------------------------- + +# End +echo '**************************************************' +exit 0 + +#------------------------------------------------------------------------------- +","Shell" +"In Silico","GGFHF/ddRADseqTools","Package/simulation-scripts/simulation-pipeline-Vberus-se.sh",".sh","10935","327","#!/bin/bash + +#------------------------------------------------------------------------------- + +# This script generates fragments from the Vipera berus genome; it simulates a +# double digest and generates their SE reads; it calculates the loci number +# without data; it demultiplexes the individuals; it trims the adapters and +# other Illumina specific sequences; it aligns the reads and gets SAM, BAM, BED +# and VCF format files to study and visualize alignments; and it gets the +# distinct loci list with mutations. + +#------------------------------------------------------------------------------- + +# WARNING + +# This script uses the following bioinformatics tools: +# - BWA v0.7.13 (http://bio-bwa.sourceforge.net/) +# - SAMtools & BCFtools v0.1.19 (http://www.htslib.org/) +# - BEDtools v2.25.0 (http://bedtools.readthedocs.io/) +# - VCFtools v0.1.14-14 (https://vcftools.github.io/) + +#------------------------------------------------------------------------------- + +# Control parameters + +if [ -n ""$*"" ]; then echo 'This script has not parameters.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Set run environment + +SAMTOOLSDIR=/usr/share/samtools # SAMTools directory + +DDRADSEQTOOLSDIR=$TRABAJO/ddRADseqTools # ddRADseqTools programs directory +GENOMESDIR=$TRABAJO/ddRADseqTools/genomes # genomes file directory +FRAGSDIR=$TRABAJO/ddRADseqTools/fragments # fragments directory +READSDIR=$TRABAJO/ddRADseqTools/reads # reads directory +STATSDIR=$TRABAJO/ddRADseqTools/statistics # statistics directory +ALIGNDIR=$TRABAJO/ddRADseqTools/alignments # alignments directory + +if [ ! -d ""$FRAGSDIR"" ]; then mkdir $FRAGSDIR; fi +if [ ! -d ""$READSDIR"" ]; then mkdir $READSDIR; else rm -f $READSDIR/*; fi +if [ ! -d ""$STATSDIR"" ]; then mkdir $STATSDIR; else rm -f $STATSDIR/*; fi +if [ ! -d ""$ALIGNDIR"" ]; then mkdir $ALIGNDIR; else rm -f $ALIGNDIR/*; fi + +GENOME=GCA_000800605.1_Vber.be_1.0_genomic.fna.gz # Vipera berus genome + +ENZYME1=EcoRI +ENZYME2=SbfI +TECHNIQUE=IND1 +FORMAT=FASTQ +READTYPE=SE +INDEX1LEN=6 +INDEX2LEN=0 +DBRLEN=0 +WEND=end51 +CEND=end52 +INDIVIDUALSFILE=individuals-40index1.txt + +if [ `ulimit -n` -lt 1024 ]; then ulimit -n 1024; fi + +#------------------------------------------------------------------------------- + +# Generate genome fragments and get statistics + +echo '**************************************************' +echo 'GENOME FRAGMENTS ARE BEING GENERATED FROM GENOME ...' + +$DDRADSEQTOOLSDIR/rsitesearch.py \ + --genfile=$GENOMESDIR/$GENOME \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --minfragsize=230 \ + --maxfragsize=380 \ + --fragstfile=$STATSDIR/fragments-genome-stats.txt \ + --fragstinterval=25 \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Generate ddRADseq simulated reads + +echo '**************************************************' +echo 'DDRADSEQ SIMULATED READS ARE BEING GENERATED ...' + +$DDRADSEQTOOLSDIR/simddradseq.py \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readsfile=$READSDIR/reads \ + --readtype=$READTYPE \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --locinum=2340 \ + --readsnum=3300000 \ + --minreadvar=0.8 \ + --maxreadvar=1.2 \ + --insertlen=50 \ + --mutprob=0.8 \ + --locusmaxmut=1 \ + --indelprob=0.1 \ + --maxindelsize=10 \ + --dropout=0.05 \ + --pcrdupprob=0.0 \ + --pcrdistribution=MULTINOMIAL \ + --multiparam=0.167,0.152,0.136,0.121,0.106,0.091,0.076,0.061,0.045,0.030,0.015 \ + --poissonparam=1.0 \ + --gcfactor=0.2 \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Remove the PCR duplicates (this step is only used for statistics) + +echo '**************************************************' +echo 'THE PRC DUPLICATES ARE BEING REMOVED ...' + +$DDRADSEQTOOLSDIR/pcrdupremoval.py \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --readsfile1=$READSDIR/reads.fastq \ + --readsfile2=NONE \ + --clearfile=$READSDIR/reads-cleared \ + --dupstfile=$STATSDIR/pcrduplicates-stats.txt \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Demultiplex the individual files (all reads including duplicates) + +echo '**************************************************' +echo 'INDIVIDUAL FILES ARE BEING DEMULTIPLEXED ...' + +$DDRADSEQTOOLSDIR/indsdemultiplexing.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --readsfile1=$READSDIR/reads.fastq \ + --readsfile2=NONE \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Trim adapters and other Illumina-specific sequences from reads + +echo '**************************************************' +echo 'ADAPTERS AND OTHER ILLUMINA SPECIFIC SEQUENCES ARE BEING TRIMMED IN INDIVIDUAL FILES ...' + +ls $READSDIR/demultiplexed-*.fastq > $READSDIR/reads-files.txt + +while read FILE_1; do + + if [[ $FILE_1 =~ .*errors.* ]]; then continue; fi + + FILE_2=NONE + FILE_TRIMMED=`echo $FILE_1 | sed 's/.fastq/-trimmed/g'` + + $DDRADSEQTOOLSDIR/readstrim.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --readsfile1=$FILE_1 \ + --readsfile2=$FILE_2 \ + --trimfile=$FILE_TRIMMED \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $READSDIR/reads-files.txt + +#------------------------------------------------------------------------------- + +# Index the genome + +echo '**************************************************' +echo 'GENOME IS BEING INDEXED ...' + + +bwa index -a bwtsw $GENOMESDIR/$GENOME +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + +#------------------------------------------------------------------------------- + +# Align sequences of individual files in SAM format + +echo '**************************************************' +echo 'SEQUENCES OF INDIVIDUAL FILES ARE BEING ALIGNED IN SAM FORMAT ...' + +ls $READSDIR/demultiplexed-*-trimmed.fastq > $READSDIR/reads-trimmed-files.txt + +while read FILE_TRIM; do + + FILE_SAM=`echo $FILE_TRIM | sed 's/.fastq/.sam/g' | sed ""s|$READSDIR|$ALIGNDIR|g""` + bwa mem $GENOMESDIR/$GENOME $FILE_TRIM > $FILE_SAM + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $READSDIR/reads-trimmed-files.txt + +#------------------------------------------------------------------------------- + +# Convert SAM files to BED, BAM and VCF format + +echo '**************************************************' +echo 'SAM FILES ARE BEING CONVERTED IN BAM, BED AND VCF FORMAT ...' + +ls $ALIGNDIR/*.sam > $ALIGNDIR/sam-files.txt + +while read FILE_SAM; do + + FILE_BAM=`echo $FILE_SAM | sed 's/.sam/.bam/g'` + FILE_BAM_STATS=`echo $FILE_SAM | sed 's/.sam/-stats-bam.txt/g'` + FILE_BED=`echo $FILE_SAM | sed 's/.sam/.bed/g'` + FILE_SORTED=`echo $FILE_SAM | sed 's/.sam/.sorted/g'` + FILE_SORTED_BAM=`echo $FILE_SAM | sed 's/.sam/.sorted.bam/g'` + FILE_VCF=`echo $FILE_SAM | sed 's/.sam/.vcf/g'` + FILE_VCF_STATS1=`echo $FILE_SAM | sed 's/.sam/-stats-vcf-1.txt/g'` + FILE_VCF_STATS2=`echo $FILE_SAM | sed 's/.sam/-stats-vcf-2.txt/g'` + + # convert SAM file to BAM format + samtools view -bS $FILE_SAM >$FILE_BAM + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # get aligment statistic in a file + samtools flagstat $FILE_BAM >$FILE_BAM_STATS + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # convert BAM file to BED format + bedtools bamtobed -i $FILE_BAM > $FILE_BED + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # sort the BAM file + samtools sort $FILE_BAM $FILE_SORTED + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # index the BAM file + samtools index $FILE_SORTED_BAM + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # convert BAM file to VCF format + samtools mpileup -uf $GENOMESDIR/$GENOME $FILE_SORTED_BAM | bcftools view -vcg - > $FILE_VCF + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # get variant statistic in a file with SAMtools + $SAMTOOLSDIR/vcfutils.pl qstats $FILE_VCF > $FILE_VCF_STATS1 + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # get variant statistic in a file with VCFtools + vcftools --vcf $FILE_VCF > $FILE_VCF_STATS2 + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $ALIGNDIR/sam-files.txt + +#------------------------------------------------------------------------------- + +# Get the distinct loci list with mutations + +echo '**************************************************' +echo 'THE DISTINCT LOCI LIST WITH MUTATIONS ARE BEING GOT ...' + +LOCI_FILE=$ALIGNDIR/loci.txt +cat >$LOCI_FILE < $ALIGNDIR/vcf-files.txt + +while read FILE_VCF; do + + while read -r LINE; do + + if [[ $LINE =~ ^#.*$ ]]; then continue; fi + + echo ""$LINE"" | cut -f 1,2 >> $LOCI_FILE + + done < $FILE_VCF + +done < $ALIGNDIR/vcf-files.txt + +sort -u $LOCI_FILE > $DISTINCT_LOCI_FILE + +DISTINCT_LOCI_TOTAL=`wc -l $DISTINCT_LOCI_FILE | cut -f1 -d' '` +echo ""The dictinct loci list contains $DISTINCT_LOCI_TOTAL loci."" +echo ""$DISTINCT_LOCI_TOTAL"" > $DISTINCT_LOCI_TOTAL_FILE + +#------------------------------------------------------------------------------- + +# End +echo '**************************************************' +exit 0 + +#------------------------------------------------------------------------------- +","Shell" +"In Silico","GGFHF/ddRADseqTools","Package/simulation-scripts/simulation-dropout.sh",".sh","5149","132","#!/bin/bash + +#------------------------------------------------------------------------------- + +# This software has been developed by Forest Genetics and Physiology Research Group, +# Technical University of Madrid (UPM) + +# Licence: GNU General Public Licence Version 3 + +#------------------------------------------------------------------------------- + +# This script analyses the effect of dropout on the number of reads to be +# generate and the probability of loci bearing PCR duplicates + +#------------------------------------------------------------------------------- + +# Control parameters + +if [ -n ""$*"" ]; then echo 'This script has not parameters'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Set run environment + +DDRADSEQTOOLSDIR=$TRABAJO/ddRADseqTools # ddRADseqTools programs directory +FRAGSDIR=$TRABAJO/ddRADseqTools/fragments # fragments directory +READSDIR=$TRABAJO/ddRADseqTools/reads # reads directory +STATSDIR=$TRABAJO/ddRADseqTools/statistics # statistics directory + +if [ ! -d ""$READSDIR"" ]; then mkdir $READSDIR; else rm -f $READSDIR/*; fi +if [ ! -d ""$STATSDIR"" ]; then mkdir $STATSDIR; else rm -f $STATSDIR/*; fi + +SCEREVISIAE='Scerevisiae' # Saccharomyces cerevisiae +SCEREVISIAE_FRAGS_FILE=$SCEREVISIAE'-fragments-EcoRI-MseI.fasta' # Saccharomyces cerevisiae framents gotten by EcoI and MseI digest +SCEREVISIAE_READSNUM=(600000 1200000) # Saccharomyces cerevisiae readsnum values +#--SCEREVISIAE_PCRDUPPROB=(0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9) # Saccharomyces cerevisiae pcrdupprob values +SCEREVISIAE_PCRDUPPROB=(0.0) # Saccharomyces cerevisiae pcrdupprob values +SCEREVISIAE_DROPOUT=(0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8) # Saccharomyces cerevisiae dropout values + +TECHNIQUE=IND1_IND2_DBR +FORMAT=FASTQ +READTYPE=PE +INDEX1LEN=6 +INDEX2LEN=6 +DBRLEN=4 +WEND=end31 +CEND=end32 +INDIVIDUALSFILE=individuals-8index1-6index2.txt + +#------------------------------------------------------------------------------- + +# Generate ddRADseq simulated reads of Saccharomyces cerevisiae + +echo '**************************************************' +echo 'SACCHAROMYCES CEREVISIAE' + +for I in ""${SCEREVISIAE_READSNUM[@]}"" +do + for J in ""${SCEREVISIAE_PCRDUPPROB[@]}"" + do + for K in ""${SCEREVISIAE_DROPOUT[@]}"" + do + + # Generate ddRADseq simulated reads + + echo '--------------------------------------------------' + echo ""SIMULATION WITH READSNUM=$I AND PCRDUPPROB=$J AND DROPOUT=$K ..."" + + $DDRADSEQTOOLSDIR/simddradseq.py \ + --fragsfile=$FRAGSDIR/$SCEREVISIAE_FRAGS_FILE \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readsfile=$READSDIR/$SCEREVISIAE'-reads-'$I'-'$J'-'$K \ + --readtype=$READTYPE \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=EcoRI \ + --enzyme2=MseI \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --locinum=3000 \ + --readsnum=$I \ + --minreadvar=0.8 \ + --maxreadvar=1.2 \ + --insertlen=100 \ + --mutprob=0.2 \ + --locusmaxmut=1 \ + --indelprob=0.1 \ + --maxindelsize=10 \ + --dropout=$K \ + --pcrdupprob=$J \ + --pcrdistribution=MULTINOMIAL \ + --multiparam=0.167,0.152,0.136,0.121,0.106,0.091,0.076,0.061,0.045,0.030,0.015 \ + --poissonparam=1.0 \ + --gcfactor=0.2 \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # Remove the PCR duplicates + + echo '--------------------------------------------------' + echo ""REMOVING PCR DUPLICATES ..."" + + $DDRADSEQTOOLSDIR/pcrdupremoval.py \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --readsfile1=$READSDIR/$SCEREVISIAE'-reads-'$I'-'$J'-'$K'-1.fastq' \ + --readsfile2=$READSDIR/$SCEREVISIAE'-reads-'$I'-'$J'-'$K'-2.fastq' \ + --clearfile=$READSDIR/$SCEREVISIAE'-reads-cleared-'$I'-'$J'-'$K \ + --dupstfile=$STATSDIR/$SCEREVISIAE'-pcrduplicates-stats-'$I'-'$J'-'$K'.txt' \ + --plot=YES \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + done + done +done + +#------------------------------------------------------------------------------- + +# End +echo '**************************************************' +exit 0 + +#------------------------------------------------------------------------------- +","Shell" +"In Silico","GGFHF/ddRADseqTools","Package/simulation-scripts/simulation-mutations-polymorphicloci.sh",".sh","12738","357","#!/bin/bash + +#------------------------------------------------------------------------------- + +# This script generates fragments from the Saccharomyces cerevisiae genome; it +# simulates a double digest and generates their PE reads; it quantifies and +# removes PCR duplicates and calculates the loci number without data; it +# calculates mutation statistics; it demultiplexes the individuals; it trims the +# adapters and other Illumina specific sequences; it aligns the reads and gets +# SAM, BAM, BED and VCF format files to study and visualize alignments; and it +# gets the distinct loci list with mutations. + +#------------------------------------------------------------------------------- + +# Control parameters + +if [ -n ""$*"" ]; then echo 'This script has not parameters.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Set run environment + +SAMTOOLSDIR=/usr/share/samtools # SAMTools directory + +DDRADSEQTOOLSDIR=$TRABAJO/ddRADseqTools # ddRADseqTools programs directory +GENOMESDIR=$TRABAJO/ddRADseqTools/genomes # genomes file directory +FRAGSDIR=$TRABAJO/ddRADseqTools/fragments # fragments directory +READSDIR=$TRABAJO/ddRADseqTools/reads # reads directory +STATSDIR=$TRABAJO/ddRADseqTools/statistics # statistics directory +ALIGNDIR=$TRABAJO/ddRADseqTools/alignments # alignments directory + +if [ ! -d ""$FRAGSDIR"" ]; then mkdir $FRAGSDIR; fi +if [ ! -d ""$READSDIR"" ]; then mkdir $READSDIR; else rm -f $READSDIR/*; fi +if [ ! -d ""$STATSDIR"" ]; then mkdir $STATSDIR; else rm -f $STATSDIR/*; fi +if [ ! -d ""$ALIGNDIR"" ]; then mkdir $ALIGNDIR; else rm -f $ALIGNDIR/*; fi + +GENOME=GCF_000146045.2_R64_genomic.fna.gz # Saccharomyces cerevisiae genome +ENZYME1=EcoRI +ENZYME2=MseI +TECHNIQUE=IND1_IND2_DBR +FORMAT=FASTQ +READTYPE=PE +INDEX1LEN=6 +INDEX2LEN=6 +DBRLEN=4 +WEND=end91 +CEND=end92 +INDIVIDUALSFILE=individuals-8index1-6index2.txt + +MUTPROB=(0.001 0.010 0.020 0.030 0.040 0.050 0.060 0.070 0.080 0.090 0.100) + +if [ `ulimit -n` -lt 1024 ]; then ulimit -n 1024; fi + +#------------------------------------------------------------------------------- + +# Generate genome fragments and get statistics + +echo '**************************************************' +echo 'GENOME FRAGMENTS ARE BEING GENERATED FROM GENOME ...' + +$DDRADSEQTOOLSDIR/rsitesearch.py \ + --genfile=$GENOMESDIR/$GENOME \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --minfragsize=101 \ + --maxfragsize=300 \ + --fragstfile=$STATSDIR/fragments-genome-stats.txt \ + --fragstinterval=25 \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +for I in ""${MUTPROB[@]}"" +do + + # Generate ddRADseq simulated reads + + echo '**************************************************' + echo ""MUTPROB=$I"" + + echo '--------------------------------------------------' + echo 'DDRADSEQ SIMULATED READS ARE BEING GENERATED ...' + + $DDRADSEQTOOLSDIR/simddradseq.py \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readsfile=$READSDIR/'reads-'$I \ + --readtype=$READTYPE \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --locinum=3000 \ + --readsnum=300000 \ + --minreadvar=0.8 \ + --maxreadvar=1.2 \ + --insertlen=100 \ + --mutprob=$I \ + --locusmaxmut=1 \ + --indelprob=0.1 \ + --maxindelsize=10 \ + --dropout=0.0 \ + --pcrdupprob=0.2 \ + --pcrdistribution=MULTINOMIAL \ + --multiparam=0.167,0.152,0.136,0.121,0.106,0.091,0.076,0.061,0.045,0.030,0.015 \ + --poissonparam=1.0 \ + --gcfactor=0.2 \ + --trace=NO \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # Remove the PCR duplicates + + echo '--------------------------------------------------' + echo 'THE PRC DUPLICATES ARE BEING REMOVED ...' + + $DDRADSEQTOOLSDIR/pcrdupremoval.py \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --readsfile1=$READSDIR/'reads-'$I'-1.fastq' \ + --readsfile2=$READSDIR/'reads-'$I'-2.fastq' \ + --clearfile=$READSDIR/'reads-cleared-'$I \ + --dupstfile=$STATSDIR/'pcrduplicates-stats-'$I'.txt' \ + --plot=YES \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # Demultiplex the individual files + + echo '--------------------------------------------------' + echo 'INDIVIDUAL FILES ARE BEING DEMULTIPLEXED ...' + + $DDRADSEQTOOLSDIR/indsdemultiplexing.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --readsfile1=$READSDIR/'reads-cleared-'$I'-1.fastq' \ + --readsfile2=$READSDIR/'reads-cleared-'$I'-2.fastq' \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + ls $READSDIR/demultiplexed-*-1.fastq > $READSDIR/reads-files.txt + + while read FILE_1; do + + FILE_1_R=`echo $FILE_1 | sed 's/demultiplexed/inddemultiplexed-'$I'/g'` + FILE_2=`echo $FILE_1 | sed 's/-1.fastq/-2.fastq/g'` + FILE_2_R=`echo $FILE_2 | sed 's/demultiplexed/inddemultiplexed-'$I'/g'` + + mv $FILE_1 $FILE_1_R + mv $FILE_2 $FILE_2_R + + done < $READSDIR/reads-files.txt + + # Calcultes a statistics of mutated reads and no mutared reads of each individual + + echo '--------------------------------------------------' + echo 'MUTATION STATISTICS ARE BEING CALCULATED ...' + + FILE_STATS=$STATSDIR/'mutations-stats-'$I'.csv' +cat >$FILE_STATS < $READSDIR/reads-files.txt + + while read FILE_1; do + + if [[ $FILE_1 =~ .*errors.* ]]; then continue; fi + + gawk 'function ltrim(s) { sub(/^[ \t\r\n]+/, """", s); return s } + + function rtrim(s) { sub(/[ \t\r\n]+$/, """", s); return s } + + function trim(s) { return rtrim(ltrim(s)) } + + BEGIN { FS = ""|""; mutated_reads = 0; no_mutated_reads = 0 } + + /@/ { if (FNR = 1) individual = trim(substr($6, 14, length($6))) } + + /mutated: True/ { ++mutated_reads } + + /mutated: False/ { ++no_mutated_reads } + + END { printf ""%s;%d;%d;\n"", individual, no_mutated_reads, mutated_reads } + + ' $FILE_1 >> $FILE_STATS + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + done < $READSDIR/reads-files.txt + + # Trim adapters and other Illumina-specific sequences from reads + + echo '--------------------------------------------------' + echo 'ADAPTERS AND OTHER ILLUMINA SPECIFIC SEQUENCES ARE BEING TRIMMED IN INDIVIDUAL FILES ...' + + ls `echo $READSDIR/'inddemultiplexed-'$I'-*-1.fastq'` > $READSDIR/reads-files.txt + + while read FILE_1; do + + if [[ $FILE_1 =~ .*errors.* ]]; then continue; fi + + FILE_2=`echo $FILE_1 | sed 's/-1.fastq/-2.fastq/g'` + FILE_TRIMMED=`echo $FILE_1 | sed 's/-1.fastq/-trimmed/g'` + + $DDRADSEQTOOLSDIR/readstrim.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --readsfile1=$FILE_1 \ + --readsfile2=$FILE_2 \ + --trimfile=$FILE_TRIMMED \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + done < $READSDIR/reads-files.txt + + # Align sequences of individual files in SAM format + + echo '--------------------------------------------------' + echo 'SEQUENCES OF INDIVIDUAL FILES ARE BEING ALIGNED IN SAM FORMAT ...' + + ls `echo $READSDIR/'inddemultiplexed-'$I'-*-trimmed-1.fastq'` > $READSDIR/reads-trimmed-files.txt + + while read FILE1_TRIM; do + + FILE2_TRIM=`echo $FILE1_TRIM | sed 's/-trimmed-1.fastq/-trimmed-2.fastq/g'` + FILE_SAM=`echo $FILE1_TRIM | sed 's/-1.fastq/.sam/g' | sed ""s|$READSDIR|$ALIGNDIR|g""` + bwa mem $GENOMESDIR/$GENOME $FILE1_TRIM $FILE2_TRIM > $FILE_SAM + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + done < $READSDIR/reads-trimmed-files.txt + + #------------------------------------------------------------------------------- + + # Convert SAM files to BED, BAM and VCF format + + echo '--------------------------------------------------' + echo 'SAM FILES ARE BEING CONVERTED IN BAM, BED AND VCF FORMAT ...' + + ls `echo $ALIGNDIR/'inddemultiplexed-'$I'-*.sam'` > $ALIGNDIR/sam-files.txt + + while read FILE_SAM; do + + FILE_BAM=`echo $FILE_SAM | sed 's/.sam/.bam/g'` + FILE_BAM_STATS=`echo $FILE_SAM | sed 's/.sam/-stats-bam.txt/g'` + FILE_BED=`echo $FILE_SAM | sed 's/.sam/.bed/g'` + FILE_SORTED=`echo $FILE_SAM | sed 's/.sam/.sorted/g'` + FILE_SORTED_BAM=`echo $FILE_SAM | sed 's/.sam/.sorted.bam/g'` + FILE_VCF=`echo $FILE_SAM | sed 's/.sam/.vcf/g'` + FILE_VCF_STATS1=`echo $FILE_SAM | sed 's/.sam/-stats-vcf-1.txt/g'` + FILE_VCF_STATS2=`echo $FILE_SAM | sed 's/.sam/-stats-vcf-2.txt/g'` + + # convert SAM file to BAM format + samtools view -bS $FILE_SAM >$FILE_BAM + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # get aligment statistics in a file + samtools flagstat $FILE_BAM >$FILE_BAM_STATS + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # convert BAM file to BED format + bedtools bamtobed -i $FILE_BAM > $FILE_BED + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # sort the BAM file + samtools sort $FILE_BAM $FILE_SORTED + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # index the BAM file + samtools index $FILE_SORTED_BAM + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # convert BAM file to VCF format + samtools mpileup -uf $GENOMESDIR/$GENOME $FILE_SORTED_BAM | bcftools view -vcg - > $FILE_VCF + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # get variant statistics in a file with SAMtools + $SAMTOOLSDIR/vcfutils.pl qstats $FILE_VCF > $FILE_VCF_STATS1 + # -- if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # get variant statistics in a file with VCFtools + vcftools --vcf $FILE_VCF > $FILE_VCF_STATS2 + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + done < $ALIGNDIR/sam-files.txt + + # Get the distinct loci list with mutations + + echo '--------------------------------------------------' + echo 'THE DISTINCT LOCI LIST WITH MUTATIONS ARE BEING GOT ...' + + LOCI_FILE=$ALIGNDIR/loci-$I.txt +cat >$LOCI_FILE < $ALIGNDIR/vcf-files.txt + + while read FILE_VCF; do + + while read -r LINE; do + + if [[ $LINE =~ ^#.*$ ]]; then continue; fi + + echo ""$LINE"" | cut -f 1,2 >> $LOCI_FILE + + done < $FILE_VCF + + done < $ALIGNDIR/vcf-files.txt + + sort -u $LOCI_FILE > $DISTINCT_LOCI_FILE + + DISTINCT_LOCI_TOTAL=`wc -l $DISTINCT_LOCI_FILE | cut -f1 -d' '` + echo ""The dictinct loci list contains $DISTINCT_LOCI_TOTAL loci."" + echo ""$DISTINCT_LOCI_TOTAL"" > $DISTINCT_LOCI_TOTAL_FILE + +done + +#------------------------------------------------------------------------------- + +# End +echo '**************************************************' +exit 0 + +#------------------------------------------------------------------------------- +","Shell" +"In Silico","GGFHF/ddRADseqTools","Package/simulation-scripts/simulation-pipeline-Scerevisiae-pe.sh",".sh","11137","328","#!/bin/bash + +#------------------------------------------------------------------------------- + +# This script generates fragments from the Saccharomyces cerevisiae genome; it +# simulates a double digest and generates their PE reads; it quantifies and +# removes PCR duplicates and calculates the loci number without data; it +# demultiplexes the individuals; it trims the adapters and other Illumina specific +# sequences; it aligns the reads and gets SAM, BAM, BED and VCF format files to +# study and visualize alignments; and it gets the distinct loci list with mutations. + +#------------------------------------------------------------------------------- + +# WARNING + +# This script uses the following bioinformatics tools: +# - BWA v0.7.13 (http://bio-bwa.sourceforge.net/) +# - SAMtools & BCFtools v0.1.19 (http://www.htslib.org/) +# - BEDtools v2.25.0 (http://bedtools.readthedocs.io/) +# - VCFtools v0.1.14-14 (https://vcftools.github.io/) + +#------------------------------------------------------------------------------- + +# Control parameters + +if [ -n ""$*"" ]; then echo 'This script has not parameters.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Set run environment + +SAMTOOLSDIR=/usr/share/samtools # SAMTools directory + +DDRADSEQTOOLSDIR=$TRABAJO/ddRADseqTools # ddRADseqTools programs directory +GENOMESDIR=$TRABAJO/ddRADseqTools/genomes # genomes file directory +FRAGSDIR=$TRABAJO/ddRADseqTools/fragments # fragments directory +READSDIR=$TRABAJO/ddRADseqTools/reads # reads directory +STATSDIR=$TRABAJO/ddRADseqTools/statistics # statistics directory +ALIGNDIR=$TRABAJO/ddRADseqTools/alignments # alignments directory + +if [ ! -d ""$FRAGSDIR"" ]; then mkdir $FRAGSDIR; fi +if [ ! -d ""$READSDIR"" ]; then mkdir $READSDIR; else rm -f $READSDIR/*; fi +if [ ! -d ""$STATSDIR"" ]; then mkdir $STATSDIR; else rm -f $STATSDIR/*; fi +if [ ! -d ""$ALIGNDIR"" ]; then mkdir $ALIGNDIR; else rm -f $ALIGNDIR/*; fi + +GENOME=GCF_000146045.2_R64_genomic.fna.gz # Saccharomyces cerevisiae genome + +ENZYME1=EcoRI +ENZYME2=MseI +TECHNIQUE=IND1_IND2_DBR +FORMAT=FASTQ +READTYPE=PE +INDEX1LEN=6 +INDEX2LEN=6 +DBRLEN=4 +WEND=end91 +CEND=end92 +INDIVIDUALSFILE=individuals-8index1-6index2.txt + +if [ `ulimit -n` -lt 1024 ]; then ulimit -n 1024; fi + +#------------------------------------------------------------------------------- + +# Generate genome fragments and get statistics + +echo '**************************************************' +echo 'GENOME FRAGMENTS ARE BEING GENERATED FROM GENOME ...' + +$DDRADSEQTOOLSDIR/rsitesearch.py \ + --genfile=$GENOMESDIR/$GENOME \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --minfragsize=101 \ + --maxfragsize=300 \ + --fragstfile=$STATSDIR/fragments-genome-stats.txt \ + --fragstinterval=25 \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Generate ddRADseq simulated reads + +echo '**************************************************' +echo 'DDRADSEQ SIMULATED READS ARE BEING GENERATED ...' + +$DDRADSEQTOOLSDIR/simddradseq.py \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readsfile=$READSDIR/reads \ + --readtype=$READTYPE \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --locinum=3000 \ + --readsnum=300000 \ + --minreadvar=0.8 \ + --maxreadvar=1.2 \ + --insertlen=100 \ + --mutprob=0.2 \ + --locusmaxmut=1 \ + --indelprob=0.1 \ + --maxindelsize=10 \ + --dropout=0.05 \ + --pcrdupprob=0.2 \ + --pcrdistribution=MULTINOMIAL \ + --multiparam=0.167,0.152,0.136,0.121,0.106,0.091,0.076,0.061,0.045,0.030,0.015 \ + --poissonparam=1.0 \ + --gcfactor=0.2 \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Remove the PCR duplicates + +echo '**************************************************' +echo 'THE PRC DUPLICATES ARE BEING REMOVED ...' + +$DDRADSEQTOOLSDIR/pcrdupremoval.py \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --readsfile1=$READSDIR/reads-1.fastq \ + --readsfile2=$READSDIR/reads-2.fastq \ + --clearfile=$READSDIR/reads-cleared \ + --dupstfile=$STATSDIR/pcrduplicates-stats.txt \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Demultiplex the individual files + +echo '**************************************************' +echo 'INDIVIDUAL FILES ARE BEING DEMULTIPLEXED ...' + +$DDRADSEQTOOLSDIR/indsdemultiplexing.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --readsfile1=$READSDIR/reads-cleared-1.fastq \ + --readsfile2=$READSDIR/reads-cleared-2.fastq \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Trim adapters and other Illumina-specific sequences from reads + +echo '**************************************************' +echo 'ADAPTERS AND OTHER ILLUMINA SPECIFIC SEQUENCES ARE BEING TRIMMED IN INDIVIDUAL FILES ...' + +ls $READSDIR/demultiplexed-*-1.fastq > $READSDIR/reads-files.txt + +while read FILE_1; do + + if [[ $FILE_1 =~ .*errors.* ]]; then continue; fi + + FILE_2=`echo $FILE_1 | sed 's/-1.fastq/-2.fastq/g'` + FILE_TRIMMED=`echo $FILE_1 | sed 's/-1.fastq/-trimmed/g'` + + $DDRADSEQTOOLSDIR/readstrim.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --readsfile1=$FILE_1 \ + --readsfile2=$FILE_2 \ + --trimfile=$FILE_TRIMMED \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $READSDIR/reads-files.txt + +#------------------------------------------------------------------------------- + +# Index the genome + +echo '**************************************************' +echo 'GENOME IS BEING INDEXED ...' + + +bwa index -a bwtsw $GENOMESDIR/$GENOME +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + +#------------------------------------------------------------------------------- + +# Align sequences of individual files in SAM format + +echo '**************************************************' +echo 'SEQUENCES OF INDIVIDUAL FILES ARE BEING ALIGNED IN SAM FORMAT ...' + +ls $READSDIR/demultiplexed-*-trimmed-1.fastq > $READSDIR/reads-trimmed-files.txt + +while read FILE1_TRIM; do + + FILE2_TRIM=`echo $FILE1_TRIM | sed 's/-trimmed-1.fastq/-trimmed-2.fastq/g'` + FILE_SAM=`echo $FILE1_TRIM | sed 's/-1.fastq/.sam/g' | sed ""s|$READSDIR|$ALIGNDIR|g""` + bwa mem $GENOMESDIR/$GENOME $FILE1_TRIM $FILE2_TRIM > $FILE_SAM + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $READSDIR/reads-trimmed-files.txt + +#------------------------------------------------------------------------------- + +# Convert SAM files to BED, BAM and VCF format + +echo '**************************************************' +echo 'SAM FILES ARE BEING CONVERTED IN BAM, BED AND VCF FORMAT ...' + +ls $ALIGNDIR/*.sam > $ALIGNDIR/sam-files.txt + +while read FILE_SAM; do + + FILE_BAM=`echo $FILE_SAM | sed 's/.sam/.bam/g'` + FILE_BAM_STATS=`echo $FILE_SAM | sed 's/.sam/-stats-bam.txt/g'` + FILE_BED=`echo $FILE_SAM | sed 's/.sam/.bed/g'` + FILE_SORTED=`echo $FILE_SAM | sed 's/.sam/.sorted/g'` + FILE_SORTED_BAM=`echo $FILE_SAM | sed 's/.sam/.sorted.bam/g'` + FILE_VCF=`echo $FILE_SAM | sed 's/.sam/.vcf/g'` + FILE_VCF_STATS1=`echo $FILE_SAM | sed 's/.sam/-stats-vcf-1.txt/g'` + FILE_VCF_STATS2=`echo $FILE_SAM | sed 's/.sam/-stats-vcf-2.txt/g'` + + # convert SAM file to BAM format + samtools view -bS $FILE_SAM >$FILE_BAM + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # get aligment statistic in a file + samtools flagstat $FILE_BAM >$FILE_BAM_STATS + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # convert BAM file to BED format + bedtools bamtobed -i $FILE_BAM > $FILE_BED + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # sort the BAM file + samtools sort $FILE_BAM $FILE_SORTED + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # index the BAM file + samtools index $FILE_SORTED_BAM + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # convert BAM file to VCF format + samtools mpileup -uf $GENOMESDIR/$GENOME $FILE_SORTED_BAM | bcftools view -vcg - > $FILE_VCF + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # get variant statistic in a file with SAMtools + $SAMTOOLSDIR/vcfutils.pl qstats $FILE_VCF > $FILE_VCF_STATS1 + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # get variant statistic in a file with VCFtools + vcftools --vcf $FILE_VCF > $FILE_VCF_STATS2 + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +done < $ALIGNDIR/sam-files.txt + +#------------------------------------------------------------------------------- + +# Get the distinct loci list with mutations + +echo '**************************************************' +echo 'THE DISTINCT LOCI LIST WITH MUTATIONS ARE BEING GOT ...' + +LOCI_FILE=$ALIGNDIR/loci.txt +cat >$LOCI_FILE < $ALIGNDIR/vcf-files.txt + +while read FILE_VCF; do + + while read -r LINE; do + + if [[ $LINE =~ ^#.*$ ]]; then continue; fi + + echo ""$LINE"" | cut -f 1,2 >> $LOCI_FILE + + done < $FILE_VCF + +done < $ALIGNDIR/vcf-files.txt + +sort -u $LOCI_FILE > $DISTINCT_LOCI_FILE + +DISTINCT_LOCI_TOTAL=`wc -l $DISTINCT_LOCI_FILE | cut -f1 -d' '` +echo ""The dictinct loci list contains $DISTINCT_LOCI_TOTAL loci."" +echo ""$DISTINCT_LOCI_TOTAL"" > $DISTINCT_LOCI_TOTAL_FILE + +#------------------------------------------------------------------------------- + +# End +echo '**************************************************' +exit 0 + +#------------------------------------------------------------------------------- +","Shell" +"In Silico","GGFHF/ddRADseqTools","Package/simulation-scripts/simulation-gcfactor.sh",".sh","5473","153","#!/bin/bash + +#------------------------------------------------------------------------------- + +# This software has been developed by Forest Genetics and Physiology Research Group, +# Technical University of Madrid (UPM) + +# Licence: GNU General Public Licence Version 3 + +#------------------------------------------------------------------------------- + +# This script analyses the effect of GC factor on the number of reads to be +# generate and the probability of loci bearing PCR duplicates + +#------------------------------------------------------------------------------- + +# Control parameters + +if [ -n ""$*"" ]; then echo 'This script has not parameters'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Set run environment + +DDRADSEQTOOLSDIR=$TRABAJO/ddRADseqTools # ddRADseqTools programs directory +GENOMESDIR=$TRABAJO/ddRADseqTools/genomes # genomes file directory +FRAGSDIR=$TRABAJO/ddRADseqTools/fragments # fragments directory +READSDIR=$TRABAJO/ddRADseqTools/reads # reads directory +STATSDIR=$TRABAJO/ddRADseqTools/statistics # statistics directory + +if [ ! -d ""$READSDIR"" ]; then mkdir $READSDIR; else rm -f $READSDIR/*; fi +if [ ! -d ""$STATSDIR"" ]; then mkdir $STATSDIR; else rm -f $STATSDIR/*; fi + +GENOME=GCF_000146045.2_R64_genomic.fna.gz # Saccharomyces cerevisiae genome +ENZYME1=EcoRI +ENZYME2=MseI +TECHNIQUE=IND1_IND2_DBR +FORMAT=FASTQ +READTYPE=PE +INDEX1LEN=6 +INDEX2LEN=6 +DBRLEN=4 +WEND=end91 +CEND=end92 +INDIVIDUALSFILE=individuals-8index1-6index2.txt + +READSNUM=(600000 1200000) # readsnum values +PCRDUPPROB=(0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9) # cerevisiae pcrdupprob values +GCFACTOR=(0.0 0.1 0.2 0.3 0.4 0.5) # cerevisiae gcfactor values + +#------------------------------------------------------------------------------- + +# Generate genome fragments and get statistics + +echo '**************************************************' +echo 'GENOME FRAGMENTS ARE BEING GENERATED FROM GENOME ...' + +$DDRADSEQTOOLSDIR/rsitesearch.py \ + --genfile=$GENOMESDIR/$GENOME \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$ENZYME1 \ + --enzyme2=$ENZYME2 \ + --minfragsize=101 \ + --maxfragsize=300 \ + --fragstfile=$STATSDIR/fragments-genome-stats.txt \ + --fragstinterval=25 \ + --plot=YES \ + --verbose=YES \ + --trace=NO +if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + +#------------------------------------------------------------------------------- + +for I in ""${READSNUM[@]}"" +do + for J in ""${PCRDUPPROB[@]}"" + do + for K in ""${GCFACTOR[@]}"" + do + + # Generate ddRADseq simulated reads + + echo '**************************************************' + echo ""READSNUM=$I AND PCRDUPPROB=$J AND GCFACTOR=$K"" + + echo '--------------------------------------------------' + echo 'SIMULATED READS ARE BEING GENERATED ...' + + $DDRADSEQTOOLSDIR/simddradseq.py \ + --fragsfile=$FRAGSDIR/fragments-genome.fasta \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readsfile=$READSDIR/'reads-'$I'-'$J'-'$K \ + --readtype=$READTYPE \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=EcoRI \ + --enzyme2=MseI \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --locinum=3000 \ + --readsnum=$I \ + --minreadvar=0.8 \ + --maxreadvar=1.2 \ + --insertlen=100 \ + --mutprob=0.2 \ + --locusmaxmut=1 \ + --indelprob=0.1 \ + --maxindelsize=10 \ + --dropout=0.0 \ + --pcrdupprob=$J \ + --pcrdistribution=MULTINOMIAL \ + --multiparam=0.167,0.152,0.136,0.121,0.106,0.091,0.076,0.061,0.045,0.030,0.015 \ + --poissonparam=1.0 \ + --gcfactor=$K \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # Remove the PCR duplicates + + echo '--------------------------------------------------' + echo 'REMOVING PCR DUPLICATES ...' + + $DDRADSEQTOOLSDIR/pcrdupremoval.py \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --readsfile1=$READSDIR/'reads-'$I'-'$J'-'$K'-1.fastq' \ + --readsfile2=$READSDIR/'reads-'$I'-'$J'-'$K'-2.fastq' \ + --clearfile=$READSDIR/'reads-cleared-'$I'-'$J'-'$K \ + --dupstfile=$STATSDIR/'pcrduplicates-stats-'$I'-'$J'-'$K'.txt' \ + --plot=YES \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + done + done +done + +#------------------------------------------------------------------------------- + +# End +echo '**************************************************' +exit 0 + +#------------------------------------------------------------------------------- +","Shell" +"In Silico","GGFHF/ddRADseqTools","Package/simulation-scripts/simulation-performance.sh",".sh","24423","615","#!/bin/bash + +#------------------------------------------------------------------------------- + +# This software has been developed by Forest Genetics and Physiology Research Group, +# Technical University of Madrid (UPM) + +# Licence: GNU General Public Licence Version 3 + +#------------------------------------------------------------------------------- + +# This script studies the performance of the ddRADseqTols programs + +#------------------------------------------------------------------------------- + +# Control parameters + +if [ -n ""$*"" ]; then echo 'This script has not parameters'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Set run environment + +DDRADSEQTOOLSDIR=$TRABAJO/ddRADseqTools # ddRADseqTools programs directory +GENOMESDIR=$TRABAJO/ddRADseqTools/genomes # genomes file directory +FRAGSDIR=$TRABAJO/ddRADseqTools/fragments # fragments directory +READSDIR=$TRABAJO/ddRADseqTools/reads # reads directory +STATSDIR=$TRABAJO/ddRADseqTools/statistics # statistics directory + +if [ ! -d ""$FRAGSDIR"" ]; then mkdir $FRAGSDIR; else rm -f $FRAGSDIR/*; fi +if [ ! -d ""$READSDIR"" ]; then mkdir $READSDIR; else rm -f $READSDIR/*; fi +if [ ! -d ""$STATSDIR"" ]; then mkdir $STATSDIR; else rm -f $STATSDIR/*; fi + +ENZYME1=(EcoRI SbfI PstI) # codes of 1st restriction enzyme to study +ENZYME2=(MseI) # codes of 2nd restriction enzyme to study + +SCEREVISIAE='Scerevisiae' # Saccharomyces cerevisiae +SCEREVISIAE_GENOME=GCF_000146045.2_R64_genomic.fna.gz # Saccharomyces cerevisiae genome +SCEREVISIAE_FRAGS_FILE=$SCEREVISIAE'-fragments-EcoRI-MseI.fasta' # Saccharomyces cerevisiae framents gotten by EcoI and MseI digest +SCEREVISIAE_READSNUM=(300000 2400000) # Saccharomyces cerevisiae readsnum values +SCEREVISIAE_PCRDUPPROB=(0.2 0.6) # Saccharomyces cerevisiae pcrdupprob values + +HSAPIENS='Hsapiens' # Homo sapiens +HSAPIENS_GENOME=GCF_000001405.29_GRCh38.p3_genomic.fna.gz # Homo sapiens genome +HSAPIENS_FRAGS_FILE=$HSAPIENS'-fragments-SbfI-MseI.fasta' # Homo sapiens framents gotten by SbfI and MseI digest +HSAPIENS_READSNUM=(2000000 16100000) # Homo sapiens readsnum values +HSAPIENS_PCRDUPPROB=(0.2 0.6) # Homo sapiens pcrdupprob values + +PTAEDA='Ptaeda' # Pinus taeda +PTAEDA_GENOME=ptaeda.v1.01.scaffolds.fasta.gz # Pinus taeda genome +PTAEDA_FRAGS_FILE=$PTAEDA'-fragments-SbfI-MseI.fasta' # Pinus taeda framents gotten by SbfI and MseI digest +PTAEDA_READSNUM=(2500000 20400000) # Pinus taeda readsnum values +PTAEDA_PCRDUPPROB=(0.2 0.6) # Pinus taeda pcrdupprob values + +TECHNIQUE=IND1_IND2_DBR +FORMAT=FASTQ +READTYPE=PE +INDEX1LEN=6 +INDEX2LEN=6 +DBRLEN=4 +WEND=end31 +CEND=end32 +INDIVIDUALSFILE=individuals-8index1-6index2.txt + +TIME_FILE=$STATSDIR/time.csv # times and resources data of each run + +cat >$TIME_FILE < $READSDIR/reads-files.txt + + while read FILE_1; do + + FILE_1_R=`echo $FILE_1 | sed 's/demultiplexed/'$SCEREVISIAE'-demultiplexed-'$I'-'$J'/g'` + FILE_2=`echo $FILE_1 | sed 's/-1.fastq/-2.fastq/g'` + FILE_2_R=`echo $FILE_2 | sed 's/demultiplexed/'$SCEREVISIAE'-demultiplexed-'$I'-'$J'/g'` + + mv $FILE_1 $FILE_1_R + mv $FILE_2 $FILE_2_R + + done < $READSDIR/reads-files.txt + + echo '--------------------------------------------------' + echo 'ADAPTERS AND OTHER ILLUMINA SPECIFIC SEQUENCES ARE BEING TRIMMED IN INDIVIDUAL FILES ...' + + ls `echo $READSDIR/$SCEREVISIAE'-demultiplexed-'$I'-'$J'-ind*-1.fastq'` > $READSDIR/reads-files.txt + + while read FILE_1; do + + FILE_2=`echo $FILE_1 | sed 's/-1.fastq/-2.fastq/g'` + FILE_TRIMMED=`echo $FILE_1 | sed 's/-1.fastq/-trimmed/g'` + + /usr/bin/time \ + --output=$TIME_FILE \ + --append \ + --format='readstrim;'$SCEREVISIAE';'$I';'$J';%e;%S;%U;%P;%M;%K;' \ + $DDRADSEQTOOLSDIR/readstrim.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --readsfile1=$FILE_1 \ + --readsfile2=$FILE_2 \ + --trimfile=$FILE_TRIMMED \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + done < $READSDIR/reads-files.txt + + done +done + +#------------------------------------------------------------------------------- + +# Homo sapiens + +echo '**************************************************' +echo 'HOMO SAPIENS' + +for I in ""${ENZYME1[@]}"" +do + for J in ""${ENZYME2[@]}"" + do + + echo '--------------------------------------------------' + echo ""GENOME FRAGMENTS ARE BEING GENERATED WITH ENZYME1=$I AND ENZYME2=$J ..."" + + /usr/bin/time \ + --output=$TIME_FILE \ + --append \ + --format='rsitesearch.py;'$HSAPIENS';'$I';'$J';%e;%S;%U;%P;%M;%K;' \ + $DDRADSEQTOOLSDIR/rsitesearch.py \ + --genfile=$GENOMESDIR/$HSAPIENS_GENOME \ + --fragsfile=$FRAGSDIR/$HSAPIENS'-fragments-'$I'-'$J'.fasta' \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$I \ + --enzyme2=$J \ + --minfragsize=201 \ + --maxfragsize=300 \ + --fragstfile=$STATSDIR/$HSAPIENS'-fragments-'$I'-'$J'-stats.txt' \ + --fragstinterval=25 \ + --plot=YES \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + done +done + +for I in ""${HSAPIENS_READSNUM[@]}"" +do + for J in ""${HSAPIENS_PCRDUPPROB[@]}"" + do + + # Generate ddRADseq simulated reads + + echo '--------------------------------------------------' + echo ""SIMULATED READS ARE BEING GENERATED WITH READSNUM=$I AND PCRDUPPROB=$J ..."" + + /usr/bin/time \ + --output=$TIME_FILE \ + --append \ + --format='simddradseq;'$HSAPIENS';'$I';'$J';%e;%S;%U;%P;%M;%K;' \ + $DDRADSEQTOOLSDIR/simddradseq.py \ + --fragsfile=$FRAGSDIR/$HSAPIENS_FRAGS_FILE \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readsfile=$READSDIR/$HSAPIENS'-reads-'$I'-'$J \ + --readtype=$READTYPE \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=SbfI \ + --enzyme2=MseI \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --locinum=20700 \ + --readsnum=$I \ + --minreadvar=0.8 \ + --maxreadvar=1.2 \ + --insertlen=100 \ + --mutprob=0.2 \ + --locusmaxmut=1 \ + --indelprob=0.1 \ + --maxindelsize=10 \ + --dropout=0.0 \ + --pcrdupprob=$J \ + --pcrdistribution=MULTINOMIAL \ + --multiparam=0.167;0.152;0.136;0.121;0.106;0.091;0.076;0.061;0.045;0.030;0.015 \ + --poissonparam=1.0 \ + --gcfactor=0.2 \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + # Remove the PCR duplicates + + echo '--------------------------------------------------' + echo ""REMOVING PCR DUPLICATES ..."" + + /usr/bin/time \ + --output=$TIME_FILE \ + --append \ + --format='pcrdupremoval;'$HSAPIENS';'$I';'$J';%e;%S;%U;%P;%M;%K;' \ + $DDRADSEQTOOLSDIR/pcrdupremoval.py \ + --readsfile1=$READSDIR/$HSAPIENS'-reads-'$I'-'$J'-1.fastq' \ + --readsfile2=$READSDIR/$HSAPIENS'-reads-'$I'-'$J'-2.fastq' \ + --clearfile=$READSDIR/$HSAPIENS'-reads-cleared-'$I'-'$J \ + --dupstfile=$STATSDIR/$HSAPIENS'-pcrduplicates-stats-'$I'-'$J'.txt' \ + --plot=YES \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + echo '--------------------------------------------------' + echo 'INDIVIDUAL FILES ARE BEING DEMULTIPLEXED ...' + + /usr/bin/time \ + --output=$TIME_FILE \ + --append \ + --format='indsdemultiplexing;'$HSAPIENS';'$I';'$J';%e;%S;%U;%P;%M;%K;' \ + $DDRADSEQTOOLSDIR/indsdemultiplexing.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --readsfile1=$READSDIR/$HSAPIENS'-reads-cleared-'$I'-'$J'-1.fastq' \ + --readsfile2=$READSDIR/$HSAPIENS'-reads-cleared-'$I'-'$J'-2.fastq' \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + ls $READSDIR/demultiplexed-ind*-1.fastq > $READSDIR/reads-files.txt + + while read FILE_1; do + + FILE_1_R=`echo $FILE_1 | sed 's/demultiplexed/'$HSAPIENS'-demultiplexed-'$I'-'$J'/g'` + FILE_2=`echo $FILE_1 | sed 's/-1.fastq/-2.fastq/g'` + FILE_2_R=`echo $FILE_2 | sed 's/demultiplexed/'$HSAPIENS'-demultiplexed-'$I'-'$J'/g'` + + mv $FILE_1 $FILE_1_R + mv $FILE_2 $FILE_2_R + + done < $READSDIR/reads-files.txt + + echo '--------------------------------------------------' + echo 'ADAPTERS AND OTHER ILLUMINA SPECIFIC SEQUENCES ARE BEING TRIMMED IN INDIVIDUAL FILES ...' + + ls `echo $READSDIR/$HSAPIENS'-demultiplexed-'$I'-'$J'-ind*-1.fastq'` > $READSDIR/reads-files.txt + + while read FILE_1; do + + FILE_2=`echo $FILE_1 | sed 's/-1.fastq/-2.fastq/g'` + FILE_TRIMMED=`echo $FILE_1 | sed 's/-1.fastq/-trimmed/g'` + + /usr/bin/time \ + --output=$TIME_FILE \ + --append \ + --format='readstrim;'$HSAPIENS';'$I';'$J';%e;%S;%U;%P;%M;%K;' \ + $DDRADSEQTOOLSDIR/readstrim.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --readsfile1=$FILE_1 \ + --readsfile2=$FILE_2 \ + --trimfile=$FILE_TRIMMED \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + done < $READSDIR/reads-files.txt + + done +done + +#------------------------------------------------------------------------------- + +# Pinus taeda + +echo '**************************************************' +echo 'PINUS TAEDA' + +for I in ""${ENZYME1[@]}"" +do + for J in ""${ENZYME2[@]}"" + do + + echo '--------------------------------------------------' + echo ""GENOME FRAGMENTS ARE BEING GENERATED WITH ENZYME1=$I AND ENZYME2=$J ..."" + + /usr/bin/time \ + --output=$TIME_FILE \ + --append \ + --format='rsitesearch.py;'$PTAEDA';'$I';'$J';%e;%S;%U;%P;%M;%K;' \ + $DDRADSEQTOOLSDIR/rsitesearch.py \ + --genfile=$GENOMESDIR/$PTAEDA_GENOME \ + --fragsfile=$FRAGSDIR/$PTAEDA'-fragments-'$I'-'$J'.fasta' \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$I \ + --enzyme2=$J \ + --minfragsize=201 \ + --maxfragsize=300 \ + --fragstfile=$STATSDIR/$PTAEDA'-fragments-'$I'-'$J'-stats.txt' \ + --fragstinterval=25 \ + --plot=YES \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + done +done + +for I in ""${PTAEDA_READSNUM[@]}"" +do + for J in ""${PTAEDA_PCRDUPPROB[@]}"" + do + + # Generate ddRADseq simulated reads + + echo '--------------------------------------------------' + echo ""SIMULATED READS ARE BEING GENERATED WITH READSNUM=$I AND PCRDUPPROB=$J ..."" + + /usr/bin/time \ + --output=$TIME_FILE \ + --append \ + --format='simddradseq;'$PTAEDA';'$I';'$J';%e;%S;%U;%P;%M;%K;' \ + $DDRADSEQTOOLSDIR/simddradseq.py \ + --fragsfile=$FRAGSDIR/$PTAEDA_FRAGS_FILE \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readsfile=$READSDIR/$PTAEDA'-reads-'$I'-'$J \ + --readtype=$READTYPE \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=SbfI \ + --enzyme2=MseI \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --locinum=26000 \ + --readsnum=$I \ + --minreadvar=0.8 \ + --maxreadvar=1.2 \ + --insertlen=100 \ + --mutprob=0.2 \ + --locusmaxmut=1 \ + --indelprob=0.1 \ + --maxindelsize=10 \ + --dropout=0.0 \ + --pcrdupprob=$J \ + --pcrdistribution=MULTINOMIAL \ + --multiparam=0.167;0.152;0.136;0.121;0.106;0.091;0.076;0.061;0.045;0.030;0.015 \ + --poissonparam=1.0 \ + --gcfactor=0.2 \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + + # Remove the PCR duplicates + + echo '--------------------------------------------------' + echo ""REMOVING PCR DUPLICATES ..."" + + /usr/bin/time \ + --output=$TIME_FILE \ + --append \ + --format='pcrdupremoval;'$PTAEDA';'$I';'$J';%e;%S;%U;%P;%M;%K;' \ + $DDRADSEQTOOLSDIR/pcrdupremoval.py \ + --readsfile1=$READSDIR/$PTAEDA'-reads-'$I'-'$J'-1.fastq' \ + --readsfile2=$READSDIR/$PTAEDA'-reads-'$I'-'$J'-2.fastq' \ + --clearfile=$READSDIR/$PTAEDA'-reads-cleared-'$I'-'$J \ + --dupstfile=$STATSDIR/$PTAEDA'-pcrduplicates-stats-'$I'-'$J'.txt' \ + --plot=YES \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + echo '--------------------------------------------------' + echo 'INDIVIDUAL FILES ARE BEING DEMULTIPLEXED ...' + + /usr/bin/time \ + --output=$TIME_FILE \ + --append \ + --format='indsdemultiplexing;'$PTAEDA';'$I';'$J';%e;%S;%U;%P;%M;%K;' \ + $DDRADSEQTOOLSDIR/indsdemultiplexing.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --individualsfile=$DDRADSEQTOOLSDIR/$INDIVIDUALSFILE \ + --readsfile1=$READSDIR/$PTAEDA'-reads-cleared-'$I'-'$J'-1.fastq' \ + --readsfile2=$READSDIR/$PTAEDA'-reads-cleared-'$I'-'$J'-2.fastq' \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + ls $READSDIR/demultiplexed-ind*-1.fastq > $READSDIR/reads-files.txt + + while read FILE_1; do + + FILE_1_R=`echo $FILE_1 | sed 's/demultiplexed/'$PTAEDA'-demultiplexed-'$I'-'$J'/g'` + FILE_2=`echo $FILE_1 | sed 's/-1.fastq/-2.fastq/g'` + FILE_2_R=`echo $FILE_2 | sed 's/demultiplexed/'$PTAEDA'-demultiplexed-'$I'-'$J'/g'` + + mv $FILE_1 $FILE_1_R + mv $FILE_2 $FILE_2_R + + done < $READSDIR/reads-files.txt + + echo '--------------------------------------------------' + echo 'ADAPTERS AND OTHER ILLUMINA SPECIFIC SEQUENCES ARE BEING TRIMMED IN INDIVIDUAL FILES ...' + + ls `echo $READSDIR/$PTAEDA'-demultiplexed-'$I'-'$J'-ind*-1.fastq'` > $READSDIR/reads-files.txt + + while read FILE_1; do + + FILE_2=`echo $FILE_1 | sed 's/-1.fastq/-2.fastq/g'` + FILE_TRIMMED=`echo $FILE_1 | sed 's/-1.fastq/-trimmed/g'` + + /usr/bin/time \ + --output=$TIME_FILE \ + --append \ + --format='readstrim;'$PTAEDA';'$I';'$J';%e;%S;%U;%P;%M;%K;' \ + $DDRADSEQTOOLSDIR/readstrim.py \ + --technique=$TECHNIQUE \ + --format=$FORMAT \ + --readtype=$READTYPE \ + --endsfile=$DDRADSEQTOOLSDIR/ends.txt \ + --index1len=$INDEX1LEN \ + --index2len=$INDEX2LEN \ + --dbrlen=$DBRLEN \ + --wend=$WEND \ + --cend=$CEND \ + --readsfile1=$FILE_1 \ + --readsfile2=$FILE_2 \ + --trimfile=$FILE_TRIMMED \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + done < $READSDIR/reads-files.txt + + done +done + +#------------------------------------------------------------------------------- + +# End +echo '**************************************************' +exit 0 + +#------------------------------------------------------------------------------- +","Shell" +"In Silico","GGFHF/ddRADseqTools","Package/simulation-scripts/simulation-genomes.sh",".sh","5295","151","#!/bin/bash + +#------------------------------------------------------------------------------- + +# This software has been developed by Forest Genetics and Physiology Research Group, +# Technical University of Madrid (UPM) + +# Licence: GNU General Public Licence Version 3 + +#------------------------------------------------------------------------------- + +# This script analyzes how several enzymes pairs perform a double digest of the +# genome of Saccharomyces cerevisiae, Homo sapiens and Pinus taeda + +#------------------------------------------------------------------------------- + +# Control parameters + +if [ -n ""$*"" ]; then echo 'This script has not parameters'; exit 1; fi + +#------------------------------------------------------------------------------- + +# Set run environment + +DDRADSEQTOOLSDIR=$TRABAJO/ddRADseqTools # ddRADseqTools programs directory +GENOMESDIR=$TRABAJO/ddRADseqTools/genomes # genomes file directory +FRAGSDIR=$TRABAJO/ddRADseqTools/fragments # fragments directory +STATSDIR=$TRABAJO/ddRADseqTools/statistics # statistics directory + +if [ ! -d ""$FRAGSDIR"" ]; then mkdir $FRAGSDIR; else rm -f $FRAGSDIR/*; fi +if [ ! -d ""$STATSDIR"" ]; then mkdir $STATSDIR; else rm -f $STATSDIR/*; fi + +SCEREVISIAE='Scerevisiae' # Saccharomyces cerevisiae +SCEREVISIAE_GENOME=GCF_000146045.2_R64_genomic.fna.gz # Saccharomyces cerevisiae genome + +HSAPIENS='Hsapiens' # Homo sapiens +HSAPIENS_GENOME=GCF_000001405.29_GRCh38.p3_genomic.fna.gz # Homo sapiens genome + +PTAEDA='Ptaeda' # Pinus taeda +PTAEDA_GENOME=ptaeda.v1.01.scaffolds.fasta.gz # Pinus taeda genome + +ENZYME1=(EcoRI SbfI PstI) # codes of 1st restriction enzyme to study +ENZYME2=(MseI) # codes of 2nd restriction enzyme to study + +#------------------------------------------------------------------------------- + +# Generate Saccharomyces cerevisiae genome fragments + +echo '**************************************************' +echo 'SACCHAROMYCES CEREVISIAE - GENOME FRAGMENTS ARE BEING GENERATED ...' + +for I in ""${ENZYME1[@]}"" +do + for J in ""${ENZYME2[@]}"" + do + + echo '--------------------------------------------------' + echo ""SIMULATION WITH ENZYME1=$I AND ENZYME2=$J ..."" + + $DDRADSEQTOOLSDIR/rsitesearch.py \ + --genfile=$GENOMESDIR/$SCEREVISIAE_GENOME \ + --fragsfile=$FRAGSDIR/$SCEREVISIAE'-fragments-'$I'-'$J'.fasta' \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$I \ + --enzyme2=$J \ + --minfragsize=101 \ + --maxfragsize=300 \ + --fragstfile=$STATSDIR/$SCEREVISIAE'-fragments-'$I'-'$J'-stats.txt' \ + --fragstinterval=25 \ + --plot=YES \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + done +done + +#------------------------------------------------------------------------------- + +# Generate Homo sapiens genome fragments + +echo '**************************************************' +echo 'HOMO SAPIENS - FRAGMENTS ARE BEING GENERATED ...' + +for I in ""${ENZYME1[@]}"" +do + for J in ""${ENZYME2[@]}"" + do + + echo '--------------------------------------------------' + echo ""SIMULATION WITH ENZYME1=$I AND ENZYME2=$J ..."" + + $DDRADSEQTOOLSDIR/rsitesearch.py \ + --genfile=$GENOMESDIR/$HSAPIENS_GENOME \ + --fragsfile=$FRAGSDIR/$HSAPIENS'-fragments-'$I'-'$J'.fasta' \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$I \ + --enzyme2=$J \ + --minfragsize=201 \ + --maxfragsize=300 \ + --fragstfile=$STATSDIR/$HSAPIENS'-fragments-'$I'-'$J'-stats.txt' \ + --fragstinterval=25 \ + --plot=YES \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + done +done + +#------------------------------------------------------------------------------- + +# Generate Pinus taeda genome fragments + +echo '**************************************************' +echo 'PINUS TAEDA - GENOME FRAGMENTS ARE BEING GENERATED ...' + +for I in ""${ENZYME1[@]}"" +do + for J in ""${ENZYME2[@]}"" + do + + echo '--------------------------------------------------' + echo ""SIMULATION WITH ENZYME1=$I AND ENZYME2=$J ..."" + + $DDRADSEQTOOLSDIR/rsitesearch.py \ + --genfile=$GENOMESDIR/$PTAEDA_GENOME \ + --fragsfile=$FRAGSDIR/$PTAEDA'-fragments-'$I'-'$J'.fasta' \ + --rsfile=$DDRADSEQTOOLSDIR/restrictionsites.txt \ + --enzyme1=$I \ + --enzyme2=$J \ + --minfragsize=201 \ + --maxfragsize=300 \ + --fragstfile=$STATSDIR/$PTAEDA'-fragments-'$I'-'$J'-stats.txt' \ + --fragstinterval=25 \ + --plot=YES \ + --verbose=YES \ + --trace=NO + if [ $? -ne 0 ]; then echo 'Script ended with errors.'; exit 1; fi + + done +done + +#------------------------------------------------------------------------------- + +# End +echo '**************************************************' +exit 0 + +#------------------------------------------------------------------------------- +","Shell" +"In Silico","wingolab-org/mpd-perl","LICENSE.md",".md","35147","675"," 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 +. +","Markdown" +"In Silico","wingolab-org/mpd-perl","ex/mpdSetup.sh",".sh","932","39","#!/usr/bin/sh + +git clone git@github.com:wingolab-org/mpd-c.git +cd mpd-c +make +cd ~/bin +sudo ln -sv ~/mpd-c/bin/* . + +# get isPcr from UCSC / Jim Kent +sudo yum install mysql-devel libpng-devel libstdc++-devel zlib-devel +export MACHTYPE=x86_64 +git clone git://genome-source.cse.ucsc.edu/kent.git + +# NOTE: +# 1) Here is what you need to change in the make /src/inc/common.mk +# to enable building on AMS. +# [ec2-user@ip-172-31-55-133 kent]$ git diff +# diff --git a/src/inc/common.mk b/src/inc/common.mk +# index 1204208..e2416eb 100644 +# --- a/src/inc/common.mk +# +++ b/src/inc/common.mk +# @@ -25,7 +25,7 @@ UNAME_S := $(shell uname -s) +# FULLWARN = $(shell uname -n) +# +# #global external libraries +# -L=$(kentSrc)/htslib/libhts.a +# +L=$(kentSrc)/htslib/libhts.a -lz +# +# # pthreads is required +# ifneq ($(UNAME_S),Darwin) +# 2) binaries are installed to: /home/ec2-user/kent/src/lib/x86_64/ + +cd jkOwnLib +make +cd .. +make blatSuite + + +","Shell" +"In Silico","stjude/PrimerTK","setup.py",".py","1077","35","import setuptools + +setuptools.setup( + name='primer_tk', + version='1.0.3', + scripts=['./scripts/primer_tk'], + author=""Dennis Kennetz"", + author_email=""dennis.kennetz@stjude.org"", + description=""A toolkit to design primers in multiplex pools and around SVs."", + packages=['primer_tk', 'primer_tk.tests'], + package_dir={'primer_tk': 'src/primer_tk', 'primer_tk.tests': 'test/python_tests'}, + package_data={'test': [ + 'data/*']}, + install_requires=[ + 'setuptools', + 'pandas >= 0.22.0', + 'numpy >= 1.16.0', + 'biopython >= 1.70', + 'pysam==0.15.2' + ], + python_requires='>=3.5.*', + test_suite='test', + tests_require=['unittest', 'coverage'], + zip_safe=True, + license='Apache2.0', + url = 'https://github.com/stjude/PrimerTK', + download_url = 'https://github.com/stjude/PrimerTK/archive/1.0.3.tar.gz', + classifiers=[ + ""Programming Language :: Python :: 3"", + 'Environment :: Console', + 'Natural Language :: English', + 'Operating System :: OS Independent' + ], +) +","Python" +"In Silico","stjude/PrimerTK","src/primer_tk/mp_class.py",".py","6958","155","#!/usr/bin/env python3 + +"""""" +Dependencies required to run program: + - python3.6+ + - pandas>=0.22.0 + - numpy>=1.16.0 +"""""" + +import sys +import pandas as pd +import numpy as np + +class MissingPrimers: + """""" + Groups Primer3 output by sample id into a list of lists, + adds NA to all groups that do not have 5 primers generated, + and then outputs a list corresponding to each primer rank. + Args: + file_name (string): name of file to be passed to program + value (int): rank of primer pair to store as list [0-4] only + Returns: + samp_primer_info (list): list of lists with all values required for + downstream analysis (id, lseq, rseq, l_tm, r_tm, + l_gc, r_gc, product_size) + """""" + def __init__(self, file_name, value): + """""" + Initialize Values + """""" + self.file_name = file_name + if value >= 0 and value <=4: + self.value = str(value) + else: + sys.exit(""Improper value selected! Acceptable values: 0,1,2,3,4."") + self.dump_list = self.__group_seqids() + self.filled_primers = self.__fill_empty_values() + self.samp_primer_info = self.__gather_primer_info() + + def __group_seqids(self): + """""" + Group by sample_id + """""" + sequence = """" + with open(self.file_name) as dump: + for line in dump: + if not line.startswith('='): + sequence += line + if line.startswith('='): + fixed_line = line.replace('=', '@@@') + sequence += fixed_line + full_string = ''.join([line for line in sequence]) + primer_split = [[string] for string in full_string.\ + split('@@@') if string is not ' '] + primers_info = primer_split[:-1] + return primers_info + + def __fill_empty_values(self): + """""" + Fill in missing required values with NA + """""" + sequence = [] + for sample in self.dump_list: + for string in sample: + if ""PRIMER_LEFT_0_SEQUENCE="" not in string: + string = string + ""PRIMER_LEFT_0_SEQUENCE=NA\n""\ + + ""PRIMER_RIGHT_0_SEQUENCE=NA\n""\ + + ""PRIMER_LEFT_0_TM=NA\n"" + ""PRIMER_RIGHT_0_TM=NA\n""\ + + ""PRIMER_LEFT_0_GC_PERCENT=NA\n""\ + + ""PRIMER_RIGHT_0_GC_PERCENT=NA\n""\ + + ""PRIMER_PAIR_0_PRODUCT_SIZE=NA\n"" + if ""PRIMER_LEFT_1_SEQUENCE="" not in string: + string = string + ""PRIMER_LEFT_1_SEQUENCE=NA\n""\ + + ""PRIMER_RIGHT_1_SEQUENCE=NA\n""\ + + ""PRIMER_LEFT_1_TM=NA\n"" + ""PRIMER_RIGHT_1_TM=NA\n""\ + + ""PRIMER_LEFT_1_GC_PERCENT=NA\n""\ + + ""PRIMER_RIGHT_1_GC_PERCENT=NA\n""\ + + ""PRIMER_PAIR_1_PRODUCT_SIZE=NA\n"" + if ""PRIMER_LEFT_2_SEQUENCE="" not in string: + string = string + ""PRIMER_LEFT_2_SEQUENCE=NA\n""\ + + ""PRIMER_RIGHT_2_SEQUENCE=NA\n""\ + + ""PRIMER_LEFT_2_TM=NA\n"" + ""PRIMER_RIGHT_2_TM=NA\n""\ + + ""PRIMER_LEFT_2_GC_PERCENT=NA\n""\ + + ""PRIMER_RIGHT_2_GC_PERCENT=NA\n""\ + + ""PRIMER_PAIR_2_PRODUCT_SIZE=NA\n"" + if ""PRIMER_LEFT_3_SEQUENCE="" not in string: + string = string + ""PRIMER_LEFT_3_SEQUENCE=NA\n""\ + + ""PRIMER_RIGHT_3_SEQUENCE=NA\n""\ + + ""PRIMER_LEFT_3_TM=NA\n"" + ""PRIMER_RIGHT_3_TM=NA\n""\ + + ""PRIMER_LEFT_3_GC_PERCENT=NA\n""\ + + ""PRIMER_RIGHT_3_GC_PERCENT=NA\n""\ + + ""PRIMER_PAIR_3_PRODUCT_SIZE=NA\n"" + if ""PRIMER_LEFT_4_SEQUENCE="" not in string: + string = string + ""PRIMER_LEFT_4_SEQUENCE=NA\n""\ + + ""PRIMER_RIGHT_4_SEQUENCE=NA\n""\ + + ""PRIMER_LEFT_4_TM=NA\n"" + ""PRIMER_RIGHT_4_TM=NA\n""\ + + ""PRIMER_LEFT_4_GC_PERCENT=NA\n""\ + + ""PRIMER_RIGHT_4_GC_PERCENT=NA\n""\ + + ""PRIMER_PAIR_4_PRODUCT_SIZE=NA\n"" + sequence.append(string.lstrip('\n').split('\n')) + + return sequence + + def __gather_primer_info(self): + """""" + Return the final list of lists with all filled values by rank + """""" + sample_info = [] + for item in self.filled_primers: + for p_info in item: + if ""SEQUENCE_ID="" in p_info: + seq_id = p_info[12:]+self.value + if ""PRIMER_LEFT_%s_SEQUENCE="" %self.value in p_info: + p_left = p_info[23:] + if ""PRIMER_RIGHT_%s_SEQUENCE="" %self.value in p_info: + p_right = p_info[24:] + if ""PRIMER_LEFT_%s_TM="" %self.value in p_info: + left_tm = p_info[17:] + if ""PRIMER_RIGHT_%s_TM="" %self.value in p_info: + right_tm = p_info[18:] + if ""PRIMER_LEFT_%s_GC_PERCENT="" %self.value in p_info: + left_gc = p_info[25:] + if ""PRIMER_RIGHT_%s_GC_PERCENT="" %self.value in p_info: + right_gc = p_info[26:] + if ""PRIMER_PAIR_%s_PRODUCT_SIZE="" %self.value in p_info: + product_size = p_info[27:] + sample_info.append([seq_id, p_left, p_right, left_tm, + right_tm, left_gc, right_gc, + product_size]) + + return sample_info + +def create_df(primer_lists): + """""" + Creates a dataframe from gather_primer_info + Args: + primer_lists (list): primer information lists to be passed for dataframe. + Returns: + primer_df (pd.DataFrame): Dataframe with all primer information. + """""" + primer_df = pd.DataFrame(np.ma.row_stack(primer_lists), + columns=['Sequence ID', 'Primer Left Seq', 'Primer Right Seq', + 'Primer Left TM', 'Primer Right TM', + 'Primer Left GC %', 'Primer Right GC %', + 'Primer3 Predicted Product']) + primer_df = primer_df.sort_values('Sequence ID').reset_index().drop(labels='index', axis=1) + rank = [num[-1] for num in primer_df['Sequence ID']] + primer_df.insert(1, 'Primer Rank', rank) + left_len = [len(length) for length in primer_df['Primer Left Seq']] + right_len = [len(length) for length in primer_df['Primer Right Seq']] + primer_df.insert(4, 'Primer Left Len', left_len) + primer_df.insert(5, 'Primer Right Len', right_len) + primer_df['Sequence ID'] = [seqid[:-1] for seqid in primer_df['Sequence ID']] + return primer_df +","Python" +"In Silico","stjude/PrimerTK","src/primer_tk/analyze_pcr_output_sv.py",".py","8412","190","#!/usr/bin/env python + +"""""" +Dependencies required to run program: + - python3.6+ + - pandas>=0.22.0 + - argparse + - sequence_info +"""""" + +import sys +import argparse +import pandas as pd +from primer_tk import sequence_info as seqinf + +def add_post_subparser(subparser): + """""" Add subparser for postprocessing sv step. + + Args: + subparser (?): Subparser object. + + Returns: None + """""" + parser = subparser.add_parser(""post_sv"", help='Parses info from pcr_output') + parser.add_argument(""-f"", ""--flank_file"", dest=""flank_file"", + help=""use flanking_regions file from output of genome_iterator_sv.py"") + parser.add_argument(""-tp"", ""--total_primers"", dest=""total_primers"", + help=""the pre-PCR master primer file that\ + contains all sample + primer info"") + parser.add_argument(""-all"", ""--all_final_primers"", default=""all_final_primers_sv.csv"", + help=""all primers generated for targets"") + parser.add_argument(""-top"", ""--top_final_primers"", default=""top_final_primers_sv.csv"", + help=""top primers generated for targets"") + parser.add_argument(""-plate"", ""--plate_basename"", default=""plated_primers"", + help=""the basename of the primers in plate format ready to order."") + +def fasta_parser(pcrfile): + """""" + Iterates through sudo-fasta output from in silico pcr + and extracts all useful info related to samples. + Args: + pcrfile (file): file output from in silico pcr of primers. + Returns: + seqs (list): list of seqs from pcr output + headers (list): list of headers from pcr output + """""" + seqs = [] + headers = [] + with open(pcrfile) as pcr_file: + sequence = """" + header = None + for line in pcr_file: + if line.startswith('>'): + headers.append(line[1:-1]) + if header: + seqs.append(sequence) + sequence = """" + header = line[1:] + else: + sequence += line.rstrip() + seqs.append(sequence) + return seqs, headers + +def amp_header_region(infile): + """""" + Extract relevant info from total_primer_list.csv to use for GC. + Args: + infile (file): total_list file to parse primer info + Returns: + header_start_stop (list): list of information to use when parsing fasta + """""" + primer_df = pd.read_csv(infile) + header_start_stop = [[header, start, stop] for header, start, stop\ + in zip(primer_df['Sequence ID'], + primer_df['Primer Left Pos'], + primer_df['Primer Right Pos'])] + return header_start_stop + +def get_gc_region(seqs, headers, positions): + """""" + Slice out the exact region of the fasta the primer amplified. + Args: + seqs (list): the list of sequences from flank_file + headers (list): the list of headers from flank_file + positions (list): list of tuples with header, p_len, p_seq + Returns: + sliced_seq (list): the exact amplified sequence. + """""" + sliced_seq = [] + for header, seq in zip(headers, seqs): + for pos in positions: + if pos[0] == header: + sliced_seq.append((header, len(seq[pos[1]:pos[2]+1]), seq[pos[1]:pos[2]+1])) + return sliced_seq + +def calc_gc(sliced_seq): + """""" + Takes sliced seq list with header, product len, and product seq and returns + the header, product len, and product GC%. A bit redundant but I might find + it useful to have this exact sequence in the future. + Args: + sliced_seq (list): contains (header, product_len, product_seq) + Returns: + sample_gc (list): contains (header, product_len, product GC%) + """""" + sample_gc = [] + for header, p_len, p_seq in sliced_seq: + sample_gc.append((header, p_len, seqinf.Sequence(p_seq).gc_percent())) + return sample_gc + +def merge_dfs(gc_calc, total_df, seqs): + """""" + Merges the product information onto the total primers sheet. + Args: + gc_calc (list): list containing header, product len, gc info + total_df (pandas object): dataframe containing primer information + Returns: + merged_df (pandas object): dataframe containing updated primer information + """""" + + gc = pd.DataFrame(gc_calc, columns=['Sequence Name', 'Product Len', 'Product GC%']) + total = pd.read_csv(total_df) + merged = pd.concat([total, gc], axis=1) # side-by-side merge + merged['Chromosome'] = [seqid.split(':')[0].split('_')[2] for seqid in merged['Sequence ID']] + merged['Position1'] = [seqid.split(':')[1].strip('_').split('-')[0] for seqid in merged['Sequence ID']] + merged['Position2'] = [seqid.split(':')[1].strip('_').strip('__BP1').strip('__BP2').\ + split('-')[1] for seqid in merged['Sequence ID']] + seqlen = [] + for seq in seqs: + seqlen.append(len(seq[:-1])) + flanksize = (seqlen[0]/2) + merged['FlankSize'] = int(flanksize) + merged['NucsBeforeBP'] = (merged['Position1']).apply(int)\ + - ((merged['Position1'].apply(int) - merged['FlankSize'])\ + + (merged['Primer Left Pos']).apply(int)) + merged['NucsAfterBP'] = merged['Product Len'].apply(int) -\ + (merged['FlankSize'] - merged['Primer Left Pos'].apply(int)) + merged['Position1'] = ((merged['Position1'].apply(int) - merged['FlankSize'])\ + + merged['Primer Left Pos'].apply(int)) + merged['Position2'] = (merged['Position2'].apply(int) + merged['NucsAfterBP'].apply(int)) + merged['FwdPrimPos'] = (merged['Position1']).apply(str) + '-'\ + + (merged['Position1'] + merged['Primer Left Len']).apply(str) + merged['RvsPrimPos'] = (merged['Position2'] - merged['Primer Right Len']).apply(str)\ + + '-' + (merged['Position2']).apply(str) + merged_df = merged[['Sequence ID', 'Primer Rank', 'Primer Left Seq', 'Primer Right Seq', + 'Primer Left Len', 'Primer Right Len', 'Primer Left TM', + 'Primer Right TM', 'Primer Left GC %', 'Primer Right GC %', + 'Product Len', 'Product GC%', 'Chromosome', 'Position1', 'Position2', + 'NucsBeforeBP', 'NucsAfterBP', 'FwdPrimPos', 'RvsPrimPos']] + return merged_df + +def to_order_plate(top_ranking_final_primers): + """""" + Takes output from top_ranked_final_primers and organizes to easy order plates + (Forward and Reverse). + Args: + top_ranked_final_primers (DataFrame): filtered, top ranked dataframe primers + Returns: + idt_order_sheet_plate_f (DataFrame): 96 well plate order format forward primers + idt_order_sheet_plate_r (DataFrame): 96 well plate order format reverse primers + """""" + # Generate well numbers + if len(top_ranking_final_primers) == 0: + sys.exit(""No primers were kept for any target. Try starting over with relaxed parameters."") + well_and_nums = [] + wells = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] + num_wells = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'] + for well in wells: + for num in num_wells: + well_and_nums.append(well+num) + + # this is required because sometimes more than 96 primers are generated and the list is consumed. + big_well_nums = well_and_nums * 50 + top_ranking_final_primers.set_index('Sequence ID', inplace=True) + plate_order_sheet_f = pd.DataFrame(columns=['Sequence Name', 'Sequence']) + plate_order_sheet_r = pd.DataFrame(columns=['Sequence Name', 'Sequence']) + names = top_ranking_final_primers.index.tolist() + f_seq = top_ranking_final_primers['Primer Left Seq'].tolist() + r_seq = top_ranking_final_primers['Primer Right Seq'].tolist() + plate_order_sheet_f['Sequence Name'] = names + plate_order_sheet_f['Sequence Name'] = plate_order_sheet_f['Sequence Name'] + '_F' + plate_order_sheet_f['Sequence'] = f_seq + plate_order_sheet_f.insert(0, 'Well Position', big_well_nums[:len(plate_order_sheet_f['Sequence'])]) + plate_order_sheet_r['Sequence Name'] = names + plate_order_sheet_r['Sequence Name'] = plate_order_sheet_r['Sequence Name'] + '_R' + plate_order_sheet_r['Sequence'] = r_seq + plate_order_sheet_r.insert(0, 'Well Position', big_well_nums[:len(plate_order_sheet_r['Sequence'])]) + return plate_order_sheet_f, plate_order_sheet_r + +","Python" +"In Silico","stjude/PrimerTK","src/primer_tk/analyze_pcr_output.py",".py","12204","290","#!/usr/bin/env python3 + +"""""" +Dependencies required to run program: + - python3.6+ + - pandas>=0.22.0 + - argparse + - sequence_info +A subset of functions used after PCR. +"""""" + +import argparse +import os +import sys +import pandas as pd +from primer_tk import sequence_info as seqinf + +def add_post_subparser(subparser): + """""" Add subparser for postprocessing step. + + Args: + subparser (?): Subparser object. + + Returns: None + """""" + parser = subparser.add_parser(""post"", help='Parses info from pcr_output') + parser.add_argument(""-i"", ""--pcr_output"", + dest=""pcrfile"", default=""pcr_output.txt"", + help=""use output of isPCR"") + + parser.add_argument(""-tp"", ""--total_primers"", + help=""the pre-PCR master primer file that\ + contains all sample + primer info."") + parser.add_argument(""-ot"", ""--off_target_max"", default=8, type=int, + help=""the maximum number of off target hits of primer."") + parser.add_argument(""-pcri"", ""--pcr_product_info"", default=""pcr_product_info.csv"", + help=""the information of all products generated by isPcr"") + parser.add_argument(""-all"", ""--all_primer_info"", default=""all_final_primers.csv"", + help=""all of the successful primers generated"") + parser.add_argument(""-top"", ""--top_final_primers"", default=""top_final_primers.csv"", + help=""the top primers generated for each position"") + parser.add_argument(""-plate"", ""--plate_basename"", default=""plated_primers"", + help=""the basename of the primers in plate format ready to order."") + + +def fasta_parser(pcrfile): + """""" + Iterates through sudo-fasta output from in silico pcr + and extracts all useful info related to samples. + Args: + pcrfile (file): file output from in silico pcr of primers. + Returns: + seqs (list): list of seqs from pcr output + headers (list): list of headers from pcr output + """""" + seqs = [] + headers = [] + if not os.path.exists(pcrfile): + sys.exit(""ERROR: pcr_file '%s' DNE""%(pcrfile)) + with open(pcrfile) as pcr_file: + sequence = """" + header = None + for line in pcr_file: + if line.startswith('>'): + headers.append(line[1:-1]) + if header: + seqs.append([sequence]) + sequence = """" + header = line[1:] + else: + sequence += line.rstrip() + seqs.append([sequence]) + return seqs, headers + +def gc_percent_seqs(seqs_list): + """""" + Use seqinf to calculate GC content for output from isPCR. + Args: + seqs_list (list): list of seqs output from isPCR + Returns: + gc_list (list): list of gc content of seqs. + """""" + upper_seqs = [[nuc.upper() for nuc in seq] for seq in seqs_list] + gc_list = [] + for seqs in upper_seqs: + for seq in seqs: + gc_list.append(seqinf.Sequence(seq).gc_percent()) + return gc_list + +def split_headers_list(headers): + """""" + Split the headers list into unique elements instead of 1 string. + Args: + headers (list): headers output from fasta_parser + Returns: + split_headers (list): headers list split into components. + no_chrom (list): all things that are not the chromosome. + """""" + split_headers = [item.split("" "") for item in headers] + no_chrom = [item[1:] for item in split_headers] + return split_headers, no_chrom + +def chr_split_list(split_headers): + """""" + Gets chromosome info from split_headers. + Args: + split_headers (list): header list split into parts + Returns: + chr_list (list): list of chromosome values + """""" + chr_list = [] + for item in split_headers: + if item[0]: + new_item = item[0].split("":"") + chr_list.append(new_item) + return chr_list + +def pos_split_list(chr_list): + """""" + Gets position info from chr_list. + Args: + chr_list (list): list of chr info with position + Returns: + pos_list (list): list with position info + """""" + pos_list = [] + for pos in chr_list: + if ""+"" in pos[1]: + for_pos = pos[1].split(""+"") + pos_list.append(for_pos) + if ""-"" in pos[1]: + rev_pos = pos[1].split(""-"") + pos_list.append(rev_pos) + return pos_list + + +def split_name_pos(no_chrom_list): + """""" + Splits the name and position in no_chrom_list. + Args: + no_chrom_list (list): list with header info not containing chromosome + Returns: + name_pos_split_list: split name and position list + """""" + name_pos_split_list = [] + for item in no_chrom_list: + new_split = item[0].replace(""_"", """").split("":"") + name_pos_split_list.append([new_split[1]]) + return name_pos_split_list + +def merge_info(chr_list, pos_split, name_pos_split_list, no_chrom_list): + """""" + Merges all lists created above to be used for DataFrame. + Args: + chr_list (list): the list with the chromosome info of product + pos_split_list (list): the list with the split positions + name_pos_split_list (list): the list with the names and positions split + no_chrom_list (list): the list without chrom info + Returns: + merged_list (list): list with all info to be taken into dataframe + """""" + merged_list = [] + for chrom, pos, name, prims in zip(chr_list, pos_split, name_pos_split_list, + no_chrom_list): + merged_items = chrom + pos + name + prims + merged_list.append(merged_items) + return merged_list + +def generate_pcr_df(merged_list, gc_list): + """""" + Generate a DataFrame from all the relevant merged_list information. + Args: + merged_list (list): list of all information about pcr products + Returns: + pcr_df (DataFrame): dataframe with all PCR product information + good_primers_df (DataFrame): dataframe with primers that are on target + bad_primers_df (DataFrame): dataframe with primers that failed + """""" + pcr_df = pd.DataFrame.from_records(merged_list) + pcr_df.columns = ['Chromosome', 'Position1', 'Position2', 'Sample_Pos', + 'Sequence ID', 'PCR_Prod_Len', 'Forward', 'Reverse'] + pcr_df['Product GC%'] = gc_list + pcr_df['ForwardPrimLen'] = [len(primer) for primer in pcr_df['Forward']] + pcr_df['ReversePrimLen'] = [len(primer) for primer in pcr_df['Reverse']] + pcr_df['Position1'] = pcr_df['Position1'].astype(int) + pcr_df['Position2'] = pcr_df['Position2'].astype(int) + pcr_df['Sample_Pos'] = pcr_df['Sample_Pos'].astype(int) + # Filter primers based on if they amplified in correct position + off_target_dict = {} + for fprim, pos1, pos2, sample_pos in zip(pcr_df['Forward'], pcr_df['Position1'], + pcr_df['Position2'], pcr_df['Sample_Pos']): + if fprim not in off_target_dict.keys() and (pos1 < sample_pos < pos2): + off_target_dict[fprim] = 0 + elif fprim not in off_target_dict.keys() and not (pos1 < sample_pos < pos2): + off_target_dict[fprim] = 1 + elif fprim in off_target_dict.keys() and not (pos1 < sample_pos < pos2): + off_target_dict[fprim] += 1 + pcr_df['OffTargetCount'] = pcr_df['Forward'].map(off_target_dict) + good_primers_df = pcr_df.loc[(pcr_df['Position1'] <= pcr_df['Sample_Pos']) & + (pcr_df['Sample_Pos'] <= pcr_df['Position2'])] + # These primers failed filtering + bad_primers_df = pcr_df.loc[~((pcr_df['Position1'] <= pcr_df['Sample_Pos']) & + (pcr_df['Sample_Pos'] <= pcr_df['Position2']))] + + return pcr_df, good_primers_df, bad_primers_df + +def merge_good_total(good_primers, total_primers): + """""" + Merges good primers and total primers on Sequence ID. + Picks highest ranking primers. + Args: + good_primers (file): dataframe generated by pcr analysis + total_primers (file): dataframe generated by Primer3 + Returns: + merged_df (DataFrame): good_total merged dataframe on Sequence ID + """""" + total_primers_df = pd.read_csv(total_primers) + merged_df = total_primers_df.merge(good_primers, on='Sequence ID', how='left') + merged_df['FwdPrimerPos'] = merged_df['Position1'].apply(str) + '-' +\ + (merged_df['Position1'] + merged_df['Primer Left Len']).apply(str) + merged_df['RvsPrimerPos'] = (merged_df['Position2'] - merged_df['Primer Right Len']).apply(str)\ + + '-' + merged_df['Position2'].apply(str) + return merged_df + +def filter_merged(merged_df, off_target_max): + """""" + Filters the merged df to find only primers which align with initial primer pairs, and have a value + below off target threshold. + Args: + merged_df (DataFrame): output df from merge_good_total() + off_target_max (int): the maximum number of off target sites allowed (<= this value) + Returns: + off_target_filtered (DataFrame): the filtered dataframe + """""" + filtered_df = merged_df.loc[(merged_df['Primer Left Seq'] == merged_df['Forward']) & + (merged_df['Primer Right Seq'] == merged_df['Reverse'])] + useful_filtered = filtered_df[['Sequence ID', 'Primer Rank', 'Primer Left Seq', + 'Primer Right Seq', 'Primer Left Len', 'Primer Right Len', + 'Primer Left TM', 'Primer Right TM', 'Primer Left GC %', + 'Primer Right GC %', 'Chromosome', 'Position1', + 'Position2', 'PCR_Prod_Len', + 'Product GC%', 'FwdPrimerPos', 'RvsPrimerPos', 'OffTargetCount']] + off_target_filtered = useful_filtered.loc[useful_filtered['OffTargetCount'] <= off_target_max] + return off_target_filtered + +def top_ranked_final_primers(filter_merged_df): + """""" + Drops duplicate sequence ids and keeps first (which also corresponds) + to the highest ranking primer pair for each sample. + Args: + filter_merged_df (DataFrame): input from filter_merged, where primers are only equal + to on target primers from initial primer generation. + Returns: + top_ranked_df (DataFrame): outputs only the highest scoring primer pair + at each position + """""" + top_ranked_df = filter_merged_df.drop_duplicates('Sequence ID', keep='first') + return top_ranked_df + +def to_order_plate(top_ranking_final_primers): + """""" + Takes output from top_ranked_final_primers and organizes to easy order IDT plates + (Forward and Reverse). + Args: + top_ranked_final_primers (DataFrame): filtered, top ranked dataframe primers + Returns: + idt_order_sheet_plate_f (DataFrame): 96 well plate order format forward primers + idt_order_sheet_plate_r (DataFrame): 96 well plate order format reverse primers + """""" + # Generate well numbers + well_and_nums = [] + wells = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'] + num_wells = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12'] + for well in wells: + for num in num_wells: + well_and_nums.append(well+num) + + # this is required because sometimes more than 96 primers are generated and the list is consumed. + big_well_nums = well_and_nums * 50 + filt_ranked_df = top_ranking_final_primers + plate_order_sheet_f = pd.DataFrame(columns=['Sequence Name', 'Sequence']) + plate_order_sheet_r = pd.DataFrame(columns=['Sequence Name', 'Sequence']) + plate_order_sheet_f['Sequence Name'] = filt_ranked_df['Sequence ID']+'_F' + plate_order_sheet_f['Sequence'] = filt_ranked_df['Primer Left Seq'] + plate_order_sheet_f.insert(0, 'Well Position', big_well_nums[:len(plate_order_sheet_f['Sequence'])]) + plate_order_sheet_r['Sequence Name'] = filt_ranked_df['Sequence ID']+'_R' + plate_order_sheet_r['Sequence'] = filt_ranked_df['Primer Right Seq'] + plate_order_sheet_r.insert(0, 'Well Position', big_well_nums[:len(plate_order_sheet_r['Sequence'])]) + return plate_order_sheet_f, plate_order_sheet_r +","Python" +"In Silico","stjude/PrimerTK","src/primer_tk/genome_iterator_sv.py",".py","27842","555","#!/usr/bin/env python +"""""" +Modules required to run program. +Dependencies: + - python3.6+ + - pandas>=0.22.0 + - numpy>=1.14.2 + - biopython>=1.70 + - argparse +"""""" + +import sys +import argparse + +from Bio import SeqIO +import pandas as pd +from primer_tk import sequence_info as seqinf + +def add_iterator_subparser(subparser): + """""" Get commandline arguments + Args: + subparser (?): Argparse subparsers + + Returns: None + """""" + + parser = subparser.add_parser(""iterator_sv"", help=""iterator_sv subparser"") + + parser.add_argument(""-ref"", ""--ref_genome"", required=True, + help=""Reference Genome File to design primers around"") + parser.add_argument(""-in"", ""--regions_file"", required=True, + help=""File with regions to design primers around"") + parser.add_argument(""-opt_size"", ""--primer_opt_size"", + dest=""primer_opt_size"", default=""22"", + help=""The optimum primer size for output, default: 22"") + parser.add_argument(""-min_size"", ""--primer_min_size"", + dest=""primer_min_size"", default=""18"", + help=""The optimum primer size for output, default: 18"") + parser.add_argument(""-max_size"", ""--primer_max_size"", + dest=""primer_max_size"", default=""25"", + help=""The optimum primer size for output, default: 25"") + parser.add_argument(""-opt_gc"", ""--primer_opt_gc"", + dest=""primer_opt_gc"", default=""50"", + help=""Optimum primer GC, default: 50"") + parser.add_argument(""-min_gc"", ""--primer_min_gc"", + dest=""primer_min_gc"", default=""20"", + help=""Minimum primer GC, default: 20"") + parser.add_argument(""-max_gc"", ""--primer_max_gc"", + dest=""primer_max_gc"", default=""80"", + help=""Maximum primer GC, default: 80"") + parser.add_argument(""-opt_tm"", ""--primer_opt_tm"", + dest=""primer_opt_tm"", default=""60"", + help=""Optimum primer TM, default: 60"") + parser.add_argument(""-min_tm"", ""--primer_min_tm"", + dest=""primer_min_tm"", default=""57"", + help=""minimum primer TM, default: 57"") + parser.add_argument(""-max_tm"", ""--primer_max_tm"", + dest=""primer_max_tm"", default=""63"", + help=""maximum primer TM, default: 63"") + parser.add_argument(""-sr"", ""--product_size_range"", + dest=""product_size_range"", default=""200-400"", + help=""Size Range for PCR Product, default=200-400"") + parser.add_argument(""-flank"", ""--flanking_region_size"", + dest=""flanking_region_size"", default=""200"", + help=""This value will select how many bases up and downstream to count\ + when flanking SNP (will do 200 up and 200 down), default: 200"") + parser.add_argument(""-st"", ""--sequence_target"", + dest=""sequence_target"", default=""199,1"", + help=""default: 199,1, should be half of your flanking region size,\ + so SNP/V will be included."") + parser.add_argument(""-mp"", ""--mispriming"", dest=""mispriming"", required=True, + help=""full path to mispriming library for primer3\ + (EX: /home/dkennetz/mispriming/humrep.ref"") + parser.add_argument(""-tp"", ""--thermopath"", dest=""thermopath"", required=True, + help=""full path to thermo parameters for primer3 to use\ + (EX: /home/dkennetz/primer3/src/primer3_config/) install loc"") + parser.add_argument(""-sv"", ""--sv-type"", dest=""sv"", + choices=['deletion', 'inversion', 'insertion', 'translocation'], required=True, + help=""currently supported SV primer generation: "" + ""deletion, inversion, insertion and translocation."") + +def genome_iterator(genome): + """""" + Uses Biopython SeqIO to parse a genome Fasta and store each chr and + sequence as a list. + + Args: + genome (file): Full reference genome from command-line arguments. + + Returns: + output (list): genome parsed into list of tuples of (header, seq) + by chromosome for easy access later. + """""" + + output = [] + with open(genome, ""r"") as handle: + for record in SeqIO.parse(handle, ""fasta""): + chrm = record.id + seq = record.seq + output.append((chrm, seq)) + return output + +def create_dataframe_csv(regions_file): + """""" + Creates a pandas DataFrame from a regions file in comma separated form + and names the columns in the DF according to their values. + + Args: + regions_file (file): Full path to -in input regions.csv. + This should have coordinate positions of interest to design primers around. + Note: the chromosome column can be of format chr1 or simply 1 (chr not necessary). + The file should contain no headers and should be structured as follows: + + Gene1,Sample1,chr1,pos1,pos2 + Gene2,Sample2,chr2,pos1,pos2 + Gene3,Sample3,chr3,pos1,pos2 + ... + Returns: + regions_df (pd.DataFrame): The infile parsed to pd.DataFrame object. + """""" + + regions_df = pd.read_csv(regions_file, header=None) + regions_df.columns = ['Gene', 'Sample', 'Chr', 'PosStart', 'PosStop'] + regions_df = regions_df.astype({'Chr': str}) + return regions_df + +def create_dataframe_insertion_csv(regions_file): + """""" + Creates a pandas DataFrame from a regions file in comma separated form + and names the columns in the DF according to their values. + + Args: + regions_file (file): Full path to -in input regions.csv. + This should have coordinate positions of interest to design primers around. + Note: the chromosome column can be of format chr1 or simply 1 (chr not necessary). + The file should contain no headers and should be structured as follows: + + Gene1,Sample1,chrNorm1,posNorm1,posNorm2,strand,chrIns2,posIns1,posIns2,strand + Gene2,Sample2,chrNorm2,posNorm1,posNorm2,strand,chrIns3,posIns1,posIns2,strand + Gene3,Sample3,chrNorm3,posNorm1,posNorm2,strand,chrIns4,posIns1,posIns2,strand + ... + Returns: + regions_df (pd.DataFrame): The infile parsed to pd.DataFrame object. + """""" + + regions_df = pd.read_csv(regions_file, header=None) + regions_df.columns = ['Gene', 'Sample', 'ChrNorm', 'PosNorm1', 'PosNorm2', 'StrandN', + 'ChrIns', 'PosIns1', 'PosIns2', 'StrandI'] + regions_df = regions_df.astype({'ChrNorm': str}) + regions_df = regions_df.astype({'ChrIns': str}) + return regions_df + +def create_dataframe_translocation_csv(regions_file): + """""" + Creates a pandas DataFrame from a regions file in csv form + and uses column names in df according tot heir values. + + Args: + regions_file (file): input regions.csv file. + Note: the chromosome column can be of format chr1 or simply 1 (chr not necessary). + The file should contain no headers and should be constructed as follows: + + Gene1,Sample1,chrNorm,posNorm,strand,chrTrans,posTrans,strand + Gene2,Sample2,chrNorm,posNorm,strand,chrTrans,posTrans,strand + Gene3,Sample3,chrNorm,posNorm,strand,chrTrans,posTrans,strand + ... + Returns: + regions_df (pd.DataFrame): the infile parsed to pd.DataFrame object. + """""" + regions_df = pd.read_csv(regions_file, header=None) + regions_df.columns = ['Gene', 'Sample', 'ChrNorm', 'PosNorm', 'StrandN', + 'ChrTrans', 'PosTrans', 'StrandT'] + regions_df = regions_df.astype({'ChrNorm': str}) + regions_df = regions_df.astype({'ChrTrans': str}) + return regions_df + +def create_dataframe_txt(regions_file): + """""" + Creates a pandas DataFrame from a regions file in a tab separated form + and uses the following column names in the DF according to their values. + + Args: + regions_file (file): Full path to -in input regions.txt. + This should have coordinate positions of interest to design primers around. + Note: the chromosome column can be of format chr1 or simply 1 (chr not necessary). + The file should contain no headers and should be constructed as follows: + + Gene1\tSample1\tchr1\tpos1\tpos2 + Gene2\tSample2\tchr2\tpos1\tpos2 + Gene3\tSample3\tchr3\tpos1\tpos2 + ... + Returns: + regions_df (pd.DataFrame): The infile parsed to pd.DataFrame object. + """""" + regions_df = pd.read_csv(regions_file, sep='\t', header=None) + regions_df.columns = ['Gene', 'Sample', 'Chr', 'PosStart', 'PosStop'] + regions_df = regions_df.astype({'Chr': str}) + return regions_df + +def create_dataframe_insertion_txt(regions_file): + """""" + Creates a pandas DataFrame from a regions file in a tab separated form + and uses the following column names in the DF according to their values. + + Args: + regions_file (file): Full path to -in input regions.txt. + This should have coordinate positions of interest to design primers around. + Note: the chromosome column can be of format chr1 or simply 1 (chr not necessary). + The file should contain no headers and should be constructed as follows: + + Gene1\tSample1\tchrNorm1\tposNorm1\tposNorm2\tstrand\tchrIns2\tposIns1\tposIns2\tstrand + Gene2\tSample2\tchrNorm2\tposNorm1\tposNorm2\tstrand\tchrIns3\tposIns1\tposIns2\tstrand + Gene3\tSample3\tchrNorm3\tposNorm1\tposNorm2\tstrand\tchrIns4\tposIns1\tposIns2\tstrand + ... + Returns: + regions_df (pd.DataFrame): The infile parsed to pd.DataFrame object. + """""" + regions_df = pd.read_csv(regions_file, sep='\t', header=None) + regions_df.columns = ['Gene', 'Sample', 'ChrNorm', 'PosNorm1', 'PosNorm2', 'StrandN', + 'ChrIns', 'PosIns1', 'PosIns2', 'StrandI'] + regions_df = regions_df.astype({'ChrNorm': str}) + regions_df = regions_df.astype({'ChrIns': str}) + return regions_df + +def create_dataframe_translocation_txt(regions_file): + """""" + Creates a pandas DataFrame from a regions file in txt form + and uses column names in df according tot heir values. + + Args: + regions_file (file): input regions.csv file. + Note: the chromosome column can be of format chr1 or simply 1 (chr not necessary). + The file should contain no headers and should be constructed as follows: + + Gene1\tSample1\tchrNorm\tposNorm\tstrand\tchrTrans\tposTrans\tstrand + Gene2\tSample2\tchrNorm\tposNorm\tstrand\tchrTrans\tposTrans\tstrand + Gene3\tSample3\tchrNorm\tposNorm\tstrand\tchrTrans\tposTrans\tstrand + ... + Returns: + regions_df (pd.DataFrame): the infile parsed to pd.DataFrame object. + """""" + regions_df = pd.read_csv(regions_file, sep='\t', header=None) + regions_df.columns = ['Gene', 'Sample', 'ChrNorm', 'PosNorm', 'StrandN', + 'ChrTrans', 'PosTrans', 'StrandT'] + regions_df = regions_df.astype({'ChrNorm': str}) + regions_df = regions_df.astype({'ChrTrans': str}) + return regions_df + +def file_extension(infile, strvar): + """""" + Runs pd.read_ function to create dataframe corresponding + to file extension, .txt and .csv accepted. + This will call the function to create a df only if file extension is correct. + If the file extension is wrong, it will return the error message and exit. + + Args: + infile (file): Full path to -in input regions.txt. + strvar (string): the structural variant type + Returns: + small_regions (pd.DataFrame): The infile parsed to pd.DataFrame object + """""" + if infile.lower().endswith('.txt') and strvar in ('deletion', 'inversion'): + small_regions = create_dataframe_txt(infile) + elif infile.lower().endswith('.csv') and strvar in ('deletion', 'inversion'): + small_regions = create_dataframe_csv(infile) + elif infile.lower().endswith('.txt') and strvar == 'insertion': + small_regions = create_dataframe_insertion_txt(infile) + elif infile.lower().endswith('.csv') and strvar == 'insertion': + small_regions = create_dataframe_insertion_csv(infile) + elif infile.lower().endswith('.csv') and strvar == 'translocation': + small_regions = create_dataframe_translocation_csv(infile) + elif infile.lower().endswith('.txt') and strvar == 'translocation': + small_regions = create_dataframe_translocation_txt(infile) + else: + sys.exit(""Wrong File Format, should be .txt (tab) or .csv (comma), or check sv type."") + return small_regions + +def match_chr_to_genome(dataframe, genome, strvar): + """""" + Used to match formatting between regionsFile input and genome for chromosome + denotations. Some genomes contain the string ""chr"" and some do not. + + Args: + dataframe (pandas object): dataframe created from create_dataframe() function. + genome (list): genome list of tuples created from genome_iterator() function. + + Returns: + dataframe (pandas object): dataframe formatted to match genome annotation of chromosome. + """""" + if strvar in ('deletion', 'inversion'): + if dataframe['Chr'].str.contains(""chr"").any() and ""chr"" not in str(genome[0][0]): + dataframe['Chr'] = dataframe['Chr'].str.replace('chr', '') + elif not dataframe['Chr'].str.contains(""chr"").any() and ""chr"" in str(genome[0][0]): + dataframe['Chr'] = 'chr' + dataframe['Chr'] + elif strvar == 'insertion': + if dataframe['ChrNorm'].str.contains(""chr"").any() and ""chr"" not in str(genome[0][0]): + dataframe['ChrNorm'] = dataframe['ChrNorm'].str.replace('chr', '') + dataframe['ChrIns'] = dataframe['ChrIns'].str.replace('chr', '') + elif not dataframe['ChrNorm'].str.contains(""chr"").any() and ""chr"" in str(genome[0][0]): + dataframe['ChrNorm'] = 'chr' + dataframe['ChrNorm'] + dataframe['ChrIns'] = 'chr' + dataframe['ChrIns'] + elif strvar == 'translocation': + if dataframe['ChrNorm'].str.contains(""chr"").any() and ""chr"" not in str(genome[0][0]): + dataframe['ChrNorm'] = dataframe['ChrNorm'].str.replace('chr', '') + dataframe['ChrTrans'] = dataframe['ChrTrans'].str.replace('chr', '') + elif not dataframe['ChrNorm'].str.contains(""chr"").any() and ""chr"" in str(genome[0][0]): + dataframe['ChrNorm'] = 'chr' + dataframe['ChrNorm'] + dataframe['ChrTrans'] = 'chr' + dataframe['ChrIns'] + else: + sys.exit(""Wrong SV type, please select an SV in help menu."") + return dataframe + +def flanking_regions_fasta_deletion(genome, dataframe, flanking_region_size): + """""" + Makes batch processing possible, pulls down small region + of genome for which to design primers around. + This is based on the chromosome and position of input file. + Each Fasta record will contain: + + >Sample_Gene_chr:posStart-posStop + Seq of flanking region upstream of SV + seq of flanking region downstream of SV + + Args: + genome (list): genome list of tuples (header, seq). + dataframe (pandas object): dataframe with sample info. + flanking_region_size (int): length of sequence upstream and downstream of + input coordinate position to pull as sequence to design primers around. + """""" + output = [] + for headers, seqs in genome: + chrm = str(headers) + seq = str(seqs) + for gene, sample, chrom, start, stop in zip(dataframe.Gene, dataframe.Sample, dataframe.Chr, + dataframe.PosStart, dataframe.PosStop): + if str(chrom) == chrm: + header = str(str(sample)+""_""+str(gene)+""_""+\ + str(chrom)+"":""+str(start)+""-""+str(stop)+""__"") + flank_seq = seq[int(start)-int(flanking_region_size):int(start)+1]\ + +seq[int(stop):(int(stop)+int(flanking_region_size))] + output.append((header, flank_seq.upper())) + return output + +def flanking_regions_fasta_inversion(genome, dataframe, flanking_region_size): + """""" + Makes batch processing possible, pulls down small region + of genome for which to design primers around and generates + flanking regions based on an inverted sequence. + + This is based on the chromosome and position of input file. + Each Fasta record will contain: + + >Sample_Gene_chr:posStart-posStop_BP + Seq of flanking region upstream of SV + seq of flanking region downstream of SV + + Args: + genome (list): genome list of tuples (header, seq). + dataframe (pandas object): dataframe with sample info. + flanking_region_size (int): length of sequence upstream and downstream of + input coordinate position to pull as sequence to design primers around. + Returns: + output (list): header + seq + """""" + output = [] + for headers, seqs in genome: + chrm = str(headers) + seq = str(seqs) + for gene, sample, chrom, start, stop in zip(dataframe.Gene, dataframe.Sample, dataframe.Chr, + dataframe.PosStart, dataframe.PosStop): + if str(chrom) == chrm: + header = str(str(sample)+""_""+str(gene)+""_""+\ + str(chrom)+"":""+str(start)+""-""+str(stop)+""__BP1"") + flank_seq = seq[int(start)-int(flanking_region_size):int(start)+1]\ + + seqinf.\ + Sequence(seq[int(stop):((int(stop)-(int(flanking_region_size)+1))):-1])\ + .complement() + output.append((header, flank_seq)) + for gene, sample, chrom, start, stop in zip(dataframe.Gene, dataframe.Sample, dataframe.Chr, + dataframe.PosStart, dataframe.PosStop): + if str(chrom) == chrm: + header = str(str(sample)+""_""+str(gene)+""_""+\ + str(chrom)+"":""+str(start)+""-""+str(stop)+""__BP2"") + flank_seq = seqinf.\ + Sequence(seq[int(start)+int(flanking_region_size):int(start)+1:-1])\ + .complement()\ + + seq[int(stop):(int(stop)+int(flanking_region_size))] + output.append((header, flank_seq.upper())) + return output + +def flanking_region_fasta_translocation(genome, dataframe, flanking_region_size): + """""" + Pulls down small region of genome for which to design primers around and + generates flanking regions based on strand info from input file. + + Each Fasta record will contain: + >Sample_Gene_chrNorm:posNorm-posTrans + Seq of flanking region upstream of posNorm + seq after posTrans based on strand + + Args: + genome (list): genome list of tuples (header, seq) + dataframe (pd.DataFrame): dataframe with sample info. + flanking_region_size (int): length of sequence to pad position with. + Returns: + result (dict): {header: seq} + """""" + output = [] + samp_norm = {} + samp_tran = {} + for headers, seqs in genome: + chrm = str(headers) + seq = str(seqs) + for gene, sample, chrn, posn, strandn, chrt, post, strandt in zip(dataframe.Gene, dataframe.Sample, + dataframe.ChrNorm, dataframe.PosNorm, + dataframe.StrandN, dataframe.ChrTrans, + dataframe.PosTrans, dataframe.StrandT): + if str(chrn) == chrm and strandn == '+': + header = str(str(sample)+""_""+str(gene)+""_""+str(chrn)+"":""+str(posn)+""-""+str(post)) + flank_seq = seq[int(posn):int(posn)+int(flanking_region_size)] + samp_norm[header] = flank_seq + elif str(chrn) == chrm and strandn == '-': + header = str(str(sample)+""_""+str(gene)+""_""+str(chrn)+"":""+str(posn)+""-""+str(post)) + flank_seq = seqinf.Sequence(seq[int(posn):int(posn)-(int(flanking_region_size)):-1])\ + .complement() + samp_norm[header] = flank_seq + + for gene, sample, chrn, posn, strandn, chrt, post, strandt in zip(dataframe.Gene, dataframe.Sample, + dataframe.ChrNorm, dataframe.PosNorm, + dataframe.StrandN, dataframe.ChrTrans, + dataframe.PosTrans, dataframe.StrandT): + if str(chrt) == chrm and strandt == '+': + header = str(str(sample)+""_""+str(gene)+""_""+str(chrn)+"":""+str(posn)+""-""+str(post)) + flank_seq = seq[int(post)-int(flanking_region_size):int(post)] + samp_tran[header] = flank_seq + elif str(chrt) == chrm and strandt == '-': + header = str(str(sample)+""_""+str(gene)+""_""+str(chrn)+"":""+str(posn)+""-""+str(post)) + flank_seq = seqinf.Sequence(seq[int(post)+int(flanking_region_size):int(post):-1])\ + .complement() + samp_tran[header] = flank_seq + + result = {} + for name1, seq1 in samp_norm.items(): + for name2, seq2 in samp_tran.items(): + if name1 == name2: + outseq = seq2+seq1 + result[name1] = outseq + + return result + +def flanking_region_fasta_insertion(genome, dataframe, flanking_region_size): + """""" + Makes batch processing possible, pulls down small region + of genome for which to design primers around and generates + flanking regions based on an inverted sequence. + + This is based on the chromosome and position of input file. + Each Fasta record will contain: + + Note: If strand is negative, coordinates should be in decreasing order. + + >Sample_Gene_chr:posNorm1-posNorm2_BP + Seq of flanking region upstream of SV + seq of inserted sequence based on strand + + Args: + genome (list): genome list of tuples (header, seq) + dataframe (pandas object): dataframe with sample info. + flanking_region_size (int): length of sequence upstream dna downstream of + input coordinate position to pull as sequence to design primers around. + Returns: + result (dict): {header: seq} + """""" + seqsnormbp1 = {} + seqsinsbp1 = {} + seqsnormbp2 = {} + seqsinsbp2 = {} + for headers, seqs in genome: + chrm = str(headers) + seq = str(seqs) + for gene, sample, chrn, startn, stopn, strandn, stopi in zip(dataframe.Gene, dataframe.Sample, + dataframe.ChrNorm, dataframe.PosNorm1, + dataframe.PosNorm2, dataframe.StrandN, + dataframe.PosIns2): + if str(chrn) == chrm and strandn == '+': + header = str(str(sample)+""_""+str(gene)+""_""+str(chrn)+"":""+\ + str(startn)+""-""+str(stopi)+""__BP1"") + flank_seq = seq[int(startn):int(startn)+int(flanking_region_size)] + seqsnormbp1[header] = flank_seq + elif str(chrn) == chrm and strandn == '-': + header = str(str(sample)+""_""+str(gene)+""_""+str(chrn)+"":""+\ + str(startn)+""-""+str(stopi)+""__BP1"") + flank_seq = seqinf.Sequence(seq[int(startn):int(startn)-(int(flanking_region_size)):-1])\ + .complement() + seqsnormbp1[header] = flank_seq + + for gene, sample, chrn, startn, chri, starti, stopi, strandi in zip(dataframe.Gene, dataframe.Sample, + dataframe.ChrNorm, dataframe.PosNorm1, + dataframe.ChrIns, dataframe.PosIns1, + dataframe.PosIns2, dataframe.StrandI): + if str(chri) == chrm and strandi == '+': + header = str(str(sample)+""_""+str(gene)+""_""+str(chrn)+"":""+\ + str(startn)+""-""+str(stopi)+""__BP1"") + flank_seq = seq[int(starti)-int(flanking_region_size):int(starti)] + seqsinsbp1[header] = flank_seq + elif str(chri) == chrm and strandi == '-': + header = str(str(sample)+""_""+str(gene)+""_""+str(chrn)+"":""+\ + str(startn)+""-""+str(stopi)+""__BP1"") + flank_seq = seqinf.Sequence(seq[int(starti)+int(flanking_region_size):int(starti):-1])\ + .complement() + seqsinsbp1[header] = flank_seq + for gene, sample, chrn, startn, stopn, strandn, stopi in zip(dataframe.Gene, dataframe.Sample, + dataframe.ChrNorm, + dataframe.PosNorm1, + dataframe.PosNorm2, dataframe.StrandN, + dataframe.PosIns2): + if str(chrn) == chrm and strandn == '+': + header = str(str(sample)+""_""+str(gene)+""_""+str(chrn)+"":""+\ + str(startn)+""-""+str(stopi)+""__BP2"") + flank_seq = seq[int(stopn)-int(flanking_region_size):int(stopn)] + seqsnormbp2[header] = flank_seq + elif str(chrn) == chrm and strandn == '-': + header = str(str(sample)+""_""+str(gene)+""_""+str(chrn)+"":""+\ + str(startn)+""-""+str(stopi)+""__BP2"") + flank_seq = seqinf.Sequence(seq[int(stopn)+int(flanking_region_size):int(stopn):-1])\ + .complement() + seqsnormbp2[header] = flank_seq + + for gene, sample, chrn, startn, chri, starti, stopi, strandi in zip(dataframe.Gene, dataframe.Sample, + dataframe.ChrNorm, dataframe.PosNorm1, + dataframe.ChrIns, dataframe.PosIns1, + dataframe.PosIns2, dataframe.StrandI): + if str(chri) == chrm and strandi == '+': + header = str(str(sample)+""_""+str(gene)+""_""+str(chrn)+"":""+\ + str(startn)+""-""+str(stopi)+""__BP2"") + flank_seq = seq[int(stopi):int(stopi)+(int(flanking_region_size))] + seqsinsbp2[header] = flank_seq + elif str(chri) == chrm and strandi == '-': + header = str(str(sample)+""_""+str(gene)+""_""+str(chrn)+"":""+\ + str(startn)+""-""+str(stopi)+""__BP2"") + flank_seq = seqinf.\ + Sequence(seq[int(stopi):int(stopi)-int(flanking_region_size):-1])\ + .complement() + seqsinsbp2[header] = flank_seq + + result = {} + for name1, seq1 in seqsnormbp1.items(): + for name2, seq2 in seqsinsbp1.items(): + if name1 == name2: + outseq = seq2+seq1 + result[name1] = outseq + + for name1, seq1 in seqsnormbp2.items(): + for name2, seq2 in seqsinsbp2.items(): + if name1 == name2: + outseq = seq1+seq2 + result[name1] = outseq + return result +","Python" +"In Silico","stjude/PrimerTK","src/primer_tk/__init__.py",".py","46","4","#!/usr/bin/env python3 + +__version__ = ""1.0.0"" +","Python" +"In Silico","stjude/PrimerTK","src/primer_tk/constants.py",".py","30","3","START_POS=10000 +END_POS=11000 +","Python" +"In Silico","stjude/PrimerTK","src/primer_tk/primer_cross_hyb.py",".py","8729","196","#!/usr/bin/env python3 +"""""" +Modules required for program. + - python3.6+ + - pandas>=0.22.0 + - argparse + - sequence_info +"""""" + +import argparse +from primer_tk import sequence_info as seqinf + +def add_pre_subparser(subparser): + """""" Add subparser for 'pre' step. + + Args: + subparser (?): Subparser object. + + Returns: None + """""" + parser = subparser.add_parser(""pre"", help=""Preprocessing for snv/indel"", + description=""Command Line argument for total primer"" + ""input file to check if primers have a degree"" + ""of complementarity with each other as defined"" + ""by the user. Default is 60% (fairly strict)."") + + parser.add_argument(""-d"", ""--primer3_dump"", dest=""dump"", required=True, + help=""Primer3 stdout passed into a 'dump' file to be used as input"") + + parser.add_argument(""-o"", ""--outfile_name"", dest=""outfile"", required=True, + help=""The output filename for all primer information."") + parser.add_argument(""-nd"", ""--no_dimer"", default=""no_dimer_df.csv"", + help=""The primers left after dimers removed."") + parser.add_argument(""-spcr"", ""--standard_pcr_file"", default=""standard_pcr.txt"", + help=""The file to be used for standard pcr input"") + parser.add_argument(""-mpcr"", ""--multiplex_pcr_file"", default=""multiplex_pcr.txt"", + help=""The file to be used for multiplex pcr input"") + parser.add_argument(""-pa"", ""--percent_alignment"", dest=""percent_alignment"", + default=""60"", help=""Percent match between 2 primers for pair to be\ + discarded. EX: primer_len = 22, percent_aln = 60\ + dimer_len = (60/100) * 22 = 13.2 -> 13."") + parser.add_argument(""-pcr"", ""--pcr_type"", dest=""pcr"", required=True, + choices=['standard', 'multiplex'], + help=""perform standard or multiplex pcr on given inputs."") + +def add_pre_sv_subparser(subparser): + """""" Add subparser for 'pre' step. + + Args: + subparser (?): Subparser object. + + Returns: None + """""" + parser = subparser.add_parser(""pre_sv"", help=""Preprocessing for SV's"") + + parser.add_argument(""-d"", ""--primer3_dump"", dest=""dump"", required=True, + help=""Primer3 stdout passed into a 'dump' file to be used as input"") + + parser.add_argument(""-o"", ""--outfile_name"", dest=""outfile"", required=True, + help=""The output filename for all primer information."") + parser.add_argument(""-pcr"", ""--pcrfile"", default=""standard_pcr.txt"", + help=""The pseudopcr file"") + +def get_fprimer_percent_aln(fprimer, percent_alignment): + """""" + Gets the len of the fprimer and calculates minimum percent alignment + based on user input of maximum alignment between 2 primers allowed. + See percent alignment help for info. + Args: + fprimer (str): the forward primer + Returns: + fp_len (int): user defined total number of bases to allowed to match. + """""" + fp_len = [] + for fseq in fprimer: + f_len = len(fseq) + min_dimer_alignment = int(f_len*(percent_alignment/100)) + fp_len.append(min_dimer_alignment) + return fp_len + +def primer_dimer_local(aln_len_list, names, seq1, seq2): + """""" + Looks for complementarity between all primers in list, + and returns alignment + score. No return, prints visualization + between aligned primers (forming dimer) if they meet the min score set in the func. + Args: + min_dimer_alignment (int): the minimum alignment score between 2 primers before + it is thrown out + names (string): sequence ID + seq1 (string): primer1 sequence + seq2 (string): primer2 sequence + Returns: + name, seq1, seq2, score (generator): yields any primer pair that has score + greater than or equal to min_dimer_alignment. + """""" + for name, fseq, aln_len in zip(names, seq1, aln_len_list): + for rseq in seq2: + pd_test = seqinf.PrimerDimer(fseq, seqinf.Sequence(rseq).complement(), aln_len) + pd_output = pd_test.pd_local() + for item in pd_output: + yield(name+""\n"", seqinf.PrimerDimer.format_alignment_compl(item[0], + item[1], + item[2], + item[3], + item[4])) + +def list_from_gen(gen_expression): + """""" + Creates a list from the generator function for dimer alignment. + Items in each_item are name, seq1, seq2, score. + Args: + gen_expression (generator object): the output from primer_dimer_local + Returns: + primer_compare_list (list): generaor converted to list + """""" + primer_compare_list = [] + for each_item in gen_expression: + primer_compare_list.append(str(each_item)) + return primer_compare_list + +def p_list_formatter(primer_list): + """""" + Reformat the primer list (remove unnecessary characters from biopython2 output). + Args: + primer_list (list): list from list_from_gen output + Returns: + primer_dimers (list): list with unnecessary chars removed. + """""" + reformat_p_list = [] + primer_dimers = [] + reformat_p_list = [each_item.replace('\\n', ' ').split() for each_item in primer_list] + for each_item in reformat_p_list: + primer_dimers.append((each_item[0].replace('(', '').replace('\'', ''), + each_item[2].replace('\'', ''), each_item[4], + each_item[5].replace('\')', ''))) + return primer_dimers + +def dimer_true(dataframe, col_num, dimer_list): + """""" + Boolean masks to let us know which primers from original df + form dimers. If so they are dropped. + Args: + dataframe (pd.DataFrame): the primer dataframe + col_num (int): the column number to check for primer match + dimer_list (list): the list containing primer dimer info + Returns: + out_series (pd.Series): boolean masked series, True if primer is dimer, else False + """""" + out_series = dataframe.iloc[:, col_num].isin([seq[1] or seq[2] for seq in dimer_list]) + return out_series + +def all_vs_all_pcr(df_boolean, outfile): + """""" + Creates all vs all pcr input to check for off target PCR amplification. + This function assumes you used the output created from primer_cross_hyb.py + Args: + df_boolean (pd.DataFrame): dataframe with removed cross hybridizing primers + Returns: + nothing: writes a file output + """""" + no_dimer_df = df_boolean + all_vs_all = open(outfile, 'w') + for seqid, primer_left in zip(no_dimer_df['Sequence ID'], no_dimer_df['Primer Left Seq']): + for primer_right in no_dimer_df['Primer Right Seq']: + all_vs_all.write(str(seqid) + '\t' + str(primer_left) + '\t' + str(primer_right) + '\n') + + for seqid, primer_right in zip(no_dimer_df['Sequence ID'], no_dimer_df['Primer Right Seq']): + for primer_left in no_dimer_df['Primer Left Seq']: + all_vs_all.write(str(seqid) + '\t' + str(primer_right) + '\t' + str(primer_left) + '\n') + + for seqid, primer_left in zip(no_dimer_df['Sequence ID'], no_dimer_df['Primer Left Seq']): + for primer_left2 in no_dimer_df['Primer Left Seq']: + all_vs_all.write(str(seqid) + '\t' + str(primer_left) + '\t' + str(primer_left2) + '\n') + + for seqid, primer_right in zip(no_dimer_df['Sequence ID'], no_dimer_df['Primer Right Seq']): + for primer_right2 in no_dimer_df['Primer Right Seq']: + all_vs_all.write(str(seqid) + '\t' + str(primer_right) +\ + '\t' + str(primer_right2) + '\n') + + all_vs_all.close() + +def standard_pcr(primer_df, outfile): + """""" + Creates standard PCR input file (one primer with one other) to run in silico PCR. + Args: + primer_df (pd.DataFrame): dataframe with primer info + Returns: + nothing: writes a file output + """""" + standard = open(outfile, 'w') + for seqid, primer_left, primer_right in zip(primer_df['Sequence ID'], + primer_df['Primer Left Seq'], + primer_df['Primer Right Seq']): + standard.write(str(seqid) + '\t' + str(primer_left) + '\t' + str(primer_right) + '\n') + standard.close() +","Python" +"In Silico","stjude/PrimerTK","src/primer_tk/primer_tabix.py",".py","8074","209","#!/usr/bin/env python3 + +"""""" +Dependencies required to run program. + - python3.6+ + - argparse + - pandas >= 0.22.4 + - pysam==0.15.2 +"""""" + +import sys +import pandas as pd +from primer_tk import constants + +def add_tabix_subparser(subparser): + """""" + Get commandline arguments + Args: + subparser (?): Subparser object. + Returns: + args (Namespace): the parsed arguments. + """""" + parser = subparser.add_parser(""tabix"", help=""Tabix subparser"") + parser.add_argument(""-vcf"", ""--variant-call-file"", dest=""vcf"", + help=""Tabix indexed VCF."") + parser.add_argument(""-in"", ""--primer-input-file"", dest=""p_info"", + help=""The output of the primer pipeline."") + parser.add_argument(""-o"", ""--output"", dest=""output"", + help=""The name of the output file"") + return parser + +def create_tabix_df(primer_pipeline_output): + """""" + Takes output of primer pipeline and generates dataframe. + + Args: + total_primers (file): the output of the primer pipeline + Returns: + dataframe (pd.DataFrame): a pandas dataframe + """""" + primer_df = pd.read_csv(primer_pipeline_output, header=0) + return primer_df + +def primer_range_left(seqid, rank, chrm, p_left, position1): + """""" + Takes the chromosome, primer sequence, and position and creates a + query range for tabix to search by. + + Args: + seqid (pd.Series): pandas column containing seqids + rank (pd.Series): pandas column containing primer rank + chrm (pd.Series): pandas column of chrm info + p_left (pd.Series): pandas column of the left primer seq + position1 (pd.Series): pandas column of the left primer position. + Returns: + p_left_info (pd.DataFrame): the positional info in a frame format. + """""" + p_left_info = pd.DataFrame() + p_left_info['Sequence ID'] = seqid + p_left_info['Primer Rank'] = rank + p_left_info['Chromosome'] = chrm.apply(str) + p_left_info['P_Len'] = p_left.apply(len) + p_left_info['Position1'] = position1 + p_left_info['Position2'] = p_left_info['Position1']\ + + p_left_info['P_Len'] + return p_left_info + +def primer_range_right(seqid, rank, chrm, p_right, position2): + """""" + Takes the chromosome, primer sequence, and position and creates a + query range for tabix to search by. + + Args: + seqid (pd.Series): pandas column containing seqids + rank (pd.Series): pandas column containing primer rank + chrm (pd.Series): pandas column of chrm info + p_right (pd.Series): pandas column of the right primer seq + position1 (pd.Series): pandas column of the right primer position. + Returns: + p_right_info (pd.DataFrame): the positional info in a frame format. + """""" + p_right_info = pd.DataFrame() + p_right_info['Sequence ID'] = seqid + p_right_info['Primer Rank'] = rank + p_right_info['Chromosome'] = chrm.apply(str) + p_right_info['P_Len'] = p_right.apply(len) + p_right_info['Position2'] = position2 + p_right_info['Position1'] = p_right_info['Position2']\ + - p_right_info['P_Len'] + return p_right_info + + +def match_pinfo_to_vcf(p_info, vcf): + """""" + Normalizes chromosome column to reference VCF info. + Args: + p_info (pd.DataFrame): the primer information df + vcf (file): the tabix indexed vcf input + Returns: + p_info (pd.DataFrame): the primer information df normalized to genome + """""" + switch = 0 + try: + for rec in vcf.fetch('chr1', constants.START_POS, constants.END_POS): + print(""Updating switch: 1"") + switch = 1 + except: + for rec in vcf.fetch('1', constants.START_POS, constants.END_POS): + print(""Updating switch: 2"") + switch = 2 + + if switch == 1 and not p_info['Chromosome']\ + .str.contains(""chr"").any(): + p_info['Chromosome'] = 'chr' + p_info['Chromosome'] + elif switch == 2 and p_info['Chromosome']\ + .str.contains(""chr"").any(): + p_info['Chromosome'] = p_info['Chromosome']\ + .str.replace('chr', '') + else: + pass + return p_info + + +def tabix_fetch(seqids, ranks, chrom, position1, position2, vcf_in): + """""" + Takes p_info positions and fetches SNPs from tabix indexed VCF. + Args: + seqids (pd.Series): pandas column of seqids + ranks (pd.Series): pandas column of primer ranks + chrom (pd.Series): pandas column of chrm info + position1 (pd.Series): pandas column of pos1 info + position2 (pd.Series): pandas column of pos2 info + Returns: + snp_list (list): list containing vcf info for primer positions. + """""" + snp_list = [] + for seqid, rank, chrm, pos1, pos2 in zip(seqids, ranks, chrom, position1, position2): + for row in vcf_in.fetch(chrm, pos1, pos2): + snp_list.append((seqid, rank, str(row).strip('\n').split('\t'))) + select_list = [] + for item in snp_list: + select_list.append((item[0], item[1], item[2][0], item[2][1],\ + item[2][2], item[2][7].split(';'))) + final_list = [] + for item in select_list: + geneinfo = [j for j in item[5] if ""GENEINFO="" in j] + caf = [j for j in item[5] if ""CAF="" in j] + topmed = [j for j in item[5] if ""TOPMED="" in j] + final_list.append((item[0], item[1], item[2], item[3], item[4], geneinfo, caf, topmed)) + return final_list + +def tabix_results_to_df(tabix_list, which_primer, column_name): + """""" + Takes the results from the tabix search and creates a dataframe. + Args: + tabix_list (list): tabix info from primer_left + which_primer (str): should be L or R to denote left or right in names + column_name (str): column name of snp count (should specify left or right) + Returns: + tabix_frame (pd.DataFrame): list organized into dataframe + """""" + tabix_frame = pd.DataFrame(tabix_list) + if len(tabix_frame) == 0: + sys.exit(""There are no SNPs in any of your primers, WOW!"") + else: + pass + tabix_frame.columns = [""Sequence ID"", ""Primer Rank"", + ""Chromosome"", ""SNPPosition"", ""rs_id"", + ""GeneInfo"", ""CommonAlleleFreq"", ""TopMedFreq""] + tabix_frame[""GeneInfo""] = tabix_frame[""GeneInfo""]\ + .apply(lambda x: ""NA"" if len(x) == 0 else x[0].split(""="")[1]) + tabix_frame[""CommonAlleleFreq""] = tabix_frame[""CommonAlleleFreq""]\ + .apply(lambda x: ""NA"" if len(x) == 0 else x[0].split('=')[1].split(',')[1]) + tabix_frame[""TopMedFreq""] = tabix_frame[""TopMedFreq""]\ + .apply(lambda x: ""NA"" if len(x) == 0 else x[0].split('=')[1].split(',')[1]) + tabix_frame = tabix_frame.groupby([""Sequence ID"", ""Primer Rank"", ""Chromosome""])\ + .agg({'SNPPosition': ';'.join, + 'rs_id': ';'.join, + 'GeneInfo': 'first', + 'CommonAlleleFreq': ';'.join, + 'TopMedFreq': ';'.join}).reset_index() + tabix_frame[column_name] = tabix_frame[""rs_id""]\ + .apply(lambda x: len(x.split(';'))) + tabix_frame.columns = [""Sequence ID"", ""Primer Rank"", ""Chromosome"", + ""%s_SNPPosition"" %which_primer, + ""%s_rs_id"" %which_primer, + ""%s_GeneInfo"" %which_primer, + ""%s_CommonAlleleFreq"" %which_primer, + ""%s_TopMedFreq"" %which_primer, column_name] + return tabix_frame + +def merge_left_right(left_df, right_df, total): + """""" + Merge left and right primer tabix info dataframes. + Args: + left_df (pd.DataFrame): primer left tabix dataframe + right_df (pd.DataFrame): primer right tabix dataframe + returns: + merged_tabix_df (pd.DataFrame): left and right merged df + """""" + merged_tabix_df = pd.merge(total, left_df, + on=['Sequence ID', 'Primer Rank'], how='left')\ + .merge(right_df, on=['Sequence ID', 'Primer Rank'], + how='left') + return merged_tabix_df + +if __name__ == ""__main__"": + main() +","Python" +"In Silico","stjude/PrimerTK","src/primer_tk/utils.py",".py","2796","66","#!/usr/bin/env python3 + +def primer3_input(header, sequence, args): + """""" Generates a primer3 input file with specified arguments. + Args: + header (string): The primer header string + sequence (string): the sequence used to design primers + args (Namespace): Arparse results. + Returns: + primer3_input_string (string): The string to write to the primer3 input file. + """""" + + primer3_input_string = ""SEQUENCE_ID=""+header+'\n'\ + +""SEQUENCE_TEMPLATE=""+sequence+'\n'\ + +""SEQUENCE_TARGET=%s"" %args.sequence_target+'\n'\ + +""PRIMER_FIRST_BASE_INDEX=1""+'\n'\ + +""PRIMER_TASK=pick_detection_primers""+'\n'\ + +""PRIMER_MIN_THREE_PRIME_DISTANCE=3""+'\n'\ + +""PRIMER_MAX_LIBRARY_MISPRIMING=12.00""+'\n'\ + +""PRIMER_PAIR_MAX_LIBRARY_MISPRIMING=20.00""+'\n'\ + +""PRIMER_PRODUCT_SIZE_RANGE=%s"" %args.product_size_range+'\n'\ + +""PRIMER_MAX_END_STABILITY=9.0""+'\n'\ + +""PRIMER_MAX_SELF_ANY_TH=45.00""+'\n'\ + +""PRIMER_MAX_SELF_END_TH=35.00""+'\n'\ + +""PRIMER_PAIR_MAX_COMPL_ANY_TH=45.00""+'\n'\ + +""PRIMER_PAIR_MAX_COMPL_END_TH=35.00""+'\n'\ + +""PRIMER_MAX_HAIRPIN_TH=24.00""+'\n'\ + +""PRIMER_MAX_TEMPLATE_MISPRIMING_TH=40.00""+'\n'\ + +""PRIMER_PAIR_MAX_TEMPLATE_MISPRIMING_TH=70.00""+'\n'\ + +""PRIMER_TM_FORMULA=1""+'\n'\ + +""PRIMER_SALT_CORRECTIONS=1""+'\n'\ + +""PRIMER_SALT_MONOVALENT=50.0""+'\n'\ + +""PRIMER_INTERNAL_SALT_MONOVALENT=50.0""+'\n'\ + +""PRIMER_SALT_DIVALENT=1.5""+'\n'\ + +""PRIMER_INTERNAL_SALT_DIVALENT=1.5""+'\n'\ + +""PRIMER_DNTP_CONC=0.6""+'\n'\ + +""PRIMER_INTERNAL_DNTP_CONC=0.6""+'\n'\ + +""PRIMER_DNA_CONC=50.0""+'\n'\ + +""PRIMER_INTERNAL_DNA_CONC=50.0""+'\n'\ + +""PRIMER_THERMODYNAMIC_OLIGO_ALIGNMENT=1""+'\n'\ + +""PRIMER_THERMODYNAMIC_TEMPLATE_ALIGNMENT=1""+'\n'\ + +""PRIMER_THERMODYNAMIC_PARAMETERS_PATH=%s"" %args.thermopath+'\n'\ + +""PRIMER_PICK_LEFT_PRIMER=1""+'\n'\ + +""PRIMER_PICK_RIGHT_PRIMER=1""+'\n'\ + +""PRIMER_PICK_INTERNAL_OLIGO=1""+'\n'\ + +""PRIMER_MAX_POLY_X=3""+'\n'\ + +""PRIMER_LEFT_NUM_RETURNED=5""+'\n'\ + +""PRIMER_RIGHT_NUM_RETURNED=5""+'\n'\ + +""PRIMER_OPT_SIZE=%s"" %args.primer_opt_size+'\n'\ + +""PRIMER_MIN_SIZE=%s"" %args.primer_min_size+'\n'\ + +""PRIMER_MAX_SIZE=%s"" %args.primer_max_size+'\n'\ + +""PRIMER_MIN_TM=%s"" %args.primer_min_tm+'\n'\ + +""PRIMER_OPT_TM=%s"" %args.primer_opt_tm+'\n'\ + +""PRIMER_MAX_TM=%s"" %args.primer_max_tm+'\n'\ + +""PRIMER_MAX_NS_ACCEPTED=1""+'\n'\ + +""PRIMER_NUM_RETURN=5""+'\n'\ + +""P3_FILE_FLAG=1""+'\n'\ + +""PRIMER_EXPLAIN_FLAG=1""+'\n'\ + +""PRIMER_MISPRIMING_LIBRARY=%s"" %args.mispriming+'\n'\ + +""PRIMER_MIN_GC=%s"" %args.primer_min_gc+'\n'\ + +""PRIMER_OPT_GC_PERCENT=%s"" %args.primer_opt_gc+'\n'\ + +""PRIMER_MAX_GC=%s"" %args.primer_max_gc+'\n'\ + +""PRIMER_PAIR_MAX_DIFF_TM=3""+'\n'\ + +""=""+'\n' + return primer3_input_string +","Python" +"In Silico","stjude/PrimerTK","src/primer_tk/genome_iterator.py",".py","9416","225","#!/usr/bin/env python3 + +"""""" +Modules required to run program. +Dependencies: + - python3.6+ + - pandas>=0.22.0 + - numpy>=1.14.2 + - biopython>=1.70 + - argparse +"""""" + +import sys +import time +import argparse +from Bio import SeqIO +import pandas as pd + +def add_iterator_subparser(subparser): + """""" + Get commandline arguments + Args: + subparser (?): Subparser object. + Returns: + args (Namespace): the parsed arguments. + """""" + + parser = subparser.add_parser(""iterator"", help=""Iterator subparser"") + + parser.add_argument(""-ref"", ""--ref_genome"", required=True, + help=""Reference Genome File to design primers around"") + parser.add_argument(""-in"", ""--regions_file"", required=True, + help=""File with regions to design primers around"") + parser.add_argument(""-opt_size"", ""--primer_opt_size"", + dest=""primer_opt_size"", default=""22"", + help=""The optimum primer size for output, default: 22"") + parser.add_argument(""-min_size"", ""--primer_min_size"", + dest=""primer_min_size"", default=""18"", + help=""The optimum primer size for output, default: 18"") + parser.add_argument(""-max_size"", ""--primer_max_size"", + dest=""primer_max_size"", default=""25"", + help=""The optimum primer size for output, default: 25"") + parser.add_argument(""-opt_gc"", ""--primer_opt_gc"", + dest=""primer_opt_gc"", default=""50"", + help=""Optimum primer GC, default: 50"") + parser.add_argument(""-min_gc"", ""--primer_min_gc"", + dest=""primer_min_gc"", default=""20"", + help=""Minimum primer GC, default: 20"") + parser.add_argument(""-max_gc"", ""--primer_max_gc"", + dest=""primer_max_gc"", default=""80"", + help=""Maximum primer GC, default: 80"") + parser.add_argument(""-opt_tm"", ""--primer_opt_tm"", + dest=""primer_opt_tm"", default=""60"", + help=""Optimum primer TM, default: 60"") + parser.add_argument(""-min_tm"", ""--primer_min_tm"", + dest=""primer_min_tm"", default=""57"", + help=""minimum primer TM, default: 57"") + parser.add_argument(""-max_tm"", ""--primer_max_tm"", + dest=""primer_max_tm"", default=""63"", + help=""maximum primer TM, default: 63"") + parser.add_argument(""-sr"", ""--product_size_range"", + dest=""product_size_range"", default=""200-400"", + help=""Size Range for PCR Product, default=200-400"") + parser.add_argument(""-flank"", ""--flanking_region_size"", + dest=""flanking_region_size"", default=""200"", + help=""This value will select how many bases up and downstream to count\ + when flanking SNP (will do 200 up and 200 down), default: 200"") + parser.add_argument(""-st"", ""--sequence_target"", + dest=""sequence_target"", default=""199,1"", + help=""default: 199,1, should be half of your flanking region size,\ + so SNP/V will be included."") + parser.add_argument(""-mp"", ""--mispriming"", dest=""mispriming"", + help=""full path to mispriming library for primer3\ + (EX: /home/dkennetz/mispriming/humrep.ref"") + parser.add_argument(""-tp"", ""--thermopath"", dest=""thermopath"", + help=""full path to thermo parameters for primer3 to use\ + (EX: /home/dkennetz/primer3/src/primer3_config/) install loc"") + + return parser + +def genome_iterator(genome): + """""" + Uses Biopython SeqIO to parse a genome Fasta and store each chr and + sequence as a list. + + Args: + genome (file): Full reference genome from command-line arguments. + + Returns: + output (list): genome parsed into list of tuples of (header, seq) + by chromosome for easy access later. + """""" + output = [] + with open(genome, ""r"") as handle: + for record in SeqIO.parse(handle, ""fasta""): + chrm = record.id + seq = record.seq + output.append((chrm, seq)) + return output + +def create_dataframe_csv(regions_file): + """""" + Creates a pandas DataFrame from a regions file in comma separated form + and names the columns in the DF according to their values. + + Args: + regions_file (file): Full path to -in input regions.csv. + This should have coordinate positions of interest to design primers around. + Note: the chromosome column can be of format chr1 or simply 1 (chr not necessary). + The file should contain no headers and should be structured as follows: + + Gene1,Sample1,chr1,pos1 + Gene2,Sample2,chr2,pos2 + Gene3,Sample3,chr3,pos3 + ... + Returns: + regions_df (pd.DataFrame): The infile parsed to pd.DataFrame object. + """""" + + regions_df = pd.read_csv(regions_file, header=None) + regions_df.columns = ['Gene', 'Sample', 'Chr', 'Pos'] + regions_df = regions_df.astype({'Chr': str}) + return regions_df + +def create_dataframe_txt(regions_file): + """""" + Creates a pandas DataFrame from a regions file in a tab separated form + and uses the following column names in the DF according to their values. + + Args: + regions_file (file): Full path to -in input regions.txt. + This should have coordinate positions of interest to design primers around. + Note: the chromosome column can be of format chr1 or simply 1 (chr not necessary). + The file should contain no headers and should be constructed as follows: + + Gene1\tSample1\tchr1\tpos1 + Gene2\tSample2\tchr2\tpos2 + Gene3\tSample3\tchr3\tpos3 + ... + Returns: + regions_df (pd.DataFrame): The infile parsed to pd.DataFrame object. + """""" + regions_df = pd.read_table(regions_file, header=None) + regions_df.columns = ['Gene', 'Sample', 'Chr', 'Pos'] + regions_df = regions_df.astype({'Chr': str}) + return regions_df + +def file_extension(infile): + """""" + Runs pd.read_ function to create dataframe corresponding + to file extension, .txt and .csv accepted. + This will call the function to create a df only if file extension is correct. + If the file extension is wrong, it will return the error message and exit. + + Args: + infile (file): Full path to -in input regions.txt. + Returns: + small_regions (pd.DataFrame): The infile parsed to pd.DataFrame object + """""" + if infile.lower().endswith('.txt'): + small_regions = create_dataframe_txt(infile) + elif infile.lower().endswith('.csv'): + small_regions = create_dataframe_csv(infile) + else: + sys.exit(""Wrong File Format, should be .txt or .csv"") + return small_regions + +def match_chr_to_genome(dataframe, genome): + """""" + Used to match formatting between regionsFile input and genome for chromosome + denotations. Some genomes contain the string ""chr"" and some do not. + + Args: + dataframe (pandas object): dataframe created from create_dataframe() function. + genome (list): genome list of tuples created from genome_iterator() function. + + Returns: + dataframe (pandas object): dataframe formatted to match genome annotation of chromosome. + """""" + if dataframe['Chr'].str.contains(""chr"").any() and ""chr"" in str(genome[0][0]): + pass + elif dataframe['Chr'].str.contains(""chr"").any() and ""chr"" not in str(genome[0][0]): + dataframe['Chr'] = dataframe['Chr'].str.replace('chr', '') + elif not dataframe['Chr'].str.contains(""chr"").any() and ""chr"" not in str(genome[0][0]): + pass + elif not dataframe['Chr'].str.contains(""chr"").any() and ""chr"" in str(genome[0][0]): + dataframe['Chr'] = 'chr' + dataframe['Chr'] + else: + print(""look at pandas error"") + return dataframe + +def create_flanking_regions_fasta(genome, dataframe, flanking_region_size): + """""" + Makes batch processing possible, pulls down small + region of genome for which to design primers around. + This is based on the chromosome and position of input file. + Each Fasta record will contain: + >Sample_Gene_chr:pos__ + Seq of flanking region + + Args: + genome (list): genome list of tuples (header, seq). + dataframe (pandas object): dataframe with sample info. + flanking_region_size (int): length of sequence upstream and downstream of + input coordindate position to pull as sequence to design primers around. + Returns: + output (list): list of tuples with (header, seq) where seq is flanking region + and header is sample ID. + """""" + output = [] + for headers, seqs in genome: + chrm = str(headers) + seq = str(seqs) + for gene, sample, chrom, pos in zip(dataframe.Gene, dataframe.Sample, + dataframe.Chr, dataframe.Pos): + if str(chrom) == chrm: + header = str(str(sample)+""_""+str(gene)+""_""+str(chrom)+"":""+str(pos)+""__"") + flank_seq = seq[int(pos)-int(flanking_region_size):\ + int(pos)+int(flanking_region_size)] + output.append((header, flank_seq.upper())) + return output + +if __name__ == ""__main__"": + main() +","Python" +"In Silico","stjude/PrimerTK","src/primer_tk/core.py",".py","16116","303","#!/usr/bin/env python3 +"""""" Core modules """""" + +import os +from pysam import VariantFile +from primer_tk import genome_iterator as gi +from primer_tk import analyze_pcr_output as ap +from primer_tk import analyze_pcr_output_sv as apv +from primer_tk.mp_class import MissingPrimers as mp +from primer_tk.mp_class import create_df as cd +from primer_tk.mp_class_sv import MissingPrimers as mpv +from primer_tk.mp_class_sv import create_df as cdv +from primer_tk import utils +import primer_tk.primer_cross_hyb as pch +from primer_tk import primer_tabix as pt +from primer_tk import genome_iterator_sv as giv + + +def iterator_sv(args): + """""" Use an input regions file with SV positions to pull + down flanking sequence on both sides of SV to generate + primers upstream and downstream of the SV. + + Args: + args (Namespace): Argparse results. + + Returns: None + """""" + + dataset_name = os.path.splitext(str(args.regions_file))[0] + genome = giv.genome_iterator(args.ref_genome) + # 2) create dataframe from input regions file + if args.sv in ('deletion', 'inversion'): + small_regions = giv.file_extension(args.regions_file, args.sv) + # 3) ensure proper proper number of columns in dataframe + assert len(list(small_regions)) == 5, ""DataFrame contains more/less than 5 columns...\ + Improper format."" + # 4) format dataframe ""chr"" column to match reference genome + small_regions = giv.match_chr_to_genome(small_regions, genome, args.sv) + # 5) generate flanking regions fasta based on position in input file + flanking = open(""flanking_regions.%s.fasta"" % dataset_name, 'w') + if args.sv == 'deletion': + flank_data = giv.flanking_regions_fasta_deletion(genome, small_regions, args.flanking_region_size) + primer3_in = open(""primer3_input.%s.txt"" % dataset_name, 'w') + for head, seq in flank_data: + flanking.write("">""+head+'\n'+seq+'\n') + # 6) generate primer3 input file + primer3_in.write(utils.primer3_input(head, seq, args)) + elif args.sv == 'inversion': + flank_data = giv.flanking_regions_fasta_inversion(genome, small_regions, args.flanking_region_size) + primer3_in = open(""primer3_input.%s.txt"" % dataset_name, 'w') + for head, seq in flank_data: + flanking.write("">""+head+'\n'+seq+'\n') + # 6) generate primer3 input file + primer3_in.write(utils.primer3_input(head, seq, args)) + flanking.close() + primer3_in.close() + + elif args.sv == 'insertion': + small_regions = giv.file_extension(args.regions_file, args.sv) + assert len(list(small_regions)) == 10, ""DataFrame contains more/less than 10 columns... Exiting."" + small_regions = giv.match_chr_to_genome(small_regions, genome, args.sv) + flanking = open(""flanking_regions.%s.fasta"" %dataset_name, 'w') + flank_data = giv.flanking_region_fasta_insertion(genome, small_regions, args.flanking_region_size) + primer3_in = open(""primer3_input.%s.txt"" % dataset_name, 'w') + for head, seq in flank_data.items(): + flanking.write("">""+head+'\n'+seq+'\n') + primer3_in.write(utils.primer3_input(head, seq, args)) + elif args.sv == 'translocation': + small_regions = giv.file_extension(args.regions_file, args.sv) + assert len(list(small_regions)) == 8, ""DataFrame contains more/less than 8 columns... Exiting."" + small_regions = giv.match_chr_to_genome(small_regions, genome, args.sv) + flanking = open(""flanking_regions.%s.fasta"" %dataset_name, 'w') + flank_data = giv.flanking_region_fasta_translocation(genome, small_regions, args.flanking_region_size) + primer3_in = open(""primer3_input.%s.txt"" %dataset_name, 'w') + for head, seq in flank_data.items(): + flanking.write("">""+head+'\n'+seq+'\n') + primer3_in.write(utils.primer3_input(head, seq, args)) + flanking.close() + primer3_in.close() + +def iterator(args): + """""" + Use an input regions file with specific region of interest\ + to design primers around, then run primer3. + + Args: + args (Namespace): Argparse object or None. + + Returns: None + """""" + + dataset_name = os.path.splitext(str(args.regions_file))[0] + # 1) create genome tuple from provided reference + genome = gi.genome_iterator(args.ref_genome) + # 2) create dataframe from input regions file + small_regions = gi.file_extension(args.regions_file) + # 3) ensure proper proper number of columns in dataframe + assert len(list(small_regions)) == 4, ""DataFrame contains more than 4 columns...\ + Improper format."" + # 4) format dataframe ""chr"" column to match reference genome + small_regions = gi.match_chr_to_genome(small_regions, genome) + # 5) generate flanking regions fasta based on position in input file + flanking = open(""flanking_regions.%s.fasta"" % dataset_name, 'w') + flank_data = gi.create_flanking_regions_fasta(genome, small_regions, args.flanking_region_size) + primer3_in = open(""primer3_input.%s.txt"" % dataset_name, 'w') + for head, seq in flank_data: + flanking.write("">""+head+'\n'+seq+'\n') + # 6) generate primer3 input file + primer3_in.write(utils.primer3_input(head, seq, args)) + flanking.close() + primer3_in.close() + +def pre(args): + """""" Function for all steps leading up to PCR. """""" + # 1) Initialize primer lists by rank for each sample + prim_list_0 = mp(args.dump, 0).samp_primer_info + prim_list_1 = mp(args.dump, 1).samp_primer_info + prim_list_2 = mp(args.dump, 2).samp_primer_info + prim_list_3 = mp(args.dump, 3).samp_primer_info + prim_list_4 = mp(args.dump, 4).samp_primer_info + # 2) Generate the output df + primer_df = cd([prim_list_0, prim_list_1, prim_list_2, + prim_list_3, prim_list_4]) + # 3) Generate csv output + primer_df = primer_df.loc[~(primer_df['Primer Left Seq'] == 'NA')] + primer_df.to_csv(args.outfile, index=False) + primer_df_standard = primer_df.copy() + # 5) Get length of forward primers for percent alignment check + if args.pcr == 'multiplex': + fp_len = pch.get_fprimer_percent_aln(primer_df['Primer Left Seq'], int(args.percent_alignment)) + # 6) Generate primer dimer pairs for all vs all input + primer1_2_compare = pch.list_from_gen(pch.primer_dimer_local(fp_len, primer_df['Sequence ID'], + primer_df['Primer Left Seq'], + primer_df['Primer Right Seq'])) + primer2_1_compare = pch.list_from_gen(pch.primer_dimer_local(fp_len, primer_df['Sequence ID'], + primer_df['Primer Right Seq'], + primer_df['Primer Left Seq'])) + primer1_1_compare = pch.list_from_gen(pch.primer_dimer_local(fp_len, primer_df['Sequence ID'], + primer_df['Primer Left Seq'], + primer_df['Primer Left Seq'])) + primer2_2_compare = pch.list_from_gen(pch.primer_dimer_local(fp_len, primer_df['Sequence ID'], + primer_df['Primer Right Seq'], + primer_df['Primer Right Seq'])) + # 7) Reformat output, Biopython + Class writes ugly output. + primer1_2_dimers = pch.p_list_formatter(primer1_2_compare) + primer2_1_dimers = pch.p_list_formatter(primer2_1_compare) + primer1_1_dimers = pch.p_list_formatter(primer1_1_compare) + primer2_2_dimers = pch.p_list_formatter(primer2_2_compare) + # 8) Write output of all primer pairs that form dimers. + pd_file = open('Primer_Dimers.txt', 'w') + pd_file.write('#This is a list of possible primer dimers based on the input complementarity.\n') + pd_file.write('#Comparison of forward primers with all reverse primers...\ + \n#Sequence ID \t \t Complementarity Score\n') + for seq in primer1_2_dimers: + pd_file.write(str(seq) + '\n') + pd_file.write('#Comparison of reverse primers with all forward primers...\n') + for seq in primer2_1_dimers: + pd_file.write(str(seq) + '\n') + pd_file.write('#Comparison of forward primers with all other forward primers...\n') + for seq in primer1_1_dimers: + pd_file.write(str(seq) + '\n') + pd_file.write('#Comparison of revers primers with all other reverse primers...\n') + for seq in primer2_2_dimers: + pd_file.write(str(seq) + '\n') + pd_file.close() + # 9) Searche dataframe for dimers in list. If present, marked with True boolean in new column. + # Else, False. Used for filtering in next step. + primer_df['Dimers1_2F'] = pch.dimer_true(primer_df, 2, primer1_2_dimers) + primer_df['Dimers2_1F'] = pch.dimer_true(primer_df, 2, primer2_1_dimers) + primer_df['Dimers1_1F'] = pch.dimer_true(primer_df, 2, primer1_1_dimers) + primer_df['Dimers2_2F'] = pch.dimer_true(primer_df, 2, primer2_2_dimers) + primer_df['Dimers1_2R'] = pch.dimer_true(primer_df, 3, primer1_2_dimers) + primer_df['Dimers2_1R'] = pch.dimer_true(primer_df, 3, primer2_1_dimers) + primer_df['Dimers1_1R'] = pch.dimer_true(primer_df, 3, primer1_1_dimers) + primer_df['Dimers2_2R'] = pch.dimer_true(primer_df, 3, primer2_2_dimers) + # 10) Search for true statements, True statements indicate dimer duo. Only keep non-dimers + df_bool = (primer_df.loc[~(primer_df['Dimers1_2F'] | primer_df['Dimers2_1F']\ + | primer_df['Dimers1_1F'] | primer_df['Dimers2_2F']\ + | primer_df['Dimers1_2R'] | primer_df['Dimers2_1R']\ + | primer_df['Dimers1_1R'] | primer_df['Dimers2_2R'] == True)]) + # 11) Write output to csv + df_bool.to_csv(args.no_dimer, index=False) + pch.all_vs_all_pcr(df_bool, args.multiplex_pcr_file) + elif args.pcr == 'standard': + pch.standard_pcr(primer_df_standard, args.standard_pcr_file) + else: + print(""Please select pcr setup"") + +def pre_sv(args): + """""" + Function for all steps leading up to PCR. + """""" + # 1) Initialize primer lists by rank for each sample + prim_list_0 = mpv(args.dump, 0).samp_primer_info + prim_list_1 = mpv(args.dump, 1).samp_primer_info + prim_list_2 = mpv(args.dump, 2).samp_primer_info + prim_list_3 = mpv(args.dump, 3).samp_primer_info + prim_list_4 = mpv(args.dump, 4).samp_primer_info + # 2) Generate the output df + primer_df = cdv([prim_list_0, prim_list_1, prim_list_2, + prim_list_3, prim_list_4]) + # 3) Generate csv output + primer_df = primer_df.loc[~(primer_df['Primer Left Seq'] == 'NA')] + primer_df.to_csv(args.outfile, index=False) + # 4) create standard pcr input + pch.standard_pcr(primer_df, args.pcrfile) + +def post(args): + """""" + Generates pcr analysis dataframes and applies primer filtering based on + off-target amplification. Then compares good primers to initial primer + list to find which primer pair was generated and top ranking. + Finally, produces easy to use IDT order sheet in plate format (standard PCR only). + """""" + # 2) Generate seqs and headers lists + seqs, headers = ap.fasta_parser(args.pcrfile) + # 3) Calculate GC of each PCR product and store in list + gc_list = ap.gc_percent_seqs(seqs) + # 4) Split up the header line and get no_chrom_list + split_headers, no_chrom = ap.split_headers_list(headers) + # 5) Generate chrom list + chrom_list = ap.chr_split_list(split_headers) + # 6) Get split positions list + pos_split = ap.pos_split_list(chrom_list) + # 7) Need to delete positions after extracting positions (ugly) + for item in chrom_list: + del item[-1] + # 7) Get name and pos split list + name_pos_list = ap.split_name_pos(no_chrom) + # 8) Merge all these lists for dataframe + merged_list = ap.merge_info(chrom_list, pos_split, name_pos_list, no_chrom) + all_pcr_df, good_primers_df, bad_primers_df = ap.generate_pcr_df(merged_list, gc_list) + # 9) Output file generation + all_pcr_df.to_csv(args.pcr_product_info, index=False) + # 10) Merge good primers df with toal primers df + merged_df = ap.merge_good_total(good_primers_df, args.total_primers) + # 11) Keep only primers which match bw good and total primers + filtered_df = ap.filter_merged(merged_df, args.off_target_max) + filtered_df.to_csv(args.all_primer_info, index=False) + # 12) Output only top ranked final primers after filter + top_ranked_df = ap.top_ranked_final_primers(filtered_df) + top_ranked_df.to_csv(args.top_final_primers, index=False) + plate_order_f, plate_order_r = ap.to_order_plate(top_ranked_df) + plate_order_f.to_csv(args.plate_basename+'_F.csv', index=False) + plate_order_r.to_csv(args.plate_basename+'_R.csv', index=False) + +def post_sv(args): + """""" + Generates pcr analysis dataframes and applies primer filtering based on + off-target amplification. Then compares good primers to initial primer + list to find which primer pair was generated and top ranking. + Finally, produces easy to use IDT order sheet in plate format (standard PCR only). + """""" + # 2) Generate seqs and headers lists + seqs, headers = apv.fasta_parser(args.flank_file) + # 3) Calculate GC of each PCR product and store in list + positions_to_compare = apv.amp_header_region(args.total_primers) + sliced_seqs = apv.get_gc_region(seqs, headers, positions_to_compare) + gc_calc = apv.calc_gc(sliced_seqs) + merged_df = apv.merge_dfs(gc_calc, args.total_primers, seqs) + merged_df.to_csv(args.all_final_primers, index=False) + merged_df.drop_duplicates('Sequence ID', keep='first', inplace=True) + merged_df.to_csv(args.top_final_primers, index=False) + plate_order_f, plate_order_r = apv.to_order_plate(merged_df) + plate_order_f.to_csv(args.plate_basename+'_F.csv', index=False) + plate_order_r.to_csv(args.plate_basename+'_R.csv', index=False) + +def tabix(args): + """""" + Annotates primers with SNP information. + """""" + vcf_in = VariantFile(args.vcf) + p_info = pt.create_tabix_df(args.p_info) + p_left = pt.primer_range_left(p_info[""Sequence ID""], + p_info[""Primer Rank""], + p_info[""Chromosome""], + p_info[""Primer Left Seq""], + p_info[""Position1""]) + p_right = pt.primer_range_right(p_info[""Sequence ID""], + p_info[""Primer Rank""], + p_info[""Chromosome""], + p_info[""Primer Right Seq""], + p_info[""Position2""]) + pn_left = pt.match_pinfo_to_vcf(p_left, vcf_in) + pn_right = pt.match_pinfo_to_vcf(p_right, vcf_in) + left_snps = pt.tabix_fetch(pn_left[""Sequence ID""], + pn_left[""Primer Rank""], + pn_left[""Chromosome""], + pn_left[""Position1""], + pn_left[""Position2""], + vcf_in) + right_snps = pt.tabix_fetch(pn_right[""Sequence ID""], + pn_right[""Primer Rank""], + pn_right[""Chromosome""], + pn_right[""Position1""], + pn_right[""Position2""], + vcf_in) + left_df = pt.tabix_results_to_df(left_snps, ""L"", ""Left SNP Count"") + right_df = pt.tabix_results_to_df(right_snps, ""R"", ""Right SNP Count"") + merged_df = pt.merge_left_right(left_df, right_df, p_info) + merged_df.to_csv(args.output, index=False) +","Python" +"In Silico","stjude/PrimerTK","src/primer_tk/mp_class_sv.py",".py","7659","168","#!/usr/bin/env python3 + +"""""" +Dependencies required to run program: + - python3.6+ + - pandas>=0.22.0 + - numpy>=1.16.0 +"""""" + +import pandas as pd +import numpy as np +import sys + +class MissingPrimers: + """""" + Groups Primer3 output by sample id into a list of lists, + adds NA to all groups that do not have 5 primers generated, + and then outputs a list corresponding to each primer rank. + Args: + file_name (string): name of file to be passed to program + value (int): rank of primer pair to store as list [0-4] only + Returns: + samp_primer_info (list): list of lists with all values required for + downstream analysis (id, lseq, rseq, l_tm, r_tm, + l_gc, r_gc, product_size) + """""" + def __init__(self, file_name, value): + """""" + Initialize Values + """""" + self.file_name = file_name + self.value = str(value) + self.dump_list = self.__group_seqids() + self.filled_primers = self.__fill_empty_values() + self.samp_primer_info = self.__gather_primer_info() + + def __group_seqids(self): + """""" + Group by sample_id + """""" + sequence = """" + with open(self.file_name) as dump: + for line in dump: + if not line.startswith('='): + sequence += line + if line.startswith('='): + fixed_line = line.replace('=', '@@@') + sequence += fixed_line + full_string = ''.join([line for line in sequence]) + primer_split = [[string] for string in full_string.\ + split('@@@') if string is not ' '] + primers_info = primer_split[:-1] + return primers_info + + def __fill_empty_values(self): + """""" + Fill in missing required values with NA + """""" + sequence = [] + for sample in self.dump_list: + for string in sample: + if ""PRIMER_LEFT_0_SEQUENCE="" not in string: + string = string + ""PRIMER_LEFT_0_SEQUENCE=NA\n""\ + + ""PRIMER_RIGHT_0_SEQUENCE=NA\n""\ + + ""PRIMER_LEFT_0=NA\n""\ + + ""PRIMER_RIGHT_0=NA\n""\ + + ""PRIMER_LEFT_0_TM=NA\n"" + ""PRIMER_RIGHT_0_TM=NA\n""\ + + ""PRIMER_LEFT_0_GC_PERCENT=NA\n""\ + + ""PRIMER_RIGHT_0_GC_PERCENT=NA\n""\ + + ""PRIMER_PAIR_0_PRODUCT_SIZE=NA\n"" + if ""PRIMER_LEFT_1_SEQUENCE="" not in string: + string = string + ""PRIMER_LEFT_1_SEQUENCE=NA\n""\ + + ""PRIMER_RIGHT_1_SEQUENCE=NA\n""\ + + ""PRIMER_LEFT_1=NA\n""\ + + ""PRIMER_RIGHT_1=NA\n""\ + + ""PRIMER_LEFT_1_TM=NA\n"" + ""PRIMER_RIGHT_1_TM=NA\n""\ + + ""PRIMER_LEFT_1_GC_PERCENT=NA\n""\ + + ""PRIMER_RIGHT_1_GC_PERCENT=NA\n""\ + + ""PRIMER_PAIR_1_PRODUCT_SIZE=NA\n"" + if ""PRIMER_LEFT_2_SEQUENCE="" not in string: + string = string + ""PRIMER_LEFT_2_SEQUENCE=NA\n""\ + + ""PRIMER_RIGHT_2_SEQUENCE=NA\n""\ + + ""PRIMER_LEFT_2=NA\n""\ + + ""PRIMER_RIGHT_2=NA\n""\ + + ""PRIMER_LEFT_2_TM=NA\n"" + ""PRIMER_RIGHT_2_TM=NA\n""\ + + ""PRIMER_LEFT_2_GC_PERCENT=NA\n""\ + + ""PRIMER_RIGHT_2_GC_PERCENT=NA\n""\ + + ""PRIMER_PAIR_2_PRODUCT_SIZE=NA\n"" + if ""PRIMER_LEFT_3_SEQUENCE="" not in string: + string = string + ""PRIMER_LEFT_3_SEQUENCE=NA\n""\ + + ""PRIMER_RIGHT_3_SEQUENCE=NA\n""\ + + ""PRIMER_LEFT_3=NA\n""\ + + ""PRIMER_RIGHT_3=NA\n""\ + + ""PRIMER_LEFT_3_TM=NA\n"" + ""PRIMER_RIGHT_3_TM=NA\n""\ + + ""PRIMER_LEFT_3_GC_PERCENT=NA\n""\ + + ""PRIMER_RIGHT_3_GC_PERCENT=NA\n""\ + + ""PRIMER_PAIR_3_PRODUCT_SIZE=NA\n"" + if ""PRIMER_LEFT_4_SEQUENCE="" not in string: + string = string + ""PRIMER_LEFT_4_SEQUENCE=NA\n""\ + + ""PRIMER_RIGHT_4_SEQUENCE=NA\n""\ + + ""PRIMER_LEFT_4=NA\n""\ + + ""PRIMER_RIGHT_4=NA\n""\ + + ""PRIMER_LEFT_4_TM=NA\n"" + ""PRIMER_RIGHT_4_TM=NA\n""\ + + ""PRIMER_LEFT_4_GC_PERCENT=NA\n""\ + + ""PRIMER_RIGHT_4_GC_PERCENT=NA\n""\ + + ""PRIMER_PAIR_4_PRODUCT_SIZE=NA\n"" + sequence.append(string.lstrip('\n').split('\n')) + + return sequence + + def __gather_primer_info(self): + """""" + Return the final list of lists with all filled values by rank + """""" + sample_info = [] + for item in self.filled_primers: + for p_info in item: + if ""SEQUENCE_ID="" in p_info: + seq_id = p_info[12:]+self.value + if ""PRIMER_LEFT_%s_SEQUENCE="" %self.value in p_info: + p_left = p_info[23:] + if ""PRIMER_RIGHT_%s_SEQUENCE="" %self.value in p_info: + p_right = p_info[24:] + if ""PRIMER_LEFT_%s="" %self.value in p_info: + left_pos = p_info[14:-3] + if ""PRIMER_RIGHT_%s="" %self.value in p_info: + right_pos = p_info[15:-3] + if ""PRIMER_LEFT_%s_TM="" %self.value in p_info: + left_tm = p_info[17:] + if ""PRIMER_RIGHT_%s_TM="" %self.value in p_info: + right_tm = p_info[18:] + if ""PRIMER_LEFT_%s_GC_PERCENT="" %self.value in p_info: + left_gc = p_info[25:] + if ""PRIMER_RIGHT_%s_GC_PERCENT="" %self.value in p_info: + right_gc = p_info[26:] + if ""PRIMER_PAIR_%s_PRODUCT_SIZE="" %self.value in p_info: + product_size = p_info[27:] + sample_info.append([seq_id, p_left, p_right, left_tm, + right_tm, left_gc, right_gc, + product_size, left_pos, + right_pos]) + + return sample_info + +def create_df(primer_lists): + """""" + Creates a dataframe from gather_primer_info + Args: + primer_lists (list): primer information lists to be passed for dataframe. + Returns: + primer_df (pd.DataFrame): Dataframe with all primer information. + """""" + primer_df = pd.DataFrame(np.ma.row_stack(primer_lists), + columns=['Sequence ID', 'Primer Left Seq', 'Primer Right Seq', + 'Primer Left TM', 'Primer Right TM', + 'Primer Left GC %', 'Primer Right GC %', + 'Primer3 Predicted Product', 'Primer Left Pos', + 'Primer Right Pos']) + primer_df = primer_df.sort_values('Sequence ID').reset_index().drop(labels='index', axis=1) + rank = [num[-1] for num in primer_df['Sequence ID']] + primer_df.insert(1, 'Primer Rank', rank) + left_len = [len(length) for length in primer_df['Primer Left Seq']] + right_len = [len(length) for length in primer_df['Primer Right Seq']] + primer_df.insert(4, 'Primer Left Len', left_len) + primer_df.insert(5, 'Primer Right Len', right_len) + primer_df['Sequence ID'] = [seqid[:-1] for seqid in primer_df['Sequence ID']] + return primer_df +","Python" +"In Silico","stjude/PrimerTK","src/primer_tk/__main__.py",".py","1591","66","#!/usr/bin/env python3 +"""""" Main entry point for primer_tk """""" + +import sys +import argparse + +from primer_tk import genome_iterator, genome_iterator_sv, \ + primer_cross_hyb, \ + analyze_pcr_output, analyze_pcr_output_sv, \ + primer_tabix, \ + __version__ + +from primer_tk import core + +def get_args(argv): + """""" Get arguments + + Args: + argv (list): List of strings as argv. + + Returns: + args (Namespace): Argparse object. + """""" + + parser = argparse.ArgumentParser(prog=""primer_tk"") + parser.add_argument(""-v"", ""--version"", action=""version"", + version=__version__) + + subparser = parser.add_subparsers(help=""Actions"") + genome_iterator.add_iterator_subparser(subparser) + genome_iterator_sv.add_iterator_subparser(subparser) + primer_cross_hyb.add_pre_subparser(subparser) + primer_cross_hyb.add_pre_sv_subparser(subparser) + analyze_pcr_output.add_post_subparser(subparser) + analyze_pcr_output_sv.add_post_subparser(subparser) + primer_tabix.add_tabix_subparser(subparser) + + args = parser.parse_args(argv) + + return args + +def main(): + """""" Main rountine """""" + + args = get_args(sys.argv[1:]) + + action = sys.argv[1] + + if action == ""iterator"": + core.iterator(args) + elif action == ""iterator_sv"": + core.iterator_sv(args) + elif action == ""pre"": + core.pre(args) + elif action == ""pre_sv"": + core.pre_sv(args) + elif action == ""post"": + core.post(args) + elif action == ""post_sv"": + core.post_sv(args) + elif action ==""tabix"": + core.tabix(args) + + +main() +","Python" +"In Silico","stjude/PrimerTK","src/primer_tk/sequence_info.py",".py","3997","129","#!/usr/bin/env python3 + +"""""" Modules required to run program. + +Dependencies: + - python3.6+ + - biopython>=1.70 +"""""" + +from Bio import pairwise2 + +class Sequence: + """""" + Creates a sequence object from an input DNA sequence. + """""" + + def __init__(self, sequence): + """""" + Initialize seq object. + """""" + self.sequence = str(sequence).upper() + self.name = ""seq_name_not_set"" + + def set_name(self, name): + """""" + Sets name of sequence object. + """""" + self.name = name + + def complement(self): + """""" + Returns complement (defined in Global vars). + Example: ATCG -> TAGC + """""" + return ''.join(map(complement_base, self.sequence)) + + def reverse_complement(self): + """""" + Returns the reversed complement of the sequence. + Example: ATCG -> TAGC -> CGAT + """""" + return ''.join(map(complement_base, self.sequence[::-1])) + + def reverse_sequence(self): + """""" + Returns the reverse of the input sequence. + Example: ATCG -> GCTA + """""" + return self.sequence[::-1] + + def gc_percent(self): + """""" + Calculates GC as a percentage of the input sequence. + Example: ATCG = 50 + """""" + return float((self.sequence.count('G') +\ + self.sequence.count('C')) / float(len(self.sequence))*100) + + +class PrimerDimer(Sequence): + """""" + Identifies dimerization between 2 sequences. Essentially, + it identifies high degrees of complementarity between + sequences which could lead to undesired binding behavior + during PCR amplification. Primers bind to each other rather + than target DNA strand if in pool. + Example: ATCG + TAGC (high degree of complementarity). + """""" + def __init__(self, sequence, compare_sequence, pd_length): + super(PrimerDimer, self).__init__(sequence) + self.compare_sequence = compare_sequence + self.pd_length = pd_length + + def pd_local(self): + """""" + Compares sequence and comparesequence for the highest number of + identical characters within a single alignment of the two strings. + Output is a list with: + [sequence, + complement(comparesequence), + score, + beginning-of-alignment, + end-of-alignment] + Use of the static method 'format_alignment_compl' to format the + output is highly recommended to display the alignments. + """""" + for alignment in pairwise2.align.localxs(self.sequence, + self.compare_sequence, + -len(self.sequence), + -len(self.sequence)): + if int(alignment[2]) >= self.pd_length: + yield alignment + + @staticmethod + def format_alignment_compl(align1, align2, score, begin, end): + """""" + A modified version of biopython.pairwise2.format_alignment. + Instead of returning the align2 argument, the complement of align2 + is returned. + For PrimerDimers we are trying to find complementary base pairings + so this scores based on complementarity, whereas pairwise2 scores on + literal matches. + """""" + seq = [] + compalign2 = Sequence(align2).complement() + + seq.append(""%s\n"" % align1) + seq.append(""%s%s\n"" % ("" ""*begin, ""|""*(end-begin))) + seq.append(""%s\n"" % compalign2) + seq.append("" Score=%g\n"" % score) + return ''.join(seq) + +# GLOBAL VARS +_COMPLEMENTS = {'-': '-', 'N': 'N', 'A': 'T', 'T': 'A', 'G': 'C', 'C': 'G'} + +def is_complement(base1, base2): + """""" + Used to identify is base2 is a complement of base1 + """""" + return _COMPLEMENTS[base1] == base2 + +def complement_base(base): + """""" + Returns the complement for a base. + """""" + if base in _COMPLEMENTS: + return _COMPLEMENTS[base] + print(""base not in complements, something is wrong!"") +","Python" +"In Silico","stjude/PrimerTK","test/run_test.sh",".sh","604","24","#!/usr/bin/env bash +# test developed by JRM3 + +# This script will ALWAYS be run from the directory in which it is locatred +# so as to ensure relative directory structures are intact. +SCRIPT_DIR=$(dirname $0) +#cd $SCRIPT_DIR + +usage() { + echo ""run_tests.sh [-h]"" +} + +#################### +### Build source ### +#################### +export PYTHONPATH=$(pwd)/../../lib:$PYTHONPATH +export PATH=$(pwd)/../../scripts:$PATH + +######################### +### Python unit tests ### +######################### +coverage run --source .. -m unittest discover python_tests -p ""test*.py"" -b +coverage report --skip-covered -m +","Shell" +"In Silico","stjude/PrimerTK","test/python_tests/test_genome_iterator.py",".py","2703","82","#!/usr/bin/env python3 +"""""" +Unit tester for genome_iterator.py + +Python version: Python 3.6.8 :: Anaconda, Inc. +Date: 02/28/2019 +Dependencies: + - unittest + - pandas>=0.22.0 +"""""" + +import unittest +import pandas as pd +from primer_tk import genome_iterator as gi + +class TestGenomeIterator(unittest.TestCase): + """""" + Subclass of unittest to test genome_iterator.py + """""" + def setUp(self): + self.ref_genome = ""test/data/test_standard.fa"" + self.genome = gi.genome_iterator(self.ref_genome) + self.test_input = 'test/data/input_standard.csv' + self.test_input2 = 'test/data/input_standard.txt' + self.test_input3 = 'test/data/input_standard.fa' + #self.parser = gi.get_args_iterator([]) + + def test_genome_iterator(self): + """""" + Asserts object output by genome_iterator function has length of 2 (header, seq) + """""" + self.assertEqual(len(self.genome[0]), 2) + + def test_create_dataframe_csv(self): + """""" + Asserts that a pd.DataFrame is returned from function. + """""" + self.assertTrue(isinstance(gi.create_dataframe_csv(self.test_input), pd.DataFrame)) + + def test_create_dataframe_txt(self): + """""" + Assets that a pd.DataFrame is returned from function. + """""" + self.assertTrue(isinstance(gi.create_dataframe_txt(self.test_input2), pd.DataFrame)) + + def test_file_extension_success(self): + """""" + Asserts that a pd.DataFrame is returned only if file extension matches. + """""" + self.assertTrue(isinstance(gi.file_extension(self.test_input2), pd.DataFrame)) + + def test_file_extension_failure(self): + """""" + Asserts that code exits with warning message if file extension is incorrect. + """""" + with self.assertRaises(SystemExit) as code_message: + gi.file_extension(self.test_input3) + self.assertEqual(code_message.exception.code, + ""Wrong File Format, should be .txt or .csv"") + + def test_match_chr_to_genome(self): + """""" + Asserts that a pd.DataFrame object is returned from function. + """""" + dataframe = gi.file_extension(self.test_input) + self.assertTrue(isinstance(gi.match_chr_to_genome(dataframe, self.genome), pd.DataFrame)) + + + def test_flanking_regions_fasta(self): + """""" + Asserts that return object (list of tuples) first item is sample. + """""" + dataframe = gi.file_extension(self.test_input) + self.assertTrue((gi.create_flanking_regions_fasta\ + (self.genome, dataframe, 200)[0][0]).startswith('sample')) + + def tearDown(self): + pass + +if __name__ == '__main__': + unittest.main() +","Python" +"In Silico","stjude/PrimerTK","test/python_tests/test_analyze_pcr_output_sv.py",".py","2637","75","#!/usr/bin/env python3 + +"""""" +Module required for program. + - python3.6+ + - pandas >= 0.22.0 +"""""" + +import unittest +from primer_tk import analyze_pcr_output_sv as ap + +class TestAnalyzePcrOutputSV(unittest.TestCase): + """""" + Subclass of unittest to test analyze_pcr_output_sv.py + """""" + def setUp(self): + self.flanking = 'test/data/flanking_regions_sv.fasta' + self.primer_file = 'test/data/total_list_sv.csv' + self.seqs, self.headers = ap.fasta_parser(self.flanking) + self.positions = ap.amp_header_region(self.primer_file) + + def test_fasta_parser(self): + """""" + Ensure that seq and header are appropriately parsed. + """""" + self.assertEqual(len(self.seqs), 3) + self.assertEqual(len(self.headers), 3) + + def test_amp_header_region(self): + """""" + Extract header region from primer info file. + """""" + self.assertTrue(all(len(item) == 3 for item in self.positions)) + + def test_get_gc_region(self): + """""" + Extract gc actual sequence region between primers based on positions. + """""" + sliced_seqs = ap.get_gc_region(self.seqs, self.headers, self.positions) + self.assertTrue(all(len(item[2]) < 401 for item in sliced_seqs)) + def test_calc_gc(self): + """""" + Calculate the sample GC content for each sliced sequence. + """""" + sliced_seqs = ap.get_gc_region(self.seqs, self.headers, self.positions) + gc_calc = ap.calc_gc(sliced_seqs) + self.assertTrue(all(isinstance(item[2], float) for item in gc_calc)) + + def test_merge_dfs(self): + """""" + Merges calc_gc into the original dataframe for more + information about product length and gc content. + """""" + sliced_seqs = ap.get_gc_region(self.seqs, self.headers, self.positions) + gc_calc = ap.calc_gc(sliced_seqs) + self.assertEqual(len(ap.merge_dfs(gc_calc, self.primer_file, self.seqs).columns), 19) + self.assertEqual(len(ap.merge_dfs(gc_calc, self.primer_file, self.seqs)['Sequence ID']), 13) + + def test_to_order_plate(self): + """""" + Generates a plate order format for generated primers. + """""" + sliced_seqs = ap.get_gc_region(self.seqs, self.headers, self.positions) + gc_calc = ap.calc_gc(sliced_seqs) + merged = ap.merge_dfs(gc_calc, self.primer_file, self.seqs) + plate_order_sheet_f, plate_order_sheet_r = ap.to_order_plate(merged) + self.assertEqual(len(plate_order_sheet_f), 13) + self.assertEqual(len(plate_order_sheet_r), 13) + + def tearDown(self): + pass + +if __name__ == ""__main__"": + unittest.main() +","Python" +"In Silico","stjude/PrimerTK","test/python_tests/test_genome_iterator_sv.py",".py","6140","151","#!/usr/bin/env python3 +"""""" +Unit tester for genome_iterator_sv.py + +Python version: Python 3.6.8 :: Anaconda, Inc. +Date: 02/28/2019 +Dependencies: + - unittest + - pandas >= 0.22.0 +"""""" + +import unittest +import pandas as pd +from primer_tk import genome_iterator_sv as gi + +class TestGenomeIterator(unittest.TestCase): + """""" + Subclass of unittest to test genome_iterator_sv.py + """""" + def setUp(self): + self.ref_genome = ""test/data/test_sv.fa"" + self.genome = gi.genome_iterator(self.ref_genome) + self.test_input = 'test/data/input_sv.csv' + self.test_input2 = 'test/data/input_sv.txt' + self.test_input3 = 'test/data/input_sv.fa' + self.translocation_input1 = 'test/data/translocation_input.csv' + self.translocation_input2 = 'test/data/translocation_input.txt' + self.insertion_genome = gi.genome_iterator('test/data/insertion_test.fa') + self.insertion_input1 = 'test/data/insertion_input.csv' + self.insertion_input2 = 'test/data/insertion_input.txt' + + def test_genome_iterator(self): + """""" + Asserts object output by genome_iterator function has length of 2 (header, seq) + """""" + self.assertEqual(len(self.genome[0]), 2) + + def test_create_dataframe_csv(self): + """""" + Asserts that a pd.DataFrame is returned from function. + """""" + self.assertTrue(isinstance(gi.create_dataframe_csv(self.test_input), pd.DataFrame)) + + def test_create_dataframe_txt(self): + """""" + Asserts that a pd.DataFrame is returned from function. + """""" + self.assertTrue(isinstance(gi.create_dataframe_txt(self.test_input2), pd.DataFrame)) + + def test_create_dataframe_insertion_csv(self): + """""" + Asserts that proper insertion dataframe is returned from function. + """""" + self.assertEqual(len(gi.create_dataframe_insertion_csv(self.insertion_input1)),4) + + def test_create_dataframe_insertion_txt(self): + """""" + Asserts that proper insertion dataframe is returned from function. + """""" + self.assertEqual(len(gi.create_dataframe_insertion_txt(self.insertion_input2)),4) + def test_create_dataframe_translocation_csv(self): + """""" + Asserts that proper translocation dataframe is returned from function. + """""" + self.assertEqual(len(gi.create_dataframe_translocation_csv(self.translocation_input1)),4) + + def test_create_dataframe_translocation_txt(self): + """""" + Asserts that proper translocation dataframe is returned from function. + """""" + self.assertEqual(len(gi.create_dataframe_translocation_txt(self.translocation_input2)),4) + + def test_file_extension_insertion_success(self): + """""" + Asserts that proper df is created when sv type is insertion. + """""" + self.assertEqual(len(gi.file_extension(self.insertion_input1, 'insertion')),4) + + def test_file_extension_translocation_success(self): + """""" + Asserts that proper df is created when sv type is translocation. + """""" + self.assertEqual(len(gi.file_extension(self.translocation_input1, 'translocation')),4) + + def test_file_extension_deletion_success(self): + """""" + Asserts that a pd.DataFrame is returned only if file extension matches. + """""" + self.assertTrue(isinstance(gi.file_extension(self.test_input2, 'deletion'), pd.DataFrame)) + + def test_file_extension_inversion_success(self): + """""" + Asserts that a pd.DataFrame is returned only if file extension matches. + """""" + self.assertTrue(isinstance(gi.file_extension(self.test_input2, 'inversion'), pd.DataFrame)) + + def test_file_extension_failure(self): + """""" + Asserts that code exits with warning message if file extension or sv is incorrect. + """""" + with self.assertRaises(SystemExit) as code_message: + gi.file_extension(self.test_input3, 'deletion') + self.assertEqual(code_message.exception.code, + ""Wrong File Format, should be .txt (tab) or .csv (comma), or check sv type."") + + def test_match_chr_to_genome(self): + """""" + Asserts that a pd.DataFrame object is returned from function. + chr format is mismatched between genome and input file, checks for conversion. + """""" + dataframe = gi.file_extension(self.test_input2, 'deletion') + self.assertTrue(isinstance(gi.match_chr_to_genome(dataframe, self.genome, 'deletion'), pd.DataFrame)) + + def test_match_chr_to_genome_insertion(self): + """""" + Asserts that input file with format chr1 is converted to 1 to match ref genome. + """""" + dataframe = gi.file_extension(self.insertion_input1, 'insertion') + self.assertFalse(gi.match_chr_to_genome(dataframe, self.insertion_genome, 'insertion')\ + [""ChrNorm""].str.contains(""chr"").any()) + + def test_flanking_regions_fasta_deletion(self): + """""" + Asserts that return object (list of tuples) first item is sample. + """""" + dataframe = gi.file_extension(self.test_input, 'deletion') + self.assertTrue((gi.flanking_regions_fasta_deletion\ + (self.genome, dataframe, 10)[0][0]).startswith('sample')) + + def test_flanking_regions_fasta_translocation(self): + """""" + Asserts that translocations are handled properly for both forward and reverse strand translocations. + """""" + dataframe = gi.file_extension(self.translocation_input2, 'translocation') + flanking = gi.flanking_region_fasta_translocation(self.insertion_genome, dataframe, 5) + self.assertTrue(len(flanking) == 4) + + def test_flanking_regions_fasta_insertion(self): + """""" + Asserts that insertions are handled properly for both forward and reverse strand insertions. + """""" + dataframe = gi.file_extension(self.insertion_input2, 'insertion') + flanking = gi.flanking_region_fasta_insertion(self.insertion_genome, dataframe, 5) + self.assertTrue(len(flanking) == 8) + + def tearDown(self): + pass + +if __name__ == '__main__': + unittest.main() +","Python" +"In Silico","stjude/PrimerTK","test/python_tests/test_mp_class_sv.py",".py","2310","74","#!/usr/bin/env python3 +"""""" +Unit tester for mp_class_sv.py + +Python version: Python 3.6.8 :: Anaconda, Inc. +Dependencies: + - unittest + - pandas >= 0.22.0 +"""""" + +import unittest +import pandas as pd +from primer_tk.mp_class_sv import MissingPrimers +from primer_tk.mp_class_sv import create_df + +class TestMpClassSV(unittest.TestCase): + """""" + Subclass of unittest to test mp_class_sv.py + """""" + def setUp(self): + self.mp = MissingPrimers(""test/data/primer_dump_sv.txt"", 1) + + def test_group_seqids(self): + """""" + Asserts proper list is generated for given number of sample values. + """""" + self.assertEqual(len(self.mp._MissingPrimers__group_seqids()), 3) + + def test_group_seqids_unfilled(self): + """""" + Tests to ensure NA values have not been inserted into primer3 string. + """""" + no_missing_vals = self.mp._MissingPrimers__group_seqids()[1] + self.assertFalse(""NA"" in no_missing_vals) + + def test_fill_empty_values(self): + """""" + Tests to ensure that NA vals have been inserted into samples with missing primers. + """""" + all_params = self.mp._MissingPrimers__fill_empty_values() + missing_params = all_params[1] + self.assertTrue(""=NA"" in missing_params[-2]) + + def test_gather_primer_info(self): + """""" + Test to ensure that if 1 value is passed, all sample names + end with 1. Ex: SampleABC1 + """""" + primer_info = self.mp._MissingPrimers__gather_primer_info() + self.assertTrue(all(item[0].endswith('1') for item in primer_info)) + + def test_len_list_output(self): + """""" + Tests to ensure the proper number of params have been kept from the p3 output. + Slightly longer than normal output because coordinate positions are kept for downstream. + """""" + prim_list_1 = self.mp.samp_primer_info + for sample_data in prim_list_1: + self.assertEqual(len(sample_data), 10) + + def test_create_df(self): + """""" + Tests to ensure a df is created from primer list. + """""" + prim_list_1 = self.mp.samp_primer_info + primer_df = create_df([prim_list_1]) + self.assertTrue(isinstance(primer_df, pd.DataFrame)) + + def tearDown(self): + pass + +if __name__ == '__main__': + unittest.main() +","Python" +"In Silico","stjude/PrimerTK","test/python_tests/test_sequence_info.py",".py","3413","113","#!/usr/bin/env python3 +"""""" +Unit tester for sequence_info.py + +Python version: Python 3.6.8 :: Anaconda, Inc. +Date: 03/22/2019 +Dependencies: + - unittest + - biopython>=1.70 +"""""" + +import unittest +from primer_tk import sequence_info as seqinf + +class TestSequence(unittest.TestCase): + """""" + Subclass of unittest to test Sequence Class for sequence_info.py + """""" + def setUp(self): + """""" + Generate a sequence object that is easy to test! + """""" + self.seq = seqinf.Sequence(""ACTG"") + self.name = ""seq name not seq"" + self.primer_dimer = seqinf.PrimerDimer(self.seq.sequence, + seqinf.Sequence(""TGCA"").sequence, 2) + + def test_handles_lowercase(self): + """""" + Tests to ensure handles lowercase sequence strings. + """""" + input_seq = self.seq.sequence + test_seq = seqinf.Sequence('actg').sequence + self.assertEqual(input_seq, test_seq) + + def test_set_name(self): + """""" + Tests that name is properly changed when function is called. + """""" + self.name = ""TestSeq1"" + self.assertEqual(self.name, ""TestSeq1"") + + def test_complement(self): + """""" + Tests to ensure that sequence complement is returned. + """""" + complement_seq = self.seq.complement() + self.assertEqual(complement_seq, ""TGAC"") + + def test_reverse_complement(self): + """""" + Tests to ensure that reverse complement sequence is returned. + """""" + reverse_complement_seq = self.seq.reverse_complement() + self.assertEqual(reverse_complement_seq, ""CAGT"") + + def test_reverse_sequence(self): + """""" + Tests to ensure that the sequence is properly reversed. + """""" + reverse_seq = self.seq.reverse_sequence() + self.assertEqual(reverse_seq, ""GTCA"") + + + def test_gc_percent(self): + """""" + Test to ensure that GC is properly calculated. + """""" + gc_float = self.seq.gc_percent() + self.assertEqual(gc_float, 50.0) + + def test_0_gc_percent(self): + """""" + Test to ensure that 0 GC doesn't throw error (div0). + """""" + gc_float = seqinf.Sequence(""AAAA"").gc_percent() + self.assertEqual(gc_float, 0.0) + + def test_pd_local(self): + """""" + Test to ensure pd_local is aligning exact sequences. + ACTG & TGCA align at length 2, this is our test. + Example: + ACTG + --|| + TGCA + """""" + local = self.primer_dimer.pd_local() + self.assertEqual([item[2] for item in local], [2.0]) + + def test_format_comp_align(self): + """""" + Test to ensure that complementary alignment is output. + """""" + easy_seq1 = seqinf.Sequence(""AAAA"").sequence + easy_seq2 = seqinf.Sequence(""TTTT"").complement() + test = seqinf.PrimerDimer(easy_seq1, easy_seq2, 4) + local = test.pd_local() + for item in local: + self.assertTrue(""TTTT"" in seqinf.PrimerDimer.\ + format_alignment_compl(item[0], + item[1], + item[2], + item[3], + item[4])) + + + def tearDown(self): + pass + +if __name__ == '__main__': + unittest.main() +","Python" +"In Silico","stjude/PrimerTK","test/python_tests/test_mp_class.py",".py","3367","103","#!/usr/bin/env python3 +"""""" +Unit tester for mp_class.py + +Python version: Python 3.6.8 :: Anaconda, Inc. +Date: 03/20/2019 +Dependencies: + - unittest + - pandas>=0.22.0 + - numpy>=1.16.0 +"""""" + +import unittest +import pandas as pd +import numpy as np +from primer_tk.mp_class import MissingPrimers +from primer_tk.mp_class import create_df + +class TestMissingPrimers(unittest.TestCase): + """""" + Subclass of unittest to test mp_class.py + """""" + def setUp(self): + self.mp = MissingPrimers(""test/data/primer_dump_standard.txt"", 1) + + def test_group_seqids(self): + """""" + Creates a list of lists, each sample info is stored in its own list + within a list. Since there were 3 samples, the length of the list + should be 3. + """""" + self.assertEqual(len(self.mp._MissingPrimers__group_seqids()), 3) + + def test_group_seqids_unfilled(self): + """""" + Tests to ensure that NA values have not been inserted into + primer3 string. + """""" + no_missing_vals = self.mp._MissingPrimers__group_seqids()[1] + self.assertFalse(""NA"" in no_missing_vals) + + def test_fill_empty_values(self): + """""" + Tests to ensure that NA values have been inserted into the + sample with missing primers. + """""" + all_params = self.mp._MissingPrimers__fill_empty_values() + missing_params = all_params[1] + self.assertTrue(""=NA"" in missing_params[-2])#-1 is empty space + + def test_gather_primer_info(self): + """""" + Test to ensure that if value 1 is passed, all sample names + end with 1. + """""" + primer_info = self.mp._MissingPrimers__gather_primer_info() + self.assertTrue(all(item[0].endswith('1') for item in primer_info)) + + def test_invalid_value(self): + """""" + Tests to ensure class does not succeed if invalid value is passed. + Value options are currently [0-4]. + """""" + with self.assertRaises(SystemExit) as code_message: + MissingPrimers(""primer_dump_standard.txt"", 6) + self.assertEqual(code_message.exception.code, + ""Improper value selected! Acceptable values: 0,1,2,3,4."") + + + def test_len_list_output(self): + """""" + Tests to ensure that the list created for each sample contains 8 values. + This corresponds to the number of df columns. + """""" + prim_list_1 = self.mp.samp_primer_info + for sample_data in prim_list_1: + self.assertEqual(len(sample_data), 8) + + def test_create_df(self): + """""" + Tests to ensure that a df is created from primer list + and contains the proper number of rows. + """""" + prim_list_1 = self.mp.samp_primer_info + primer_df = create_df([prim_list_1]) + self.assertEqual(len(primer_df), 3) + + def test_accept_multiple_prim_lists(self): + """""" + Tests to ensure that a mp_class.create_df() can accept multiple primer lists + as input and generate an output df. + """""" + prim_list_1 = self.mp.samp_primer_info + prim_list_2 = MissingPrimers(""test/data/primer_dump_standard.txt"", 2).samp_primer_info + primer_df = create_df([prim_list_1, prim_list_2]) + self.assertEqual(len(primer_df), 6) + + def tearDown(self): + pass + +if __name__ == '__main__': + unittest.main() +","Python" +"In Silico","stjude/PrimerTK","test/python_tests/test_analyze_pcr_output.py",".py","4066","118","#!/usr/bin/env python3 + +"""""" +Modules required for program. + - python3.6+ + - pandas >= 0.22.0 + - sequence_info +"""""" + +import unittest +import pandas as pd +from primer_tk import analyze_pcr_output as ap + +class TestAnalyzePcrOutput(unittest.TestCase): + """""" + Subclass of unittest to test analyze_pcr_output.py + """""" + def setUp(self): + self.pcr_file = 'test/data/pcr_standard.fa' + self.primer_file = 'test/data/total_primers_standard.csv' + self.seqs, self.headers = ap.fasta_parser(self.pcr_file) + self.gc_list = ap.gc_percent_seqs(self.seqs) + self.split_headers, self.no_chrom = ap.split_headers_list(self.headers) + self.chr_list = ap.chr_split_list(self.split_headers) + self.pos_list = ap.pos_split_list(self.chr_list) + self.name_pos_split_list = ap.split_name_pos(self.no_chrom) + for item in self.chr_list: + del item[-1] + self.merged = ap.merge_info(self.chr_list, self.pos_list, + self.name_pos_split_list, + self.no_chrom) + self.pcr_df, self.good_primers, self.bad_primers = ap.generate_pcr_df(self.merged, + self.gc_list) + self.merged_df = ap.merge_good_total(self.good_primers, self.primer_file) + self.filtered = ap.filter_merged(self.merged_df, 1) + + def test_fasta_parser(self): + """""" + Ensure that seq and header are proper length. + """""" + seqs, headers = ap.fasta_parser(self.pcr_file) + self.assertTrue(len(seqs[0][0]) == 306) + self.assertTrue(len(headers[0]) == 98) + + def test_gc_percent_seqs(self): + """""" + Calcs gc percent of list of seqs + """""" + self.assertEqual(int(ap.gc_percent_seqs(self.seqs)[0]), 49) + + def test_split_headers_list(self): + """""" + Split header information and return tuple of parsed header info. + """""" + self.assertTrue(len(ap.split_headers_list(self.headers)[0][0]) > + len(ap.split_headers_list(self.headers)[1][0])) + + def test_chr_split_list(self): + """""" + Parses chrm and position out of headers list. + """""" + self.assertEqual(ap.chr_split_list(self.split_headers)[0][0], '1') + + def test_split_name_pos(self): + """""" + Gets the expected position of the snp. + """""" + self.assertEqual(ap.split_name_pos(self.no_chrom)[0][0], '15000000') + + def test_merge_info(self): + """""" + Merges all the info extracted from the fasta files. + """""" + self.assertEqual(len(ap.merge_info(self.chr_list, self.pos_list, + self.name_pos_split_list, + self.no_chrom)[0]), 8) + + def test_generate_pcr_df_off_target(self): + """""" + Creates a df from all info. + """""" + pcr_df, good_primers, bad_primers = ap.generate_pcr_df(self.merged, self.gc_list) + self.assertEqual(len(pcr_df), 2) + self.assertEqual(len(good_primers), 1) + self.assertEqual(len(bad_primers), 1) + + def test_merge_good_total(self): + """""" + Merges pcr df with total primers df. + """""" + self.assertEqual(len(ap.merge_good_total(self.good_primers, self.primer_file)), 12) + + def test_filter_merged(self): + """""" + Drops off target products. + """""" + self.assertEqual(len(ap.filter_merged(self.merged_df, 0)), 0) + + def top_ranked_final_primers(self): + """""" + Selects the top ranking primer pair from each target. + """""" + self.assertEqual(len(ap.top_ranked_final_primers(self.filtered)), 1) + + def test_to_order_plate(self): + """""" + Generates a ready made primer ordering sheet. + """""" + forward, reverse = ap.to_order_plate(self.filtered) + self.assertEqual(len(forward.columns), 3) + self.assertEqual(len(forward), 1) + + def tearDown(self): + pass + +if __name__ == ""__main__"": + unittest.main() +","Python" +"In Silico","stjude/PrimerTK","test/python_tests/test_primer_cross_hyb.py",".py","3397","90","#!/usr/bin/env python3 + +"""""" +Modules required for program. + - python3.6+ + - pandas>=0.22.0 + - argparse + - primer_cross_hyb + - sequence_info +"""""" + +import unittest +from io import StringIO +import argparse +from primer_tk.mp_class import MissingPrimers +from primer_tk.mp_class import create_df +from primer_tk import primer_cross_hyb as pch + +class TestPrimerCrossHyb(unittest.TestCase): + """""" + Subclass of unittest to test primer_cross_hyb.py + """""" + def setUp(self): + """""" + Setup for tests, need to generate df as all scripts in this operate + on a dataframe. self.primer_df is called twice to drop NA. + """""" + self.dump = ""test/data/primer_dump_standard.txt"" + prim_list_0 = MissingPrimers(self.dump, 0).samp_primer_info + prim_list_1 = MissingPrimers(self.dump, 1).samp_primer_info + prim_list_2 = MissingPrimers(self.dump, 2).samp_primer_info + prim_list_3 = MissingPrimers(self.dump, 3).samp_primer_info + prim_list_4 = MissingPrimers(self.dump, 4).samp_primer_info + self.primer_df = create_df([prim_list_0, prim_list_1, prim_list_2, + prim_list_3, prim_list_4]) + self.primer_df = self.primer_df.loc[~(self.primer_df['Primer Left Seq'] == 'NA')] + self.pa = 50 + self.fp_len = pch.get_fprimer_percent_aln(self.primer_df['Primer Left Seq'], self.pa) + self.pd_compare_1_2 = pch.primer_dimer_local(self.fp_len, self.primer_df['Sequence ID'], + self.primer_df['Primer Left Seq'], + self.primer_df['Primer Right Seq']) + + + + def test_get_fprimer_percent_aln(self): + """""" + Tests to ensure that the proper forward primer length is returned for + the given percent alignment. + primer lengths input = [22, 22, 22, 22, 21, 22, 24, 22, 22, 22, 22, 24] + Should return = [11, 11, 11, 11, 10, 11, 12, 11, 11, 11, 11, 12] + """""" + self.assertEqual(self.fp_len, [11, 11, 11, 11, 10, 11, 12, 11, 11, 11, 11, 12]) + + + def test_primer_dimer_local(self): + """""" + For percent alignment == 50, this set of primers should contain 17 dimers in + forward primer vs reverse primer comparison. + """""" + self.assertEqual(len(list(self.pd_compare_1_2)), 17) + + def test_list_from_gen(self): + """""" + Tests to ensure list is generated from primer_dimer_local output. + """""" + self.assertTrue(isinstance(pch.list_from_gen(self.pd_compare_1_2), list)) + + def test_p_list_formatter(self): + """""" + Tests to ensure that output list is formatted properly. + """""" + pd_list = pch.list_from_gen(self.pd_compare_1_2) + formatted = pch.p_list_formatter(pd_list) + self.assertFalse(any('\\n' in x for x in formatted)) + + def test_dimer_true(self): + """""" + Tests to ensure that exactly 3 dimers are found between forward and reverse primers. + """""" + pd_list = pch.list_from_gen(self.pd_compare_1_2) + formatted = pch.p_list_formatter(pd_list) + self.primer_df['Dimers1_2F'] = pch.dimer_true(self.primer_df, 2, formatted) + self.assertEqual((self.primer_df['Dimers1_2F'][self.primer_df['Dimers1_2F'] == True].count()), 3) + + def tearDown(self): + pass + +if __name__ == '__main__': + unittest.main() +","Python" +"In Silico","stjude/PrimerTK","test/python_tests/test_primer_tabix.py",".py","5123","111","#!/usr/bin/env python3 +"""""" +Unit tester for primer_tabix.py + +Python version: Python 3.6.8 :: Anaconda, Inc. +Dependencies: + - unittest + - pandas >= 0.22.0 + - pysam >= 0.15.2 +"""""" + +import unittest +import pandas as pd +from pysam import VariantFile +from primer_tk import primer_tabix as pt + +class TestPrimerTabix(unittest.TestCase): + """""" + Subclass of unittest to test primer_tabix.py + """""" + def setUp(self): + self.primer_output = ""test/data/top_ranked_final_primers_standard.csv"" + self.vcf_test = 'test/data/primer_test_vcf.csv' + self.pinfo = pt.create_tabix_df(self.primer_output) + self.pvcf = pt.create_tabix_df(self.vcf_test) + self.vcf = 'test/data/smallvcf.vcf.gz' + self.vcf_in = VariantFile(self.vcf) + + def test_create_tabix_df(self): + """""" + Test dataframe creation. + """""" + self.assertTrue(isinstance(pt.create_tabix_df(self.primer_output), pd.DataFrame)) + + def test_primer_range_left(self): + """""" + Test the range info is added to the dataframe. + """""" + self.assertEqual(len(pt.primer_range_left(self.pinfo['Sequence ID'], self.pinfo['Primer Rank'], + self.pinfo['Chromosome'], self.pinfo['Primer Left Seq'], + self.pinfo['Position1']).columns), 6) + def test_primer_range_right(self): + """""" + Test the range info is added to the dataframe. + """""" + self.assertEqual(len(pt.primer_range_left(self.pinfo['Sequence ID'], self.pinfo['Primer Rank'], + self.pinfo['Chromosome'], self.pinfo['Primer Right Seq'], + self.pinfo['Position2']).columns), 6) + + def test_match_pinfo_to_vcf(self): + """""" + Normalizes the chr string to the reference vcf. + """""" + self.assertFalse(pt.match_pinfo_to_vcf(self.pinfo, self.vcf_in)['Chromosome'].str.contains(""chr"").any()) + + def test_tabix_fetch(self): + """""" + Fetches snp info and assigns to primers. + """""" + left = pt.primer_range_left(self.pvcf['Sequence ID'], self.pvcf['Primer Rank'], + self.pvcf['Chromosome'], self.pvcf['Primer Left Seq'], + self.pvcf['Position1']) + normalized = pt.match_pinfo_to_vcf(left, self.vcf_in) + left_snps = pt.tabix_fetch(normalized['Sequence ID'], normalized['Primer Rank'], + normalized['Chromosome'], normalized['Position1'], + normalized['Position2'], self.vcf_in) + self.assertEqual(len(left_snps), 20) + + def test_tabix_results_to_df(self): + """""" + Generates a pd.DataFrame from the tabix results. + """""" + left = pt.primer_range_left(self.pvcf['Sequence ID'], self.pvcf['Primer Rank'], + self.pvcf['Chromosome'], self.pvcf['Primer Left Seq'], + self.pvcf['Position1']) + normalized = pt.match_pinfo_to_vcf(left, self.vcf_in) + left_snps = pt.tabix_fetch(normalized['Sequence ID'], normalized['Primer Rank'], + normalized['Chromosome'], normalized['Position1'], + normalized['Position2'], self.vcf_in) + left_df = pt.tabix_results_to_df(left_snps, ""L"", ""Left SNP Count"") + self.assertEqual(left_df['Left SNP Count'][0], 10) + + def test_merge_left_right(self): + """""" + Merge the left and right SNP dataframes. + """""" + left = pt.primer_range_left(self.pvcf['Sequence ID'], self.pvcf['Primer Rank'], + self.pvcf['Chromosome'], self.pvcf['Primer Left Seq'], + self.pvcf['Position1']) + normalized = pt.match_pinfo_to_vcf(left, self.vcf_in) + left_snps = pt.tabix_fetch(normalized['Sequence ID'], normalized['Primer Rank'], + normalized['Chromosome'], normalized['Position1'], + normalized['Position2'], self.vcf_in) + left_df = pt.tabix_results_to_df(left_snps, ""L"", ""Left SNP Count"") + right = pt.primer_range_right(self.pvcf['Sequence ID'], self.pvcf['Primer Rank'], + self.pvcf['Chromosome'], self.pvcf['Primer Right Seq'], + self.pvcf['Position2']) + normalized = pt.match_pinfo_to_vcf(right, self.vcf_in) + right_snps = pt.tabix_fetch(normalized['Sequence ID'], normalized['Primer Rank'], + normalized['Chromosome'], normalized['Position1'], + normalized['Position2'], self.vcf_in) + right_df = pt.tabix_results_to_df(left_snps, ""R"", ""Right SNP Count"") + merged_df = pt.merge_left_right(left_df, right_df, self.pvcf) + self.assertTrue('Left SNP Count' and 'Right SNP Count' in merged_df.columns) + + def tearDown(self): + pass + +if __name__ == '__main__': + unittest.main() +","Python" +"In Silico","stjude/PrimerTK","test/python_tests/test_core.py",".py","460","29","#!/usr/bin/env python3 +"""""" +Unit tester for core.py + +Dependencies: + - python3.6+ + - unittest + - pandas >= 0.22.0 +"""""" + +import unittest +import pandas as pd +from primer_tk import core + +class TestCoreSV(unittest.TestCase): + """""" + Test all core functions for SV pipeline. + """""" + def setUp(self): + """""" + Inputs for each function. + """""" + pass + def tearDown(self): + pass + +if __name__ == ""__main__"": + unittest.main() +","Python" +"In Silico","stjude/PrimerTK","docs/cwl.md",".md","22","1","# This is coming soon!","Markdown" +"In Silico","stjude/PrimerTK","docs/introduction.md",".md","5119","63","## Introduction to PrimerTK + +The Primer ToolKit (PrimerTK) seeks to alleviate several of the challenges of primer design such as thermodynamic considerations, avoiding repeats, GC content, and length using a simple, fast, and powerful workflow that will enable users to generate high quality primers for large sets of samples. The workflow for primer generation follows the following design: + +``` + + ######################## #################### ############################ + # input positions file # # reference genome # # thermodynamic parameters # + ######################## #################### ############################ + | | | | | | + | | | + | | | + | | | + | | | + | | | + | | | + ################################################### + # Primer3 Primer Generation and Scoring + Ranking # + ################################################### + | + | + | + | + ################################################### + # Primer3 output parsing + PCR Setup # + # Optional Multiplexing and filtering primers # + ################################################### + | + | + | + | + ################################################### + # In Silico PCR off target amplification checks # + ################################################### + | + | + | + | + ################################################### + # Filter off target products, return primer # + # thermodynamics and pcr product results and # + # top ranking final primers by position # + ################################################### + | | | + | | | + | | | + ################# | ##################### + # Top Primers # | # Plate Order Sheet # + ################# | ##################### + | + | + | + ################################################### + # Annotate all primers with SNPs using tabix # + ################################################### +``` + +This is a general design schematic of the workflow, more in depth discussion will be covered in each walkthrough: + +* [standard and multiplex tutorial](standard_and_multiplex.md) +* [structural variants](structural_variants.md) + +Next, proceed to [installation](installation.md).","Markdown" +"In Silico","stjude/PrimerTK","docs/installation.md",".md","4850","146","## Installation for PrimerTK and third party software + +The easiest way to install PrimerTK is to clone the github repository. This is because the repository contains template scripts for input files, a helper script to run in silico pcr, and a helper script to install primer3 and in silico pcr. + +To clone the repo in your current working directory: + +``` +# https +git clone https://github.com/stjude/PrimerTK.git + +# git +git clone git@github.com:stjude/PrimerTK.git +``` + +Once it is cloned, you can change to the directory and see what is inside: + +``` +cd PrimerTK +ls +``` + +This will show the directories `cwl`, `scripts`, `src/primer_tk`, `input_templates`, and `test`. If you read the [introduction](introduction.md), you will know that cwl is a workflow language that will operate the entire pipeline for you after all programs have been installed and are in your `PATH` environment variable. + +`input_templates` is just a helper directory for you to see what input files should look like for the program. + +To install the python source code to your local python3 using the git copy (assuming you are still in the PrimerTK directory): + +``` +# to your user python3 +pip3 install . --user + +# to root python3 +pip3 install . +``` + +This will install the PrimerTK python code. To check for a proper installation, you can type `primer_tk -h` in the command line which will return: + +``` +usage: primer_tk [-h] [-v] + {iterator,iterator_sv,pre,pre_sv,post,post_sv,tabix} ... + +positional arguments: + {iterator,iterator_sv,pre,pre_sv,post,post_sv,tabix} + Actions + iterator Iterator subparser + iterator_sv iterator_sv subparser + pre Preprocessing for snv/indel + pre_sv Preprocessing for SV's + post Parses info from pcr_output + post_sv Parses info from pcr_output + tabix Tabix subparser + +optional arguments: + -h, --help show this help message and exit + -v, --version show program's version number and exit +``` + +Upon proper installation. + +To install third party software, change into the scripts directory and open `installer.sh` with your favorite text editor and remove all commented lines in between text boxes so the file looks like this: + +```bash +# +# Third party tools Primer3 (TODO: Link), available under GNU GPLv2, and In Silico PCR +# (TODO: Link) are needed for PrimerTK to work properly. We do not include those third +# party tools alongside the PrimerTK software. However, the following commands were +# used to install the software as of the time of PrimerTK's release. + +# Uncomment all code in between boxes to install + +########### +# Primer3 # +########### + +############################################################# +# Select the installation directory and make sure it exists.# +############################################################# + +PRIMER3_INSTALL_DIR=~/bin/ +mkdir -p $PRIMER3_INSTALL_DIR + +##################################################################### +# Make a tmp location to download / install the source # +# we need the whole source to run the program. There are configs in # +# primer3_config that are referenced for thermodynamic params # +##################################################################### + +TMPDIR=$(mktemp -d) +echo $TMPDIR +cd $TMPDIR +git clone https://github.com/primer3-org/primer3.git primer3 +cd ./primer3/src +make + +#################################### +# Copy the appropriate executables # +#################################### + +cp -rf $TMPDIR/primer3 $PRIMER3_INSTALL_DIR + +rm -rf $TMPDIR + +######### +# isPCR # +######### + +ISPCR_EXECUTABLE_DIR=~/bin/isPcr33 +mkdir -p $ISPCR_EXECUTABLE_DIR +MACHTYPE=$(uname -m) +export MACHTYPE +ISPCR33_INSTALL_DIR=~/bin/$MACHTYPE +mkdir -p $ISPCR33_INSTALL_DIR + +TMPDIR2=$(mktemp -d) +echo $TMPDIR2 +cd $TMPDIR2 +wget https://hgwdev.gi.ucsc.edu/~kent/src/isPcr33.zip && unzip isPcr33.zip 1> .unzip.out 2> .unzip.err +mkdir ./isPcrSrc/lib/$MACHTYPE +cd $TMPDIR2/isPcrSrc/lib && make HG_WARN="""" +cd $TMPDIR2/isPcrSrc && make HG_WARN="""" +cp $ISPCR33_INSTALL_DIR/isPcr $ISPCR_EXECUTABLE_DIR +rm -rf $ISPCR33_INSTALL_DIR +rm -rf $TMPDIR2 + +################# +# END INSTALLER # +################# +``` + +primer3 and isPcr will now be in `~/bin/`. + +I would recommend adding them to your `PATH` variable as they should not conflict with other programs. + +You can do this manually every time you run the program, or you can add it to your `.bashrc` + +To do it manually: + +``` +export PATH=~/bin/primer3/src/:$PATH +export PATH=~/bin/isPcr33/:$PATH +``` + +Or correspondingly you can add the same two lines of code to your `~/.bashrc` and these will both be added to your `PATH` when you login to your account. + +This will complete the installation. Next, visit [inputs](inputs.md) to see the structure of the various input files. +","Markdown" +"In Silico","stjude/PrimerTK","docs/structural_variants.md",".md","15784","335","# Structural Variants Tutorial + +The possible structural variants to design primers around are insertions, deletions, translocations, and inversions. These have a slightly different file format than the Standard and Multiplex inputs, and insertion + translocation are different than deletion + inversion. To view input file specifications, check out the [inputs page](inputs.md). + +Although the input files are different, the pipeline inputs and outputs are the same for all SV's, so I will just perform the tutorial with a deletion. +The steps of the pipeline are also quite similar to the [Standard and Multiplex Tutorial](standard_and_multiplex.md), so if you have performed that one already, this may seem more straightforward to you. + +This pipeline just parses sequences from the reference genome based on the coordinates in the inputs. If the SV type is a bit more complex than a deletion, such as an insertion of the - strand to the + strand of the normal chromosome, some more complex string manipulation is done when designing the positional flanking sequences. + +*NOTE: THERE IS CURRENTLY NO OPTION TO MULTIPLEX SV'S ALTHOUGH THIS COULD BE ADDED IN A LATER RELEASE IF DESIRED.* + +If you followed the installation page and git cloned the repo, there is a directory called `test` in the PrimerTK repo. This is for code testing but it also has data for the user to implement the full pipeline (testing is good). + +For the SV workflow, only primer3 needs to be added to your path. If you followed standard installation and added it to your .bashrc, you can skip this. If not: + +``` +export PATH=~/bin/primer3:$PATH +``` + +Or add the above to your ~/.bashrc to prevent this in the future. Now check ot make sure `primer_tk` and `primer3_core` are accessible via the command line anywhere in your system. + +## 0) Input File Examples + +It is important to note that each translocation type as its own input file format. I will display a csv example of each with a brief explanation: + +deletion.csv, inversion.csv: +``` +gene1,sample1,1,100,500 +gene2,sample2,1,1000000,2000000 +``` +Deletions and inversions are expected to take place in a defined region, therefore the csv file columns are the same. + +columns: + + - column1: an arbitrary name for the position (I put gene but you can call it whatever you want). + - column2: another name, this time sample, that way if the same sample has multiple regions you can differentiate. + - column3: chromosome + - column4: sv start + - column5: sv stop + + +translocation.csv: +``` +gene1,sample1,1,1000000,+,2,2000000,+ +gene1,sample1,1,1000000,+,2,2000000,- +gene1,sample1,1,1000000,-,2,2000000,+ +gene1,sample1,1,1000000,-,2,2000000,- +``` +columns: + + - column3: the chromosome that is being translocated. + - column4: the position the translocation event starts + - column5: the strand being translocated + - column6: the chromosome receiving the translocation + - column7: the position it is starting + - column8: which strand the sequence is translocating onto + +Consider these situations from the above (all circumstances): +``` +(+)SeqZ: (+)SeqM: output (++): + +ZZZZZZZZZZZ MMMMMMMMMMM MMMMMMZZZZZ +zzzzzzzzzzz mmmmmmmmmmm mmmmmmmmmmm + +(+)SeqZ: (-)SeqM: output (+-): + +ZZZZZZZZZZZ MMMMMMMMMMM MMMMMMMMMMM +zzzzzzzzzzz mmmmmmmmmmm ZZZZZmmmmmm + +(-)SeqZ: (+)SeqM: output (-+): + +ZZZZZZZZZZZ MMMMMMMMMMM MMMMMMzzzzz +zzzzzzzzzzz mmmmmmmmmmm mmmmmmmmmmm + +(+)SeqZ: (-)SeqM: output (--): + +ZZZZZZZZZZZ MMMMMMMMMMM MMMMMMMMMMM +zzzzzzzzzzz mmmmmmmmmmm zzzzzmmmmmm +``` +So this gives us a brief diagram that we can always expect the translocated sequence to be going from 5' -> 3' and all sequence manipulation to generate the proper primers is handled for you. + +insertion.csv: +``` +gene1,sample1,1,1000000,1005000,+,2,2000000,2005000,- +``` + +columns: + + - column3: chr of sequence being inserted + - column4: start position of sequence being inserted + - column5: stop position of sequence being inserted + - column6: strand of sequence being inserted + - column7: chr where insertion is + - column8: start position on chr where insertion is + - column9: stop position on chr where insertion is + - column10: strand where the sequence is being inserted + +A pair of primers is generated for each insertion breakpoint by the same logic used in the translocation. + +## 1) Setup a tutorial directory called sv_tutorial with files from test + +I will do everything in a directory called sv_tutorial: + +``` +mkdir -p ~/sv_tutorial/ + +cd ~/sv_tutorial/ +cp ~/PrimerTK/test/data/humrep.ref . +cp ~/PrimerTK/test/data/test_standard.fa . +cp ~/PrimerTK/test/data/input_sv.csv . +``` + +## 2) Start running the program + +Then let;s start running the program. Step 1 is called `iterator_sv` and it has a lot of inputs, but that is just because I wanted to give users a lot of flexibility on thermodynamic parameters for primer3. + +Let's display the help message and explain the parameters: + +``` + +primer_tk iterator_sv -h +usage: primer_tk iterator_sv [-h] -ref REF_GENOME -in REGIONS_FILE + [-opt_size PRIMER_OPT_SIZE] + [-min_size PRIMER_MIN_SIZE] + [-max_size PRIMER_MAX_SIZE] + [-opt_gc PRIMER_OPT_GC] [-min_gc PRIMER_MIN_GC] + [-max_gc PRIMER_MAX_GC] [-opt_tm PRIMER_OPT_TM] + [-min_tm PRIMER_MIN_TM] [-max_tm PRIMER_MAX_TM] + [-sr PRODUCT_SIZE_RANGE] + [-flank FLANKING_REGION_SIZE] + [-st SEQUENCE_TARGET] -mp MISPRIMING -tp + THERMOPATH -sv {deletion,inversion,insertion,translocation} + +optional arguments: + -h, --help show this help message and exit + -ref REF_GENOME, --ref_genome REF_GENOME + Reference Genome File to design primers around + -in REGIONS_FILE, --regions_file REGIONS_FILE + File with regions to design primers around + -opt_size PRIMER_OPT_SIZE, --primer_opt_size PRIMER_OPT_SIZE + The optimum primer size for output, default: 22 + -min_size PRIMER_MIN_SIZE, --primer_min_size PRIMER_MIN_SIZE + The optimum primer size for output, default: 18 + -max_size PRIMER_MAX_SIZE, --primer_max_size PRIMER_MAX_SIZE + The optimum primer size for output, default: 25 + -opt_gc PRIMER_OPT_GC, --primer_opt_gc PRIMER_OPT_GC + Optimum primer GC, default: 50 + -min_gc PRIMER_MIN_GC, --primer_min_gc PRIMER_MIN_GC + Minimum primer GC, default: 20 + -max_gc PRIMER_MAX_GC, --primer_max_gc PRIMER_MAX_GC + Maximum primer GC, default: 80 + -opt_tm PRIMER_OPT_TM, --primer_opt_tm PRIMER_OPT_TM + Optimum primer TM, default: 60 + -min_tm PRIMER_MIN_TM, --primer_min_tm PRIMER_MIN_TM + minimum primer TM, default: 57 + -max_tm PRIMER_MAX_TM, --primer_max_tm PRIMER_MAX_TM + maximum primer TM, default: 63 + -sr PRODUCT_SIZE_RANGE, --product_size_range PRODUCT_SIZE_RANGE + Size Range for PCR Product, default=200-400 + -flank FLANKING_REGION_SIZE, --flanking_region_size FLANKING_REGION_SIZE + This value will select how many bases up and + downstream to count when flanking SNP (will do 200 up + and 200 down), default: 200 + -st SEQUENCE_TARGET, --sequence_target SEQUENCE_TARGET + default: 199,1, should be half of your flanking region + size, so SNP/V will be included. + -mp MISPRIMING, --mispriming MISPRIMING + full path to mispriming library for primer3 (EX: + /home/dkennetz/mispriming/humrep.ref + -tp THERMOPATH, --thermopath THERMOPATH + full path to thermo parameters for primer3 to use (EX: + /home/dkennetz/primer3/src/primer3_config/) install + loc + -sv {deletion,inversion,insertion}, --sv-type {deletion,inversion,insertion} + currently supported SV primer generation: deletion, + inversion, and insertion. +``` +The `-ref` parameter is the reference genome for which you want to design primers. The `-in` parameter is the position input file with the positions of interest. The parameters in the middle with `-opt, -min, -max` in front of them are the thermodynamic parameters. They all contain defaults that I have found to be good for most standard small fragment experiments. `-sr` is the product_size_range, `-mp` is the primer mispriming library which penalizes primers that land on sequences in the file. I have provided a copy of the file I use in the `test` directory as I think it is sufficient for most cases. `-tp` is the thermodynamics path for your primer3 program to use. This is in the primer3 install location, so if you installed primer3 in your `~/bin` like the standard installation, this path will be `~/bin/primer3/src/primer3_config/`. Lastly, `-sv` is the sv type. For this I will choose deletion. If you are doing a translocation setup, you should use insertion. This is explained in the [inputs](inputs.md) for the insertion file. + +Anything with a default value does not need to be specified unless you want to change that default value to something else, but for the sake of the tutorial I will include them: + +*NOTE: THE -st SHOULD ALWAYS BE (-flank-1,1) SO IF FLANK IS 200, -st SHOULD be 200-1,1 OR 199,1. THIS IS SO YOUR POSITION OF INTEREST IS GUARANTEED TO BE IN YOUR PRODUCT. I ALSO ALWAYS SET MY -sr UPPER LIMIT TO BE TWICE MY FLANK SIZE.* + +``` +primer_tk iterator_sv \ + -ref test_standard.fa \ + -in input_sv.csv \ + -opt_size 22 \ + -min_size 18 \ + -max_size 25 \ + -opt_gc 50 \ + -min_gc 20 \ + -max_gc 80 \ + -opt_tm 60 \ + -min_tm 57 \ + -max_tm 63 \ + -sr 200-400 \ + -flank 200 \ + -st 199,1 \ + -mp /home/dkennetz/sv_tutorial/humrep.ref \ + -tp /home/dkennetz/bin/primer3/src/primer3_config/ \ + -sv deletion +``` + +This will output the following files: + +``` +flanking_regions.input_sv.fasta +primer3_input.input_sv.txt +``` + +The flanking regions file is used later in the workflow, and the primer3_input file is used in the next (primer3) step. The filename convention is always flanking_regions..fasta and priemr3_input..txt. + +## 3) Run Primer3 + +This step is easy enough but can be time consuming for large datasets. In our case, it should take about 30 seconds. + +``` +primer3_core --output=primer_dump.txt primer3_input.input_sv.txt +``` + +This will output a log file named primer_dump.txt (we want) and a bunch of intermediate files (we don't want). +I like to clean the intermediates up (the intermediates also aren't kept if you use CWL). + +``` +rm -rf *.int *.for *.rev +``` + +Up to 5 primer pairs will be output per position, and all will be visible in the files. In the final step, we will have one file called ""top_primers"" and one called ""all_primers"". The top_primers file will be the top ranking primer pair that passed all filtering steps, and all_primers will output all primers that passed all filtering steps (up to 5 per position). + +## 4) Run the primer3 output parsing + +This is similar to the Standard Primer Design pipeline in that all we are doing is parsing the primer3 output in this step: + +``` +primer_tk pre_sv -h +usage: primer_tk pre_sv [-h] -d DUMP -o OUTFILE [-pcr PCRFILE] + +optional arguments: + -h, --help show this help message and exit + -d DUMP, --primer3_dump DUMP + Primer3 stdout passed into a 'dump' file to be used as + input + -o OUTFILE, --outfile_name OUTFILE + The output filename for all primer information. + -pcr PCRFILE, --pcrfile PCRFILE + The pseudopcr file +``` + +the -pcr flag here just sets up a pseudopcr file and could be useful in the future, so I included it. To run: + +``` +primer_tk pre_sv \ + -d primer_dump.txt \ + -o total_primers.csv \ + -pcr fake_pcr.txt +``` + +If we look at the output, we see two primer pairs were designed around 1 position. This looks like a tough region to design around! We can always go back and check out the `primer_dump.txt` file to see why a specific region was rejected. It has a line like this for each position in the file: + +``` +PRIMER_LEFT_EXPLAIN=considered 653, low tm 476, high repeat similarity 113, long poly-x seq 64, ok 0 +PRIMER_RIGHT_EXPLAIN=considered 1308, GC content failed 557, low tm 53, high tm 521, high hairpin stability 147, high repeat similarity 21, ok 9 +``` + +So for position 1, we see all the problems associated with the region and why primers failed there. If we actually look at the sequence it used: + +``` +SEQUENCE_TEMPLATE=AACCCTAACCCTAACCCTAACCCTAACCCCTAACCCTAACCCTAACCCTAACCCTAACCTAACCCTAACCCTAACCCTAACCCTAACCCTAACCCTAACCCTAACCCTAACCCCTAACCCTAACCCTAAACCCTAAACCCTAACCCTAACCCTAACCCTAACCCTAACCCCAACCCCAACCCCAACCCCAACCCCAACCCCGCTCCGCCTTCAGAGTACCACCGAAATCTGTGCAGAGGACAACGCAGCTCCGCCCTCGCGGTGCTCTCCGGGTCTGTGCTGAGGAGAACGCAACTCCGCCGTTGCAAAGGCGCGCCGCGCCGGCGCAGGCGCAGAGAGGCGCGCCGCGCCGGCGCAGGCGCAGAGAGGCGCGCCGCGCCGGCGCAGGCGCAGAGAGGCGC +``` + +This is reasonable! + +## 5) Pseudo PCR check + +There is no actual PCR done here, as it isn't super necessary when we are not multiplexing. The likelihood of severe off-target for a single pair is pretty low, although it does happen occasionally! + +To run the next step: + +``` +primer_tk post_sv -h +usage: primer_tk post_sv [-h] [-f FLANK_FILE] [-tp TOTAL_PRIMERS] + [-all ALL_FINAL_PRIMERS] [-top TOP_FINAL_PRIMERS] + [-plate PLATE_BASENAME] + +optional arguments: + -h, --help show this help message and exit + -f FLANK_FILE, --flank_file FLANK_FILE + use flanking_regions file from output of + genome_iterator_sv.py + -tp TOTAL_PRIMERS, --total_primers TOTAL_PRIMERS + the pre-PCR master primer file that contains all + sample + primer info + -all ALL_FINAL_PRIMERS, --all_final_primers ALL_FINAL_PRIMERS + all primers generated for targets + -top TOP_FINAL_PRIMERS, --top_final_primers TOP_FINAL_PRIMERS + top primers generated for targets + -plate PLATE_BASENAME, --plate_basename PLATE_BASENAME + the basename of the primers in plate format ready to + order. +``` + +For this step, we actually pass the flanking regions file output from step 1 back into this step because this is the sequence that was used to design the primer pair. From this we can extract the full sequence the primers are amplifying and give pseudo-pcr product information such as GC content and product length, which is why I say there is pseudo-pcr done here. + +The primer positions for each pair in regards to the reference are also output, as this can be useful to potentially trouble shoot primers that seem like they have failed. + +The outputs for this are all primer pairs, and top primer pair by input position, as well as an easy to order primer plate format. + +To run: + +primer_tk post_sv \ + -f flanking_regions.input_sv.fasta \ + -tp total_primers.csv \ + -all all_primers.csv \ + -top top_primers.csv \ + -plate plate \ + +And all final outputs from this pipeline are: + +``` +primer3_input.input_sv.txt +flanking_regions.input_sv.fasta +primer_dump.txt +total_primers.csv +fake_pcr.txt +all_primers.csv +top_primers.csv +plate_F.csv +plate_R.csv +``` + +## 7) SNP Annotation of Primers + +To view this, please head over to [the Standard and Multiplex Tutorial Step 7](standard_and_multiplex.md#tabix). +","Markdown" +"In Silico","stjude/PrimerTK","docs/index.md",".md","1591","17","# Welcome to PrimerTK documentation + +PrimerTK is a toolkit is a python package that has the capability to design multiplex primer pools, and primer sets +around complex structural variants such as large deletions, insertions, translocation events, and inversions, and of course, standard primer sets. + +PrimerTK is used in conjunction with [primer3](https://github.com/primer3-org/primer3) and [in silico PCR](https://hgwdev.gi.ucsc.edu/~kent/src/) to extract reference sequences by coordinate position, design primers, compare them with each other to check for pooling compatibility (if multiplexing), check for off-target products, and filter for the top results. It also has the ability to detect SNP's present in primers and annotate them in results. + +PrimerTK also has pipelines written in the Common Workflow Language (CWL). CWL a powerful tool to run structured pipelines. All it requires is an input yaml file, which I will provide the skeleton for in the CWL section. By using CWL, the user can simply adjust the input yaml file to meet the specific needs of the workflow and then run it and it will execute each consecutive step on its own and return a final output. This enables users to run multiple primer sets at the same time (or the same primer set under different thermodynamic conditions). + +# Table of Contents +1. [Introduction](introduction.md) +2. [Install](installation.md) +3. [Input Templates](inputs.md) +4. [Standard and Multiplex Tutorial](standard_and_multiplex.md) +5. [Structural Variants Tutorial](structural_variants.md) +6. [Common Workflow Language Setup](cwl.md) +","Markdown" +"In Silico","stjude/PrimerTK","docs/standard_and_multiplex.md",".md","21259","404","# Standard and Multiplex Tutorial + +These two pipelines have very similar workflow so I will include them together. If you followed the installation page and git cloned the repo, there is a directory called `test` in the PrimerTK repo. This is for code testing but it also has data for the user to implement the full pipeline (testing is good). + +If you added primer3 and isPcr to you .bashrc in the installation guide, skip this. If not, run the following (assuming you installed primer3 and isPcr in your `~/bin` directory: + +``` +export PATH=~/bin/primer3:$PATH +export PATH=~/bin/isPcr33:$PATH +``` + +Or add the above to your `~/.bashrc` to prevent yourself from having to do this every time you log in to a new session. +So now `primer_tk`, `isPcr`, and `primer3_core` should all be accessible from the command line, anywhere in your system. +This tutorial is going to assume that you installed PrimerTK in your home directory but you may well have set it up anywhere. It is also going to assume you used the standard installation script so the path to the primer3 executable and isPcr executable will reflect that. + +## 1) Setup a tutorial directory with files from test + +These files are small so you can copy them over directly or just point to them as you run the program. + +I will do everything in a directory called tutorial: + +``` +cd ~/tutorial/ +cp ~/PrimerTK/test/data/humrep.ref . +cp ~/PrimerTK/test/data/input_standard.csv . +cp ~/PrimerTK/test/data/test_standard.fa . +``` + +## 2) Start running the program +Then let's start running the program. Step 1 called `iterator` has a lot of inputs, but that is just because I wanted to give users a lot of flexibility on thermodynamic parameters for primer3. + +Let's display the help message and explain the parameters: + +``` +primer_tk iterator -h + +usage: primer_tk iterator [-h] -ref REF_GENOME -in REGIONS_FILE + [-opt_size PRIMER_OPT_SIZE] + [-min_size PRIMER_MIN_SIZE] + [-max_size PRIMER_MAX_SIZE] [-opt_gc PRIMER_OPT_GC] + [-min_gc PRIMER_MIN_GC] [-max_gc PRIMER_MAX_GC] + [-opt_tm PRIMER_OPT_TM] [-min_tm PRIMER_MIN_TM] + [-max_tm PRIMER_MAX_TM] [-sr PRODUCT_SIZE_RANGE] + [-flank FLANKING_REGION_SIZE] [-st SEQUENCE_TARGET] + [-mp MISPRIMING] [-tp THERMOPATH] + +optional arguments: + -h, --help show this help message and exit + -ref REF_GENOME, --ref_genome REF_GENOME + Reference Genome File to design primers around + -in REGIONS_FILE, --regions_file REGIONS_FILE + File with regions to design primers around + -opt_size PRIMER_OPT_SIZE, --primer_opt_size PRIMER_OPT_SIZE + The optimum primer size for output, default: 22 + -min_size PRIMER_MIN_SIZE, --primer_min_size PRIMER_MIN_SIZE + The optimum primer size for output, default: 18 + -max_size PRIMER_MAX_SIZE, --primer_max_size PRIMER_MAX_SIZE + The optimum primer size for output, default: 25 + -opt_gc PRIMER_OPT_GC, --primer_opt_gc PRIMER_OPT_GC + Optimum primer GC, default: 50 + -min_gc PRIMER_MIN_GC, --primer_min_gc PRIMER_MIN_GC + Minimum primer GC, default: 20 + -max_gc PRIMER_MAX_GC, --primer_max_gc PRIMER_MAX_GC + Maximum primer GC, default: 80 + -opt_tm PRIMER_OPT_TM, --primer_opt_tm PRIMER_OPT_TM + Optimum primer TM, default: 60 + -min_tm PRIMER_MIN_TM, --primer_min_tm PRIMER_MIN_TM + minimum primer TM, default: 57 + -max_tm PRIMER_MAX_TM, --primer_max_tm PRIMER_MAX_TM + maximum primer TM, default: 63 + -sr PRODUCT_SIZE_RANGE, --product_size_range PRODUCT_SIZE_RANGE + Size Range for PCR Product, default=200-400 + -flank FLANKING_REGION_SIZE, --flanking_region_size FLANKING_REGION_SIZE + This value will select how many bases up and + downstream to count when flanking SNP (will do 200 up + and 200 down), default: 200 + -st SEQUENCE_TARGET, --sequence_target SEQUENCE_TARGET + default: 199,1, should be half of your flanking region + size, so SNP/V will be included. + -mp MISPRIMING, --mispriming MISPRIMING + full path to mispriming library for primer3 (EX: + /home/dkennetz/mispriming/humrep.ref + -tp THERMOPATH, --thermopath THERMOPATH + full path to thermo parameters for primer3 to use (EX: + /home/dkennetz/primer3/src/primer3_config/) install + loc +``` + +As you can see, the help message is pretty detailed. The only thing that may need further explaining is the -mp (mispriming flag). This is just a file containing human repetitive elements or sequences that are common primer mispriming locations. Primer3 will use this to score primers in that location with a penalty so they are not likely to be selected. + +Anything with a default value does not have to be specified on the command line (if you want to use that value as the parameter). These have been selected because I have seen good success with these values for standard pcr. In this tutorial, I will specify every value, but again you do not have to specify defaults. + +*NOTE: THE -mp AND -tp FLAGS SHOULD BE THE FULL PATH TO FILE AS THIS IS WHAT PRIMER3 REQUIRES* +*NOTE: THE -st SHOULD ALWAYS BE (-flank-1,1) SO IF FLANK IS 200, -st SHOULD be 200-1,1 OR 199,1. THIS IS SO YOUR POSITION OF INTEREST IS GUARANTEED TO BE IN YOUR PRODUCT. I ALSO ALWAYS SET MY -sr UPPER LIMIT TO BE TWICE MY FLANK SIZE.* + +``` +primer_tk iterator \ + -ref test_standard.fa \ + -in input_standard.csv \ + -opt_size 22 \ + -min_size 18 \ + -max_size 25 \ + -opt_gc 50 \ + -min_gc 20 \ + -max_gc 80 \ + -opt_tm 60 \ + -min_tm 57 \ + -max_tm 63 \ + -sr 200-400 \ + -flank 200 \ + -st 199,1 \ + -mp /home/dkennetz/tutorial/humrep.ref \ + -tp /home/dkennetz/bin/primer3/src/primer3_config/ +``` + +This module is just used to parse any reference genome and setup a primer3 config. The outputs will be: + +``` +flanking_regions.input_standard.fasta +primer3_input.input_standard.txt +``` +The fasta will show us what sequences we pulled down, and the primer3_input will be the input to primer3. +The output files will maintain the same name as the input file used for the `-in` flag. + +## 3) Run Primer3 + +This step is easy enough but can be time consuming for large datasets. In our case, it should take about 30 seconds. + +``` +primer3_core --output=primer_dump.txt primer3_input.input_standard.txt +``` + +This will output a log file named primer_dump.txt (we want) and a bunch of intermediate files (we don't want). +I like to clean the intermediates up (the intermediates also aren't kept if you use CWL). + +``` +rm -rf *.int *.for *.rev +``` + +Up to 5 primer pairs will be output per position, and all will be visible in the files. In the final step, we will have one file called ""top_primers"" and one called ""all_primers"". The top_primers file will be the top ranking primer pair that passed all filtering steps, and all_primers will output all primers that passed all filtering steps (up to 5 per position). + +We can also see why primers failed at specific regions if we look at the primer dump file. For example, position 1 returned 0 primers. If we look at why: + +``` +PRIMER_LEFT_EXPLAIN=considered 653, low tm 476, high repeat similarity 113, long poly-x seq 64, ok 0 +PRIMER_RIGHT_EXPLAIN=considered 791, GC content failed 140, low tm 304, high tm 163, high hairpin stability 47, high repeat similarity 83, long poly-x seq 54, ok 0 +``` +Primer3 gives us a pretty informative description. If we then take a look at the sequence it used to design primers: + +``` +SEQUENCE_TEMPLATE=AACCCTAACCCTAACCCTAACCCTAACCCCTAACCCTAACCCTAACCCTAACCCTAACCTAACCCTAACCCTAACCCTAACCCTAACCCTAACCCTAACCCTAACCCTAACCCCTAACCCTAACCCTAAACCCTAAACCCTAACCCTAACCCTAACCCTAACCCTAACCCCAACCCCAACCCCAACCCCAACCCCAACCCCAACCCTAACCCCTAACCCTAACCCTAACCCTACCCTAACCCTAACCCTAACCCTAACCCTAACCCTAACCCCTAACCCCTAACCCTAACCCTAACCCTAACCCTAACCCTAACCCTAACCCCTAACCCTAACCCTAACCCTAACCCTCGCGGTACCCTCAGCCGGCCCGCCCGCCCGGGTCTGACCTGAGGAGAACTGT +``` +It looks highly repetitive. This seems reasonable! + + +## 4) Run the pre-pcr step and the multiplex filtering + +This step is used for parsing the primer3 output file and setting up the input for pcr, and more importantly for filtering for multiplex primer pools. Let's look at the help message: + +``` +primer_tk pre -h +usage: primer_tk pre [-h] -d DUMP -o OUTFILE [-nd NO_DIMER] + [-spcr STANDARD_PCR_FILE] [-mpcr MULTIPLEX_PCR_FILE] + [-pa PERCENT_ALIGNMENT] -pcr {standard,multiplex} + +Command Line argument for total primerinput file to check if primers have a +degreeof complementarity with each other as definedby the user. Default is 60% +(fairly strict). + +optional arguments: + -h, --help show this help message and exit + -d DUMP, --primer3_dump DUMP + Primer3 stdout passed into a 'dump' file to be used as + input + -o OUTFILE, --outfile_name OUTFILE + The output filename for all primer information. + -nd NO_DIMER, --no_dimer NO_DIMER + The primers left after dimers removed. + -spcr STANDARD_PCR_FILE, --standard_pcr_file STANDARD_PCR_FILE + The file to be used for standard pcr input + -mpcr MULTIPLEX_PCR_FILE, --multiplex_pcr_file MULTIPLEX_PCR_FILE + The file to be used for multiplex pcr input + -pa PERCENT_ALIGNMENT, --percent_alignment PERCENT_ALIGNMENT + Percent match between 2 primers for pair to be + discarded. EX: primer_len = 22, percent_aln = 60 + dimer_len = (60/100) * 22 = 13.2 -> 13. + -pcr {standard,multiplex}, --pcr_type {standard,multiplex} + perform standard or multiplex pcr on given inputs. +``` + +### For multiplex PCR: + +PrimerTK does two important things for multiplexing: +1. It checks for the presence of primer dimers between any two primers in the entire dataset. +2. It sets up an all vs all PCR input. + +Both of these are important because in multiplexing, all primers will be in a single pool, so they will interact with each other. If the reaction between each other is more favorable than the reaction with the DNA template, or it is competing, those primers will have less effective concentration because they will bind to each other instead of the template. This will give us lower or no representation of the expected site. + +Furthermore, we do in silico PCR to check for potential off-target amplification. This has the same effect as primer dimerization to a large extent. If there are competing sites, there is less effective concentration of primer at the site of interest. + +To deal with this, a simple string matching algorithm has been implemented. This returns a score based on how well the primers align with each other. I also ask for a user input of the `-pa` or percent alignment. I use this percent alignment strategy because primers will be different lengths. If the primer length times the percent alignment is greater than the calculated alignment score, then the primer is dropped. + +This is repeated until every possible combination in the pool has been checked. + +Afterwards, it returns a primer file and a pcr file that only contains the post-filter primer pairs. + +to run: + +``` +primer_tk pre \ + -d primer_dump.txt \ + -o total_primers.csv \ + -nd no_dimers.csv \ + -mpcr multiplex_pcr.txt \ + -pa 60 \ + -pcr multiplex +``` + +We can see from our example if we check the `no_dimers.csv` file, that with this pa score the primer pair was not filtered. However, as the size of the dataset increased, there is much more potential for primer-primer interaction and many more will be filtered. + +Go ahead and cat the multiplex_pcr.txt output by this program as well. We can see that there are 4(!) pcr reactions that isPcr is going to simulate. This goes to show the complexity of pcr multiplexing. The reason one primer pair has 4 pcr reactions tested is because: +1. It considers the forward primers possibility to amplify using itself (this may be overkill but multiplexing results are good). +2. It obviously considers the forward with the reverse. +3. It considers the reverse with the forward. +4. It considers the reverse with the reverse. + +### For standard PCR: + +There is not much to consider for standard PCR input, so PrimerTK just parses information from the primer3 log and sets up a single pcr reaction for each primer pair: + +primer_tk pre \ + -d primer_dump.txt \ + -o total_primers.csv \ + -spcr standard_pcr.txt \ + -pcr standard + +This is fast for all datasets because it doesn't perform any all vs all comparisons. + +## 5) In Silico PCR off-target check + +*NOTE: IN SILICO PCR REQUIRES THE REFERENCE GENOME TO BE SPLIT INTO CHROMOSOMES FOR THE HUMAN REFERENCE (OR ANY REFERENCE ABOVE 2.1GB). I WILL POST HOW I DO THIS BELOW.* + +*NOTE: THIS IS NOT REQUIRED FOR OUR TEST CASE BECAUSE THERE IS ONLY ONE CHROMOSOME.* + +#### Splitting a reference genome by chromosome: + +The easiest way to do this is using [pyfaidx](https://github.com/mdshw5/pyfaidx). + +to install: + +``` +pip3 install pyfaidx --user +``` + +Then go to the directory with your reference genome and run: + +``` +faidx -x reference.fa +``` + +This will result in your original reference, a .fai (fasta index) file for your reference, and then each individual chromosome split out as a separate fasta file. For GRCh38 human reference this took less than 3 minutes. + +### Running isPcr for the tutorial + +In the PrimerTK/scripts directory, there is a script called `ispcr.sh`. This is an easy to use script that runs in silico PCR using the pcr file output from the last step. Running requires two inputs: a directory with your reference split into chromosomes, and your pcr input file (generated by PrimerTK). So from your tutorial directory (I am going to run this like I installed PrimerTK in my home directory). Since I copied the test.fa into this directory when I started, and my multiplex pcr input file is in the directory as well, I can just run like this: + +``` +# Usually your chromosome dir will be located somewhere else, in that case put the path. +~/PrimerTK/scripts/ispcr.sh ./ ./multiplex_pcr.txt +``` + +This will print: +`Running In Silico PCR on pcr input positions...` + +And in our case it will take less than a second. Normally it takes a few minutes if there are a lot of targets in a real reference genome. + +The script writes output to a file called `pcr_output.fa`. This will be used in the next step. If we `cat` the file, we see the following: + +``` +>1:1074+1381 sample3_gene3_1:1200__ 308bp GCAGAAACTCACGTCACGGT CTGCCACTACACCTTGAGCA +GCAGAAACTCACGTCACGGTggcgcggcgcagagacgggtagaacctcag +... +>1:1074-1381 sample3_gene3_1:1200__ 308bp CTGCCACTACACCTTGAGCA GCAGAAACTCACGTCACGGT +CTGCCACTACACCTTGAGCAagaggaccctgcaatgtccctagctgccag +... +``` + +We see the structure of the header: positions, sample name, primer1, primer2. We may notice there are two amplifications for this, but they have the same positions. The first has `1:1074+1381` a noticable (+) sign between the position coordinates, and the second `1:1074-1381` has a noticable (-) sign between the position coordinates. This indeicates that the first primer pair amplified the forward strand, while the second amplified the reverse. + +In the next step, we use all positional outputs from this file to filter out off target pairs. We also use the sequence to show predicted product length and GC content. We only test amplifications up to 5kb (which may be overkill), because most products longer than even 2kb will have incomplete amplification in the lab, so I figured 5kb would cover every possible opportune amplificiations. + +## 6) Post PCR Processing for multiplex samples + +This is going to use the `total_primers.csv` file generated by the `pre` step, and the `pcr_output.fa` file as inputs to do some final checks. It also has some other flags, such as user specified off-target max (8 by default) and output file names: + +``` +primer_tk post -h +usage: primer_tk post [-h] [-i PCRFILE] [-tp TOTAL_PRIMERS] + [-ot OFF_TARGET_MAX] [-pcri PCR_PRODUCT_INFO] + [-all ALL_PRIMER_INFO] [-top TOP_FINAL_PRIMERS] + [-plate PLATE_BASENAME] + +optional arguments: + -h, --help show this help message and exit + -i PCRFILE, --pcr_output PCRFILE + use output of isPCR + -tp TOTAL_PRIMERS, --total_primers TOTAL_PRIMERS + the pre-PCR master primer file that contains all + sample + primer info. + -ot OFF_TARGET_MAX, --off_target_max OFF_TARGET_MAX + the maximum number of off target hits of primer. + -pcri PCR_PRODUCT_INFO, --pcr_product_info PCR_PRODUCT_INFO + the information of all products generated by isPcr + -all ALL_PRIMER_INFO, --all_primer_info ALL_PRIMER_INFO + all of the successful primers generated + -top TOP_FINAL_PRIMERS, --top_final_primers TOP_FINAL_PRIMERS + the top primers generated for each position + -plate PLATE_BASENAME, --plate_basename PLATE_BASENAME + the basename of the primers in plate format ready to + order. +``` + +The PCR product info file will include information regarding all products generated by isPcr. This will include off-target sites which are filtered out of our final primer files. + +The all primers file will contain all primers that passed all the applied filters for a given position, for all positions in the file. This file will have a tag for each primer pair to indicate how many off-target sites it amplified. I have seen cases where the top ranking primer pair actually amplified more off-target than the second ranking primer pair (differences as great as 5 to 0). For this case, I go back and look at the penalty in the `primer_dump.txt` file to see if the penalty difference between the two is substantial and if they have similar tm and product gc. If the thermodynamics look good between the pair, and one has less off-target than the other, I pick the one with less off-target. + +The top final primers file will display the top ranking primer pair for each position. Also, the primer positions in regards to the reference will also be output, as this can be useful to potentially trouble shoot primers that seem like they have failed. + +Lastly, the plate_basename is a simple string that we want our primer plate to be named. This step will setup a ready to order file with the forward primers in a plate format and the reverse primers in a plate format. The default for these files will be: + +`plated_primers_F.txt` and `plated_primers_R.txt`. +The forward and reverse primers will correspond to the same positions on the plates. So primer pair 1 will be in A1 on each plate, primer pair 2 will be in A2... etc. + +To run: + +primer_tk post \ + -i pcr_output.fa \ + -tp total_primers.csv \ + -ot 5 \ + -pcri product_info.csv \ + -all all_primers.csv \ + -top top_primers.csv \ + -plate plated + +This will be fast and the final output files from the whole pipeline will be: + +``` +flanking_regions.input_standard.fasta +primer3_input.input_standard.txt +primer_dump.txt +Primer_Dimers.txt +total_primers.csv +no_dimers.csv +multiplex_pcr.txt +pcr_output.fa +product_info.csv +top_primers.csv +all_primers.csv +plated_F.csv +plated_R.csv +``` + +## 7) SNP Annotation of Primers + +This cannot be done in the tutorial, but can be done with real datasets, as long as there is a vcf file for the reference you are using. + +An example would be if I was using GRCh38 and wanted to annotate snps according to this genome. The file I may use would be (and the tabix indexed genome): + +``` +ftp://ftp.ncbi.nlm.nih.gov/pub/clinvar/vcf_GRCh38/clinvar_20190923.vcf.gz +ftp://ftp.ncbi.nlm.nih.gov/pub/clinvar/vcf_GRCh38/clinvar_20190923.vcf.gz.tbi +``` + +After these are downloaded and I want to annotate my files I run: + +``` +primer_tk tabix -h +usage: primer_tk tabix [-h] [-vcf VCF] [-in P_INFO] [-o OUTPUT] + +optional arguments: + -h, --help show this help message and exit + -vcf VCF, --variant-call-file VCF + Tabix indexed VCF. + -in P_INFO, --primer-input-file P_INFO + The output of the primer pipeline. + -o OUTPUT, --output OUTPUT + The name of the output file +``` + +The vcf file would be the tabix-indexed reference genome, the input P_INFO file would be the `all_primers.csv` file from the post-processing output, and the output file would be whatever you want! + +An example of running is: + +``` +primer_tk tabix \ + -vcf ~/tabix_indexed_genome/GRCh38/All_20180418.vcf.gz \ + -in all_primers.csv \ + -o snp_annotated_primers.csv +``` + +which would return a the snp annotated primer file! + +Next, proceed to the [Sructural Variants Tutorial](structural_variants.md) or the [CWL Tutorial](cwl.md) to learn how to run this pipeline as a single step workflow! +","Markdown" +"In Silico","stjude/PrimerTK","docs/inputs.md",".md","4498","95","# Input File Formats for Various Pipelines + +The following will present template files which display how the coordinate file input to the program should look. These inputs will contain the following columns which correspond to things used by the program. + +*NOTE: NO INPUT FILES HAVE HEADERS. THE FIRST LINE OF THE FILE SHOULD BE THE FIRST POSITION OF INTEREST.* + +*NOTE: POSITIONS ARE REFERENCE GENOME SPECIFIC* + +## Multiplex / Standard Primer Generation Input File + +This pipeline uses an input file with 4 columns. The file can be comma separated or tab delimited. Any other formats will cause the first step in the pipeline to error out. + +The first column is ""Gene"" or ""ID"". If I am targeting a specific SNP on a specific gene, I usually use the gene name here. Otherwise, I use a random identifier. Either are okay, as this column is not matched to anything, but rather is just used in the naming convention for final output. The second column is going to be the name of the sample, or the identifier you want to give the location. The reason both column 1 and column 2 are nice is because you could look for multiple genes in the same sample (or you could design a whole set around a single sample). Again, the sample name is not checked against anything and is just used for final naming. Column 3 is the chromosome location of the target position. This can be in the format `chr1` or `1` but the `chr` should be lowercase and should have no spaces between itself and the number or X, Y. The fourth column is the position of interest. This should be the integer value only and should not contain commas. + +multiplex_input.csv: + +``` +BRCA1,Sample1,chr17,43100000 +HBA2,Sample2,chr16,172900 +HBG1,SampleNice,chr11,5249000 +``` + +The same input, only tab delimited (should end in .txt): + +multiplex.txt: + +``` +BRCA1 Sample1 chr17 43100000 +HBA2 Sample2 chr16 172900 +HBG1 SampleNice chr11 5249000 +``` + +Personally, I think csv files are easier to use as sometimes different text editors tab things differently. If you have an issue with a txt input, try to run it again using csv input instead. + +*NOTE: THE STANDARD PRIMER GEN FILE IS THE EXACT SAME AS THE MULTIPLEX INPUT.* + +## Deletion and Inversion Input File + +This has the same format as the standard and multiplex input, except it has a fifth column. + +Columns 1-3 are the same; however, column 4 is deletion / inversion start and column 5 is deletion / inversion stop + +So if the user was looking for a 100 bp deletion / inversion in a random part of chromosome 1, the input could look like this: + +deletion.csv: + +``` +random,mysample,1,100000,100100 +... +``` +This would then take flanking sequence on either end of those positions to span the breakpoint. + +For an inversion, the input would be the same: + +inversion.csv: + +``` +random,mysample,1,100000,100100 +``` + +The program just performs different operations on the sequence when different SV types are specified. + +## Insertion and Translocation Input File + +This file is a bit more involved, as it includes the normal chromosome start and stop positions (where the insertion will be placed) and the inserted regions start and stop positions, as well as strand orientation of the inserted region. In theory for a translocation you can just add another entry with the positions flip-flopped, or just treat all the translocation events as individual insertions. See below: + +insertion.csv: + +``` +gene1,sample1,chr1,1000,1100,chr2,1000,1100,+ +gene2,sample2,chr1,1000,1100,chr2,1000,1100,- +``` + +Gene1 sample1 would have a 100 bp insertion on chr1 from chr2 using the forward strand orientation. +Gene2 sample2 would have a 100 bp insertion on chr1 from chr2 using the reverse strand orientation (the seq will be reverse complemented). + +Now if this was a translocation and gene1 sample1 was a translocation (where the two regions switched places) you could just handle it in two lines by switching the positions (let's pretend the same thing happened for gene2 sample2): + +translocation.csv: + +``` +gene1,sample1,chr1,1000,1100,chr2,1000,1100,+ +gene1,sample1,chr2,1000,1100,chr1,1000,1100,+ +gene2,sample2,chr1,1000,1100,chr2,1000,1100,- +gene2,sample2,chr2,1000,1100,chr1,1000,1100,- +``` + +Now of course you may have to think about strandedness a little bit here, but it is definitely applicable! + +Before diving into the program by yourself, I would recommend heading to the tutorial of interest first: + +[Standard and Multiplex Tutorial](standard_and_multiplex.md) + +[Structural Variants Tutorial](structural_variants.md) +","Markdown" +"In Silico","stjude/PrimerTK","scripts/ispcr.sh",".sh","743","38","#!/usr/bin/env bash + +######################### +# The command line help # +######################### +display_help() { + echo "" +Please provide the full path to the directory containing genome split into chromosome.fa files +as the first command line argument and the pcr input file as the second. +"" + exit 1 +} + +chromosome_dir=$1 +pcr_input=$2 + +if [[ ! -d $chromosome_dir ]]; then + >&2 echo "" +ERROR: no chromosome directory was specified. +"" + display_help + exit 1 +elif [[ ! -f $pcr_input ]]; then + >&2 echo "" +ERROR: no pcr input file was specified. +"" + display_help + exit 1 +else + echo ""Running In Silico PCR on pcr input positions..."" +fi + +for x in $chromosome_dir/*.fa +do + isPcr $x $pcr_input stdout >> pcr_output.fa +done + +","Shell" +"In Silico","stjude/PrimerTK","scripts/installer.sh",".sh","2028","66","# +# Third party tools Primer3 (https://github.com/primer3-org/primer3.git), available under GNU GPLv2, and In Silico PCR +# (https://hgwdev.gi.ucsc.edu/~kent/src/isPcr33.zip) are needed for PrimerTK to work properly. We do not include those third +# party tools alongside the PrimerTK software. However, the following commands were +# used to install the software as of the time of PrimerTK's release. + +# Uncomment all code in between boxes to install + +########### +# Primer3 # +########### + +############################################################# +# Select the installation directory and make sure it exists.# +############################################################# + +#PRIMER3_INSTALL_DIR=~/bin/ +#mkdir -p $PRIMER3_INSTALL_DIR + +##################################################################### +# Make a tmp location to download / install the source # +# we need the whole source to run the program. There are configs in # +# primer3_config that are referenced for thermodynamic params # +##################################################################### + +#TMPDIR=$(mktemp -d) +#echo $TMPDIR +#cd $TMPDIR +#git clone https://github.com/primer3-org/primer3.git primer3 +#cd ./primer3/src +#make + +#################################### +# Copy the appropriate executables # +#################################### + +#cp -rf $TMPDIR/primer3 $PRIMER3_INSTALL_DIR + +#rm -rf $TMPDIR + +######### +# isPCR # +######### + +#ISPCR_EXECUTABLE_DIR=~/bin/isPcr33 +#mkdir -p $ISPCR_EXECUTABLE_DIR +#MACHTYPE=$(uname -m) +#export MACHTYPE +#ISPCR33_INSTALL_DIR=~/bin/$MACHTYPE +#mkdir -p $ISPCR33_INSTALL_DIR + +#TMPDIR2=$(mktemp -d) +#echo $TMPDIR2 +#cd $TMPDIR2 +#wget https://hgwdev.gi.ucsc.edu/~kent/src/isPcr33.zip && unzip isPcr33.zip 1> .unzip.out 2> .unzip.err +#mkdir ./isPcrSrc/lib/$MACHTYPE +#cd $TMPDIR2/isPcrSrc/lib && make HG_WARN="""" +#cd $TMPDIR2/isPcrSrc && make HG_WARN="""" +#cp $ISPCR33_INSTALL_DIR/isPcr $ISPCR_EXECUTABLE_DIR +#rm -rf $ISPCR33_INSTALL_DIR +#rm -rf $TMPDIR2 + +################# +# END INSTALLER # +################# +","Shell" +"In Silico","rdkit/shape-it","infrastructure/pyshapeit/build.sh",".sh","354","16","#!/bin/bash + +cmake \ + -D PYTHON_INSTDIR=$SP_DIR \ + -D BUILD_RDKIT_SUPPORT=ON \ + -D BUILD_PYTHON_SUPPORT=ON \ + -D CMAKE_SYSTEM_PREFIX_PATH=$PREFIX \ + -D CMAKE_INSTALL_PREFIX=$PREFIX \ + -D RDKIT_INCLUDE_DIR=$PREFIX/include/rdkit \ + -D CMAKE_BUILD_TYPE=Release \ + . + + +make -j$CPU_COUNT install +ctest -j$CPU_COUNT --output-on-failure +","Shell" +"In Silico","rdkit/shape-it","example_note/Align_CDK2_molecule_with_shape-it.ipynb",".ipynb","41796","261","{ + ""cells"": [ + { + ""cell_type"": ""markdown"", + ""metadata"": {}, + ""source"": [ + ""## requirements\n"", + ""- rdkit\n"", + ""- py3Dmol"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 1, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""import sys\n"", + ""import os\n"", + ""sys.path.append('../pyshapeit/')\n"", + ""from rdkit import Chem\n"", + ""from rdkit.Chem import AllChem\n"", + ""from rdkit.Chem import Draw\n"", + ""from rdkit.Chem.Draw import IPythonConsole\n"", + ""from rdkit.Chem import RDConfig\n"", + ""import py3Dmol"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 2, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""import cpyshapeit"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 3, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""mols = [m for m in Chem.SDMolSupplier(os.path.join(RDConfig.RDDocsDir,'Book/data/cdk2.sdf'))]"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 4, + ""metadata"": {}, + ""outputs"": [ + { + ""data"": { + ""image/png"": ""iVBORw0KGgoAAAANSUhEUgAAAlgAAADICAIAAAC7/QjhAAAABmJLR0QA/wD/AP+gvaeTAAAgAElEQVR4nO3deVxUVeMG8GeGfRVwRVFUFNxZ1OpVwz1fEbUNlxIqNdR8JS2TsgWzTFxeXzJN6S2VLE189VcuWO5LLrnhLgriLi4oOzoDzPn9cacBcYeZO4P3+X76g3u5nHOGZJ45555zrkoIASIiIqVSm7sBRERE5sQgJCIiRWMQEhGRojEIiYhI0RiERESkaAxCIiJSNAYhEREpGoOQiIgUjUFIRESKxiAkIiJFYxASEZGiMQiJiEjRGIRERKRoDEIiIlI0BiERESkag5CIiBSNQUhERIrGICQiIkVjEBIRkaIxCImISNEYhEREpGgMQiIiUjQGIRERKRqDkIiIFI1BSEREisYgJCIiRWMQEhGRojEIiYhI0RiERESkaAxCIiJSNAYhEREpGoOQiIgUjUFIRESKxiAkIiJFYxASEZGiMQiJiEjRGIRERKRoDEIiIlI0BiERESkag5CIiBSt6gXhlSvw8MDKlfrDDz7A0qXo2RN79+rPZGbCx8dcrSMioiqm6gWhTgc7O0yciLw8ACgshEYDjQYlJfoLhMDt22ZsIBERVSVVLwgB1KiBwYMRE2PudhARUdVnbe4GVNCECfD3R3h46ZmICDg6AijtGhIRET1SlewRAnBwwKxZGDMGQujP/PgjDh/G4cPYssWsLSMioiqlqgYhgNBQ1KiBtWvN3Q4iIqrKqnAQApg9Gzdv3v9bS5di/Hi8/jpu3JC3TUREVKWohGFssYrQaJCcjMBAXL4MrRYaDWrWREYGmjRBtWoAUFSEPXvQtCnq1MHChXB1xSuvmLvRRERkqapeEEqOHIG/P9q0weHDD7xGCLz5Jr76CvXqydgyIiKqUqrq0Kg0QbSw8IEXFBfjs88wbBhTkIiIHqaqLp94ZBBOnIi0NBQVAUBwsEytIiKiKqeqDo1mZ8PdHW5uyMoyd1OIiKgqe2qHRomIiB5HVe0RArCxQXExiopgXVXHd4mIyPyqao8QgIMDwE4hERFVThXuTDk6Ii8PhYVwdTV3U4gsjLTE1sVFf5ibC2dnqB/vc++tW7dOnTqVkpJy+vTp06dPt2zZ8qWXXgoMDDRda4nMqwoPjTZujLNnceYMGjc2d1OILMyiRRg5EocOoVkzAPDzw6ZN8PIqf5lWi/R0pKQgLW1OSsqhlJSUU6dOZWZmlr3Gw8MjLy9v165d7dq1k6v5RLKqwj3CgIDZ7u6XCwtHAo3M3RYii+PrizFjsGFD6ZmsLKSn4/hxnDiB9HT913fuSBdvP316uXSZi4uLr6+v39+SkpJ+/PHH8PDwAwcOOEqz1IieLlU4CC9d+ungwX2Fha8wCInu1b070tKwZAleew0Afv4ZH35Y/horK/j4wNcXHTqE16jRTUq+unXrlr3mxRdfPHTo0JEjRz788MPZs2fL1Xwi+VThIJQ+nBZytgzRA/znP+jRAyEhANCwITw84OeHZs3g6wtfX/j5oWlT2NpK1/Z9UCF2dnYJCQnPPvvsnDlzevfu3bt3b3kaTyQbBiHRU6tJE7z5Jj7/HAA6dnzgo1rulZOTc/r0aScnpxYtWgAICAiYNGnSxIkThw8ffvToUQ8PD5M1mcgMGIRET7MPP0RQEK5ff+AFxcU4dw5paQXHj8+XpommpKRcvXoVwNChQ3/44Qfpsujo6D/++GPbtm1vv/32ihUr5Gk8kTwYhERPM3t7xMWhV6+7Tv7vf9i3D6dPIyUF6enQauHi4piXN95wgaOjo6+vr1eZaaZqtXrBggUBAQErV65MTFw9YMADh1KJqhwGIdFT6JVX0Lcvtm6FvT26dsXZs6hTp/S733+PP/7Qf61Swdsbfn6qVq0+a9y4lq+vr6+vb4MGDVQqVbkyGzdu/J//xC1e7D52bGiHDvdZjEFURTEIiZ5C0lL6fv2Ql4fsbDRseNd3X38dzz+vnzLj66vfpAn4/JHFDhs2dN06bNuGN9/Ehg24JyuJqqQqHIT29vYAcnJyzN0QIktUUoL8fKjVpfvLGISHV7zYefPw55/YtAnffIOoqMo0kMhSVMmdZXQ63YoVK6KiolQqVU5OzpAhQ8aOHdu8eXNzt4vIgty6herVTfKoslWr0L8/7O2xbx9atTJy4UTyq2Kbbut0umXLlrVs2XLAgAFXr15VqVSFhYXfffddq1at+vTpk5SUpNPpzN1GIouQnQ0Abm7GL7lfPwwbhjt3EBEBrdb45RPJrCoF4caNG9u3bz9o0KCUlBRvb+/4+Pjz588fOHAgMjLS3t4+KSmpT58+vr6+06ZNK7dZIpECSTcNqlUzSeFff40mTZCcjC+/NEn5RHKqGkOjGzdunDhx4r59+wDUr1///fffHzlypJ2dneGCmzdvLliwYN68eWfPngXg4ODw7rs/DRjwMnfMJ8XasgXduqFzZ2zdapLyd+5E584QAlu34vnnTVIFkTwsvUe4ZQtefPF879699+3b5+npOXv27NTU1HfffbdsCgKoXr36Bx98kJaWtmHDhrCwMK1Wu25dt6AgtGuH777D7dvmaj6R2ZhuaFTSsSM++AABAahRw1RVEMnDcoNw1y50745u3fDbb949eoydMWNGWlramDFjDBGYlpZWrjurVqt79OiRmJiYkpLavbubmxsOHMCIEWjUCJ98gkuX9Jfl5ZV+DeDiRRQXy/SiiGRj6iAE8Pnn2LAB4eHYtEl/ZvZsJCbi3Xexd6/+jFaLzp1N2AaiyrPEIDx6FAMGoGNHbN4MFxdER+OXX2aMHz/e8AiY8+fPjxgxonnz5itXrrxvCU2aNPr3v5GRgYQEBATg2jVMmQJvb/TsidWrsWIFGjbEwYP6i3v2REaGPK+MSD4mvUcosbWFWo3UVIwdq3+c0+XLuH4dqakwLGvS6Ur/1ogsk9mC8OhRjBmj/+MBMH06Ll7EiRMYMAD+/li+HM7OiI7G+fOIjS39Y7548eLIkSObNm363XffqVSq06dPP6QKe3tERCA5GTt2YNAgWFtj40b064cTJ9C+PUaNQkmJiV8kkTltCQ5O9PY+YOpqPDzQqxdiY01dD5GpmG1B/fnz+O9/4e6OyZMB4LffcOMGZs2CTgdHR4wejQkT7rr3cPUqZs78cM6cOI1GY2Vl9cYbb8TExDRq9FhPIuzUCZ064epV/Pe/WL8eLVpAq0VmJubPx+jRpnl5ROZ2/vyq7dvj+vf/N9DW1HV99hn8/fUPPpR89BFmzgQALmgiy2fOodHQUCxbhlOn9IfPPgtbW0RGIjUV06eXpuDNm5g0Cb6+2L9fo9Vqw8LCjh8/vmjRosdMQYM6dfDpp9ixQ78v1IwZmDYNV68a8QURWZDs7GwAbia9Sfg3V1dMmYLRo2G4az9hAhISkJCA77+XoX6iSjHnFmsODpgyBaNG6e+0N2mCK1fg7l56QXY2Zs1CXBzy8qBSoUGDjw4fHtq6dWuj1O7piffew0cfGaUwIosjZxACeO01/PAD1q/H8OEA4O6u3+bbcPuDyGKZebLMq6/C1hZLl+oPy6bgnDlo3BhffIG8PISEYN8+/PhjLWOloORf/8Lhw7h82YhFElkKmYMQwLx5SEmRrTYiozH/ptvffIOQEDg7lz+v1SIrCx07YsoUU02/trbGnDno1MkkhROZl7QffTVTThudPh2DBiE6Wn/o64slS9CwIRo0QLNm+pM2Npg+3XRNIDIC8wdh06YYPBhffFH+/KhRCApCly7Gr3HwYISFoaAA69ejsBBZWffZnp+oqru3R/jVV18dOnRowoQJ7dq1q3z5cXGIjsaCBTh2rPTkyy8DQFBQ6RkrK4waVfnaiEzIbFusHTyInTsxZgwA3L6NESMweXL5p6aZ1NWr8PREjRq4cUO+Si3f2bNnGzZseO9DWWWQlZV19OjRlStXduzYsVOnTp6envK34Wni4eGRlZWVmZlZvXp1AMXFxQ0aNMjIyFCpVL169Ro/fnz37t0rXPjGjejdGyUlWLoUAwcar9FE5mDmvUZ1OvTvjwsXkJwMtbz3K3U6ODigqAiFhbC3l7Vqi5Wbm+vn5+fj47Nq1SoPDw+Zaw8ODj5z5syVK1ekQ09Pz06dOkmhGBgYqJb530cVJ4SwsbHR6XRardbaWj/wc+7cufnz58+fP18aNfX393/vvfcGDx5sY2PzRIWfPYtnnkFmJj77DJ8/+mm+RBZPmFvt2gIQly7JVF1hodDp9F83aCAAceaMTFVbvnHjxgHo0KGDzvA7ksuqVasAuLm5ffLJJ//85z9dXV3L/iutXr163759D86bJ3buFBqNzG2rio4fPw7AxsZGejZZ2W/l5OTExcV5eXlJv9s6derExMRkZWU9Zsm5uaJVKwGI/v1FSYkJmk4kO/MH4TPPCEDs3ClHXX5+AhCXL+sPO3QQgNi+XY6qLd/x48dtbGysrKySk5NlrrqkpMTf3x9AXFycdKa4uPjYsWPx8fHh4eGGBaPX2rcXgLCxEW3biqgokZgoMjPvKujaNfHmm8LfX/j7i2HDxM2bMr8QCyHtUG9lZSX93po2bRoXF1dYWFj2Go1Gk5CQ0LJlS+kaFxeXqKioCxcuPLzkkhLRt68ARPPmIifHlK+BSEbmD8KwMAGIpUvlqCsoSADir7/uqnrJEjmqtnzdunUDMHr0aPmrXrhwIYCGDRveuXPnvhecO3fup59+ujNunGjVSqjVAtD/p1aL1q3FO++In34SOTmiRw8xZYooKRHFxWLiRBEaKvMLsQQrV66UduXt0qXL1KlTGzRoIEVd7dq1Y2Jibt794UCn023YsCE0NFS6xsbGJiwsbO/evQ8q/KOPBCA8PERqqulfCZFczB+E48cLQMTGylGX9GF25Ur94dixAhAzZshRtYX75ZdfpBHIzHJ9LNO7ffu29Ga9ePHix/qB3FyxYYOIiRE9eggHh9JQ3LhRNGpUOlpXVCQ8PcW5c6ZruQWKi4uTbqYOHTpUq9UKIbRabWJi4jPPPCNFnbOzc2Rk5KlTp8r94MGDB8PDww13Ezt27Lhq1apyY6rLl6/y8TlpbS02bZLvFRHJwPxBOHu2AMSoUXLUNWqUAMTs2frDGTMEIMaOlaNqS1ZQUODt7Q3gv//9r/y1z5gxA0CbNm1KKnDH6c4d8eefYto0MWSIWLtW9Op113eDg8XGjcZqp4UrKip65513AKhUqpiYmHsv2LFjR2hoqDQfWK1Wh4aG7t69u9w1Z8+ejY6OlpYetm3btuy3Dhw44Ojo6Opa7fvvlfXZgpTA/EH4228CECEhctT15ZcCENHR+sOlSwUgXn1Vjqot2UcffSS98VUkiionOztbmty/bt26ypb155+iQ4e7zgQEiAMHKltsJWk04uJFYeLJR7m5uSEhIQDs7e2XPHSs//Dhw5GRkfZ/z5O+b8/v5s2bU6ZM+e233wxnrl69Wr9+fQBvvvmmqV4DkfmYPwgPHRKAaNVKjroWLhSAGDJEf7h9uwBEx45yz5C0KKmpqXZ2dmq1es+ePfLXLmVwcHCwEcrKzha1a5dOhUpPF56eoqDACCVXzJ07YsgQ0aKFCAkRjRubbgg+PT29RYsW0vzPh9zeKysjIyMmJsb97y0N7zubxkCr1Xbu3FmaTvygm7hEVZr5gzArSwDCxUWOurZsye7UKW348F3SYXr6pVq12jRo4C1H3ZZK6kkMHz5c/qqvXLkiTevYtWuXcUqcN080by7mzhXffCOaNhWLFhmn2IqZNk0MHCiKi4UQIjNTNG0q7hmKrLw9e/bUrl0bQKtWrc494Q3R3NzcuLg4w2yaWrVq3TubRggRGRkJoEGDBlevXjVew4ksiPmDUAgRHHylc+fkmzdzTV3RiRMnpM+/0uGdO3dUKpW1tXWx9G6lPLGxsQBcXV2vX78uf+3SO+yrxh2bPnpUzJ8v4uPFyZPixg3x/vvCXJ2YoCBRtn82bZp4/33j1rB8+XIHBwcAPXv2zM7OrlghJSUlq1atetBsmtmzZwNwcHDYt2+f8RpOZFksIgilZ0rIsHwtNzcXgKOjo+FMzZo1AVy5csXUVd/rxo0bp06dkn/puuTatWvh4eEAatSoYWNjExsbK/MNwlOnTllbW1tZWZ04ccJUdXTuLADx3numKv/h6tS5a5+In38WAweKXKN92jNMEB0+fLg0QbSS7p1NM2/ePFtbW5VKtVSe5U1EZmIRQdinTx8Av/76qwx1ubi4ALh165Z0GBAQAEDmT7tFRUXR0dF16tRxdXVt37690QYGH9vixYtr1Kghffx/7rnnpK5At27dzp8/L1sbXnnlFQAjRowwYR379wsbG6FWm2fuaLmpOjNninHjRHi4aNBAREWJDRtEUVHFCtZoNG+88cZDJohWxuHDhyMiImxtbQFIS/InTpxo3CqILI1FBKE07fvrr7+Woa5mzZoBOHr0qHQoLSWWJ4MlmZmZ0tJ1W1tbaT9PtVo9dOhQeW7AXLly5aWXXpKSLzg4+PTp00KIpKSkunXrSmOk8fHxMjRj7969KpXKwcHh4sWLpq1p8uRCX9+RnToZPvrI57PPhCHmb98WbdqILVtE69alCx/r1hWjR4vNm8WTjMzfunWra9euAJycnEz37/bSpUv/+te/nJycnJ2dFXvjgJTDIoJw2rRpAN439h2U++rRoweA33//XTocMWIEgDlz5shQtRDi1KlTfn5+AGrWrLlt27b8/PyYmBhpLruTk1NMTIzpZuXpdLqEhARpomC1atXi4+PLjspev379ZekJOkDv3r0vG+Zemob0UUCOrkZRUc/gYACDBw82eV0Gx46JoiKRlye6dxfBwWLkSNGihZgwQQghdDqxe7cYP140blyaiDVrirffLly//pEjnGfOnJE+yXl6eu7fv9/Ur6NevXoApE9LRE8xiwhCaVsTI0+aeABpTOn777+XDidPngzgo48+kqHqpKQkaalyQEBA2UHI1NTUsLAww0T2xMREo1d95swZwzN3QkNDH9QPS0xMlDqpNWvWXLFihdGbIUlKSgLg7u4uTy8tLS3N2dkZwOTJk+W4I7ttm3BxEa++qh/5PH9e7Nx5/11Pjx0TMTGiRQspDv/s0sXNzS0sLCwhISE/P//ey3ft2lWrVi0ArVu3lmcQW/pslJCQIENdRGZkEUG4a9cuAO3bty93fvfu3UafwXHq1KkjR47k5eVJhwsWLAAQERFh3FruZZjaEBYWVnC/xW2bNm1q1aqVlFU9evQ4duyYUeotKSmJj4+XkqBWrVqPfFPLyMgw7DwZFhZ272T6yrcnMDAQwMyZM41b8oNkZmY2a9ZMujfcunXrxMREE8bhunX6Xd9ee+0JbgEeOyY+//yDkBD8zcXFZdCgQcuXLzck4rJly6SRg169euXItd319OnTAYwcOVKe6ojMxSKC8PLly9LbdNmTJ06csLGxCQwM3LFjh+mqXrt2LYDAwMCiis5ceLTbt98ID5fuBX755ZcPeRcuKiqKj4+XprHY2NhERUVVeE685OjRo4Zp8WFhYTdu3Hicn9LpdIbsrFOnzurVqyvThnIWL14MoF69eg9avm1chw8fbtiwIYDq1atLM4QB/OMf/9iwYYPxK1uzRtjbC0BERlbsAUWpqamxsbHt2rUzPBjZwcHh5ZdfDgsLk85ERUXJecdux44d0gCGbDUSmYVFBKFOp7Ozs1OpVGW7Slu3bpWW+qpUqtdff/2SCZ5YeOLEiTZt2ri7u6tUKk9Pz/uuJq6sy5fFs8/u7tzZ2dl5pWG374e6efNmVFSUNGGvevXqcXFxFXjv02q1sbGxdnZ20v2k//u//3vSEtLT04ODg6Xff2RkpKEPXRkajcbHxwfAwoULK1/aI61du1Z6rmFgYOCFCxc0Gk18fLzhwfcdOnTYZMTdo5ctEzY2AhDvvFP5DdUuXLgQFxfXo0cPaRfsunXrqtXq2YZNcuVSWFhoa2trZWVllP/7RBbLIoJQo9FUr17dxsZmypQpZd/0CwsLY2Njpa6Jo6NjTEzM7du3jVKjTqeLi4uTxpo8PT0bN25sWE08evRoo80O2LtX1KsnANGo0YUnHOpMTk6WcghAUFDQE3WLk5OTg4KCDBlW4ZG0kpKSuLg4KU0bNWq0bdu2ipVj8Pvvv6vV6rp165qw/y2EEEKn08XGxkpj0YMGDSrb+8zPz4+Li5N2YwHQsWPHrVu3Vra+n38W1tZ37WNrJJcvX46KigLQsmVL45b8mNq3bw9g8+bNZqmdSB7mD0KtVvviiy8aFi0FBARsv/tRuRcvXpSWfgPw8fGp/FySjIyMkL/vx4SHh+fm5op7VhP36NHj3s2In8wvvwhHR2kzU1HRpRGrVq2SRvakSS6P3EOrsLAwOjpa+k02btzYKD2eY8eOSbGqVqujoqIqM69Vo9FInzk6dOhw6NChyrftvm7fvi39g5GW2d33f2JeXl5sbKybm5vhpuxj7tJ5H999p39EorFTUJKdna1Wq+3s7Ay/+aVLl0ZERBw5csQU1ZUjxfCUKVNkqIvIXMwchIYUdHNzmzVrluFZ5Pe+6W/ZsqVNmzbSd7t3717huSSGiZG1atW6dxnWsWPH3n77bWnbKgBdOnYUP/wgnrQbqtOJmBihUglAvP220Ggq1lTJ43eLd+zYIa3NUKvVkZGR9515WDFarTYmJkbK15YtWx6oxCMdVq1aJT3HwNraOioqyujzPi5duiR1YpydnR+5zC43Nzc2NlaayivF4ZO+tLi4uDmdOwuVSphy7o+0ZMKwXuLNN9+EXGt+lixZAqBfv/4y1EVkLuYMQq1WKy3udnNzk/Z2efibfiXnkmRlZQ0ZMkR6y+vdu/dDtlXLzs6Oi4urX7/+R1266Jd5RUeLx1z6nZcnXnxRAMLa2oiPG5a6xVKH1cvLq9zkz5ycnKioKGkksFWrVn/99Zex6i1rz549UtDa2NjExMRUeNZGfn5+dHS0dPfL09MzISHBWNM4d+/eXadOHWnk4PE/KmVmZsbExEjTSlUqVWho6GP2VqdOnSp97Dhp4lueUgf322+/lQ7nzp0L4I033jBppZJz5261aZNdv765tgIkkoPZgrC4uHjQoEFSCpYblbp06ZLhTb9+/frl3vQrNpdk/fr1Xl5e0sT0x9w8RaPR5P3yi2jbVr/q2c5OvPGGePiGqOfOiZYtBSA8PEzxGO+tW7f6+/tLWd61a9fDhw8LIZKSkqRZRTY2NtHR0SZ9UI409Col7rPPPpuSklLhog4dOtShQwd9z7tLl+PHj1eybUuWLJG68s8//3wF9hC/fv16dHS0VIJarQ4LC7v3Me5lSfuVW1lZ/fDDD5Vo9WORdr5+6623pMO9e/cCaN68uanrldStKwCRmipPbURmYJ4gfEgKGpR70y93RyQ5Ofn55583zCX5888/H1RX2ffuf/zjH6kV+IPev1+Eh+tnQ0j3/BIT9dtirVghXntNvPCCGDdOXLwocnJEixbC11dUIiEerri4eN68edLDbK2traUH0UmxZKylh4+0fv16aXizQ7kH4T4habMbaVWD1MWv2OzE4uLi6Oho6fcQGRlZmR2or127Fh0dLc2ikuLwvv9gPvnkEykF5VlsvmfPHqmvLx1qNBrpEZLyLCh86SUBiB9/lKEqIvMwQxBqtUXShsvu7u4P3yaqpKTE8EZpbW0dGRlZdiWcTqdbsmSJ1M97/vnn71vC3r17jTKaJ4QQ6enivfdEtWr6OBw1SixbJtq0EX/9JTIyxDffCB8fcfu2SE8XJn570mg0Cxcu7Nevn62t7TPPPOPg4PDCCy9MmDBBU7mbkU8kKyvrrbfeMsp8jVu3bhnGdb28vJ50MlRubm6/fv2kfyHGWmBw/vz5yMhIafDWxsYmPDw8PT1d+pZOp3v33XcB2Nra/u9//zNKdY90+/ZtW1tbtVqd+/fDK+SczDltmv7fO9HTSu4gLC4Wr70mgoOXP6QvWI70Rim9K3l4eJQbC83Pz//444/vneNQVFQUGxsrbaLfsmXLgwcPGucF5OWJ+HjRrJn480/h7y/K9kTDwsSCBcap5aHy8/MBODk5HTt27Nq1a2lpadLsx6ysLBlqN5H9+/cb1v6HhoYagufhUlNTpT5x9erVjZ4KZ8+eNcShra1tZGTkxYsXhw0bBsDOzk7OjdqFEG3btgVgWMHyzjvv1K8fPHeu8Yff77V9uwAEV9XTU0zWINRqxauvCkC4u4uDBy880c+ePHmyV69e0hvlI7ebOXPmTMeOHaW5D5Wc8X9/JSWipETY24uym6WZ4Mmr91VcXCwN3BnOSDNEzPJURSOSdoOT5nA6ODg8cgvy9evXS3uIt27d+jGDswJOnjw5cOBAqcNqY2MjfQQxycY0DzVy5MgaNVp8+22SdLhoUQkgZNmdVxQWCltbYWUluKqenlbyBWFxsRg8WACiWjVR4VmNhnV1KpUqLCzs3q2Hpe3BnJycAHh7e2/ZsqWSzX4YF5e7RkG/+EJ8/LEJqytDekc2jIVKy05MFwZyysjIMEyVatKkieE5IeXEx8dLv4SQkBAZbpUdP348LCysadOmXbt2LbfOVR6LFmkBMWCAoT0CEN7eMtXerp0AhEn/mIjMSKYgNEoKSh6yxOLq1atlN4w2+cMNgoNF2X04e/QQct00knYOM6wead68OYDKT7y0HFu3bm3ZsqVhpPTChdLxg6KiotGjR0sfhqKjo42+LftDGHFp5pM6ckTaoUh/WFIiXF0FUOGtGp7MmDECEF99JUddRPKTIwil+4JGSUGDe7ebWb58uTSXsmbNmo+5q2dlbd0qGjUSS5eKnTvFuHHiuecqttVyBUg7hBme5Svt/CLDA+rkpNVq4+LipE880sMaNRpNZmZmly5dANjb2/+opImMJSXCxUUA4to1/RlpjeuaNXLU/vPPAhB9+8pRF5H8TB6EpkhBg40bNxr6DZI+ffpkZGQYuZqHOHBAfPqpGDlSfPutkLG74O3tDeDs2VmymooAAA0JSURBVLPSoXRD9CFrSKquc+fO9e/fX/qf6+fnJ22Z7eXl9ZSl/uMIDhaASNLfJRQffCAAERMjR9V//SW++05I6yqzs+//dEWiqksNE4uJwZIlcHPDhg34e1ag0XTv3v3QoUNz5861tbWtWbPm/Pnz16xZI80ckUlQECZPxrx5GDUKTk6yVSut+75z5450KK17u337tmwNkI23t/evv/66ceNGPz+/1NTU/Pz85557bu/evdIsSkVp3x4A9u69/6FJdeuG48fh6wsAixZh5kw5KiWSTaWC8I03sHJl6WG1ajh9GioVVq/Wnxk2DA0bomtXrF+v/7s1Omtr6y5dumi12mrVqo0YMcIkdViecsnnX6dO1wYNnIqKzNooE+revXtycvJvv/22ffv2rVu3Gh6lpCjSX9C+ffrDzp2RkID//EeOqq2tsWMHDhyQoy4i+VUqCIuKUFJSeqjRQAjUq4cJE1BYqD/p7IzNm02VgpKTJ08CkDYmVoh91asLlSrw7yD8t0az+cKFf+Tnm7dVJuXg4BAaGhoQECA9FkqBpAEVQxewVi1ERMDPz5hVpKUhJARnzpQ/r1Jh5kyMHHnX3zvRU8P4Q6OennjpJXzxhdELfiApCKWZkwphLQSEwN9Do5Ael/E0Do2SQaNGqFkTN27g/HnjF15Sgpkz0aYN1q3DxIn3uaBrVzRpgnnzjF81kdlVNgjHj0ebNvr/tFr9yYkTkZiI48cr27jHpMAghL09UCb5pCA05CI9pdq1A4DDh41c7LFj6NABH3yA27cRFoa5c0u/VVgIIfRf//vfmDEDN28auXYis6tsEM6ciSNH9P/Z2upPOjtj+nRERZX+CZmUEoOwXPKVy0V6GqWmYuBAXLuGfv0AYPVqFBdXtkyNRjNz5tWgIOzdC29vrFuHxETUqKH/7vbtCAzEwoX6w7p1MXYs5sypbKVElsZUs0ZfeQW2tti40UTFl9LpdKdPnwbgZ9y7JRaOPULlSUrC0KFIS9Mfvv12ZT/57Nmzp23btl9/HWZnJyIjcfQo/vlP/beyszFsGLp0wenT+Pnn0h8ZMwYNGlSqUiILZMLlE998gxs3TFe83oULFwoKCjw9PaVtJ5Wi3E1B9giVoU8fjB5thI5gYWHhuHHjOnXqdPz4cUfH63/8kR4fDxcX/XfXrkXr1liwAHZ2iInBunVITtZ/y9oaW7Zg/PjKNoDIolQqCD/+GJ07lx7+/jvq1y+9wdCkCTZvRmpq6b1DU1DiuCju6QKyR6gMQUFo166ySyZ27NgRGBgYFxcnbUl/8ODBDh18pG9dv46ICISG4tIldOiAgwcxaRJsbdGwYemPu7vDw6NSDSCyNNaV+eG7N3VBly4A7lo1HxODDRvg4oKxYytTz8NcvOgeEDA2MLC6qSqwTOW6gOwRKsbUqWjbFoMGAcC5c/jtN/Tti7+fYP1oWq02IiLi3Llz/v7+CxYskDbnk/z0k27sWPXNm3BxwVdf4Z13oDb5fhtEFsFq0qRJpivdwwNLlmDvXgwfDkdHk1Qxf75XUtI/X3892Ojb1lg0V1e0b49OneDsjFu30KwZXn4ZvXujWjVzt4xM5a+/cOcOQkLg5ITvv8fZs6hWDZ9+ivnzsWgRTp4EgIYNYf3QD7dWVlbNmzdv1qxZQkKC9FBrAFeuXImIiNi9u/bJk4169UJSEl54ASqV6V8SkWVQCRPP7HzhBWzYgPffN9W2TJ06YedObNqEbt1MUr7lysjAwIHQaODujjNnMGMGXnzR3G0iE/r6a2RlYdIk6HTo2BEHDiApCYmJWLMGGRn6a1xd0asX+vZFSAiqP8YoiRBi3rx5H374YV5eXu3aXrNmpb32mkL3KyAlM3kQHj6MoCBYW+P4cTRpYvzya9TAzZu4cgWK23Vr4EAEBuLDDwEgJQVdu+LIEdSsae5mkanExyMrS/8//OBB9OyJ8+fh7AwhsH8/Vq3C6tWlSwy9vC42bjwkNDS0X79+D5pQfebMmcjIyM2bNwMIDQ2dP39+vXr1ZHoxRJbE5EEI4K23sGgRBgzAsmVGLvn6ddSuDVdX5OQYuWRLV1wMFxdkZ8Ow39igQejbF6+/btZmkZmdP481a7BqFYqKvt2yZbR0snHjxqGhoX379u3cubP0NOPi4uK5c+d+/PHHBQUFtWvXnjNnzquvvmrWhhOZkxxBePky/PxQUIA//0THjsYseds2dOmC557D7t3GLLYKuHIFQUG4erX0zPjxqFkT0dHmaxNZkLy8vD/++GP16tVr1669+fdmMB4eHiEhIf7+/suWLdu/fz+AsLCwefPmVX+cUVSip5ccQQjg00/x5Zd47jns2mXMm/Dz52PUKLz1FhYsMFqZVUNREVxdkZsLGxv9mddfR+/eGDLErM0ii6PT6ZKTk1evXr1mzZoDBw4AcHJyKigoaNiwYXx8/AsvvGDuBhKZn0zzoydMgKenzsrqx19/TTJisdJMOaWtIQQAGxv07IkfftAfXr6MzZvRo4dZ20SWSK1Wt23bdtKkSfv37z99+vSkSZMKCgrs7e2PHj3KFCSSyNQjBLBw4S9Dhw728fE5ceKErWFb0ofKyUFBAQoLkZMDIfQ7DpfVqxfWr8fq1QgNNX6DLd3ZswgNRZMm8PDAtm2YNAkREeZuE1UBbm5uOTk5mZmZHBElksgXhCUlJQEBAceOHZs1a9a4ceMM57/99tutW7fm5+cXFBQUFBRkZWUVFBTY218+f96q7I83aYLU1PJlNmiAixeRlgYfHxlegeXR6XD2LLKy0LKlfnMZokcJCgpKTk7es2fPs88+a+62EFmESu0s80SsrKxiY2NDQ0O/+OKLiIgIw6fRnTt3Ll++vNzF9evrACsXFzg5wckJbm53bfWr0UCrhYsLFi/GyZNwd4cQilz/q1Yr9SMAVZyPj09ycvKZM2cYhEQS+YIQQJ8+fXr27Llhw4apU6fO/HuB/YgRI/r37+/k5OTk5OTi4lKtWjUnJydHR/VD9kj5/ntMmICjR9G5Mzp3hpcXjh6FovbcJqowHx8fAGfufQ49kVLJGoQAZsyYERQU9M0334wcObJJkyYAgoODK1BO06aIisKaNcZuH9HTjkFIVI7cu+r6+/tHRERotdqPP/74MX+ksBA3biA9HcnJ2LlT/4zDkBBoNFixwoRNJXoqMQiJypFvsozB5cuX/fz8CgoKJkyYULNmTWmOTE5OTl5eXkFBQWFhYVZWlpfXrwcPeuXnIzu7/GPuVSrMno2MDAwZgj59cPgwmjfn0CjR47pw4YK3t7enp+eVK1fM3RYiiyD30CiAevXqjRs37tdff50+ffqDrnFwuHPxov5re3s4OaFaNRjmzkgPJm3eHAMHYupUWRpN9LTw8vKys7O7evVqQUGBk5OTuZtDZH5m6BECKCoqSk1N/frrr52dnaVpMu7u7tIXzs7Obm5uzs6NHByqu7rC1RVWVuV/fO5cXLmCKVNQUIC2bXH5Mi5cYI+Q6HH17Jn7118uO3eqWrc2d1OILIAZeoQAbGxsWrRoER8fX8lynJwwdSpeftkojSJSCltb17w8nDkDBiERzBWElRQerh8dBfDSS0hP5/NoiZ6AtPqU02WIJFUyCF1d7zps1MhM7SCqmhiERGXJvXyCiMyOQUhUFoOQSHEYhERlmWfWKBGZkUYDR0eo1SgsLH2iJZFisUdIpDh2dqhbF8XFMKzWJVIyBiGREnF0lMiAQ6NESrRiBbKy0Ls36tUDAJ0OANR/fzAuKYFarchHm5EisUdIpDgdOuCnnzB8OOrVw5YtCA3F3LkYP770gu7dsWuX+dpHJC8GIZESpaRg1SpzN4LIMjAIiZRo+nS8/z7y883dDiILUCV3liGiSmrSBC+/jMmT0bu3/szixdi0Sf81J9GQojAIiRTq00/h74/GjfWH4eGYNUv/dZcuZmoTkTlwaJRIoZydMX06Jk82dzuIzI1BSKRcr7yCoKD7f+vCBbz9Nt56CytXytsmItlxHSGR4qSkoGFD2NsDwK1buHULrq7QaFC/fukFtWrB0RFFRYiMxNKlZmwskckxCInogRYuhLU1wsPN3Q4iU+LQKBHd39KlKChgCtLTj0FIRPexZQsWLMClS5g719xNITIxDo0SEZGisUdIRESKxiAkIiJFYxASEZGiMQiJiEjRGIRERKRoDEIiIlI0BiERESkag5CIiBSNQUhERIrGICQiIkVjEBIRkaIxCImISNEYhEREpGgMQiIiUjQGIRERKRqDkIiIFI1BSEREisYgJCIiRWMQEhGRojEIiYhI0RiERESkaAxCIiJSNAYhEREpGoOQiIgUjUFIRESKxiAkIiJFYxASEZGiMQiJiEjRGIRERKRoDEIiIlI0BiERESkag5CIiBSNQUhERIrGICQiIkVjEBIRkaIxCImISNEYhEREpGgMQiIiUjQGIRERKRqDkIiIFO3/AZtG3DAkac3KAAABk3pUWHRyZGtpdFBLTCByZGtpdCAyMDIwLjA5LjMAAHice79v7T0GIOABYkYGCBAEYiEgbmBkY0gAiTNDaGYkvgaIz8IBoZkg4kxMcL4DRB6dZnewAJvDzOaQAWIwM7JDZJhhNEIlVJwBrJCRiRvoPEYmoN0ga5mYWRlY2RjY2BXY+TOY2DkSOHgSODgzmDi5Ejh5E7i4E7h5Mph4+TKY+PgT+AQURJjY2Dk4efn4Wbk4OXi4xRlhnhU071zr8P3Jw30WP5zs359sd5A6sNtOqNnBTldxsoN2e5n9oi3T969zt3XQPP1hX8eX27bhb+wdgqfd3J8xMdd2XtxF+zeBM+wOrlhiyzOZ077KTHr/7h29tj/5LffbvYjcu+3zXxsFx4/7O75E75+/WnfPdzb3A6yLhfYtuW+3d+bupgPVzf37Qw1W7XXbFn2A/YPQgWmbevZOXsl2YMsJvgOxuUf3iGUFHujxmmUfHm24d+ND1gNFP5/bi2+/uHuaYtz+Ra7L7DVj+G3TXTgPZGz2cthc/Wm3GADYOHiv92cjGwAAAYt6VFh0TU9MIHJka2l0IDIwMjAuMDkuMwAAeJyVlDtuHDEMhvs5BS/gAZ8SWXtdGEE2gAsXuUH63B+hRg8MAhfWQAV/7fDbXyRHv9+fryhOqlYPaM/H48efv7AeeRwHUAVyALwWzWCsiIBPRsQr305lyW14wVOVuO3hWQsVeIX/Mr9cF0VPVtGeK6XUHpE77lEsqvfcKN0VJcV4h8JnWLVxoooyvGDVTUq4dwelleyioOWJfn2fkrlioxocl6tGcdzygqdJ1X6igmWcCEvwhpfMrczRIzQZnUahnR5lNdzVO8UtePAId+blRbIfMSikMilatiialTQdU8I0KS4Ezx0vKn3WOHtks0LF644XzhMpDUqraaewbnrhytQnh9F01kVkh8InBkWnOLEMCpadqWv9LbUOLxE458Vwz0veVdc3nT0vdfaofY3fpmRBuN9jxxXJXegSGdm1NURZv2RUl8jIl3DIi6693AXEEgEkd4FTZER0F7oEAfESfAPkO2RL2O1Pm5jefgK8PR/HP5p061yFPGAtAAABBXpUWHRTTUlMRVMgcmRraXQgMjAyMC4wOS4zAAB4nCWQO27EMAxEr5LSBmyB/w+Erdykyh4gSLX9nmAPH1KuqHkYDkld13bt1/Z47tfzhe/X9rO/X9Sv3/f3H319Nh1CfJwwRJAOGG5oUwYJSyk28yoYUUzTo0Ra+bGY0qSR6rraHbid4NI0I9pkmVkUNGYJ1g6jrI5iATJhKLt0v4F1P1jSLOlE2RiUeytgbBrmfmAlrFDWedKAxCwWeJ8BYNIYReLggeZ049rr5EFO2AmgayoIc2OEjNYofNvFbNb+EbJ4aN4cwVY6CB5ViXFhEuyYSls09V7ewucpdWpPqy8jvFOCcf/8A6nlU5HmcNkFAAABnXpUWHRyZGtpdFBLTDEgcmRraXQgMjAyMC4wOS4zAAB4nHu/b+09BiDgAWJGBggQBGJhIG5gZHPIANLMzIzsDhYgBiMzm4MGiMECo9khNDMhPjsD2CRGJg4GsAATG0MCkGaC0syMqHwEzcGgAKK5GVgymBgYExiZEpg4EpiYM5iYWRKYWRNY2TKYWLkU2NgT2DkymNg5Fbi4Gbh5GHgEGHh4GXj5GPj4GfgFGESYWRlYmJkY2djYOZiYWVl5eQT4+cQZYX4WvGnr69CzU9rhWpiO3bbPtQ7BrKvtZ5XPsen+6+rgZNdh91x2+e7unOf2W5dF2u/ewWu3IvyT/YE3fA55Jg12L7Ks7Xd59uzVfMtrd06y0X5G3qb9m6uLbJLrBR28qh/v/7rz1l6+fREOsXfa9ov95t53xEnWwSXT/UDXhsR9Ty8I7c/W3mb3obXT7ljumf3mnYr73Zkr7Na52x7YIddqKz1vn13cruYDaR3J+38uULdPWrjqwD4DyX1At9hOnzD9gO3sUvtGNaf9Rs/CDhz9p2Qfxhe7XwwAXCpzibqILR0AAAGOelRYdE1PTDEgcmRraXQgMjAyMC4wOS4zAAB4nJVUO07FMBDscwpfINb+7a15FAjxkCgouAE99xfr2DERosCWpbeTlx3Nztj5eLo/AFcUUd9SW2+358+vNBffti1hSegpwbHxLMZ29/ROAHD0cyYwbxVlYaZWQUarnB7Sr84/92Bxq9AqzMyGnQXQMd1XWMDZei/ZwbIHCyiuaMFcoWuBXBXOibjKIoszd19o+kIKsjIR5MJ0zmFVpxZb0wJQmy97uOsCp7tSV7TEHIWls5RSqKvCkLWWdIgfWkCPtBoLW1nTItoVcEbU2lmIltyNDi08PGU9WI6TE169/p8Fs3oZGRnjcJeEaMGXnbJrGVrAdLBwoZV7tEu4Ydq11FidxVRWMto17iCd+YqPG4XIsKalsEnvdXXpfEWX7lHky1rOOdop6bNZ5PbvjCKc8EQmoAmi4gmi8iuQCeRKED82QVTlAhD793I7Htf5T71S19QOSX8tGpAmoIQ8AbfP8AXIBJJQJ9CENoH99Lyk9Hi/bd8LIezp6bfEGAAAAQd6VFh0U01JTEVTMSByZGtpdCAyMDIwLjA5LjMAAHicJZA7bsQwDESvktILSAT/pKDSTarsAYJU7n2CPXwo2d08DYce/lx0X3wd9/V7f//x6zre58nneb75ddPX52BQC25dgMiydQRm1MnAIdo6QcR6RiD0nAKS7gujiW8sHoVxlKxZd1oU0WgSJGbBNOS2nKmLDZFW8SILstUyAUYfBfWB5CkFh2cjEKnISqRBEyGEnwWe9mT6LGkhS4pZ7r9YlMBGbLPLSmBlnp1hWCwv+p4Iltm1ypcsa9ZX2E1zdqvl/JTXseoRbXOIa6lhQ9djWBWrA4rFnq2L7CgXq76IuQ8mQ3cNzdfnH7RoUrzJL9kFAAAAAElFTkSuQmCC\n"", + ""text/plain"": [ + """" + ] + }, + ""execution_count"": 4, + ""metadata"": {}, + ""output_type"": ""execute_result"" + } + ], + ""source"": [ + ""Draw.MolsToGridImage(mols[:2])"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 5, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""ref = Chem.Mol(mols[0])"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 6, + ""metadata"": {}, + ""outputs"": [], + ""source"": [ + ""probe = mols[1]\n"", + ""temp = Chem.Mol(mols[1])"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 7, + ""metadata"": {}, + ""outputs"": [ + { + ""data"": { + ""application/3dmoljs_load.v0"": ""
\n

You appear to be running in JupyterLab (or JavaScript failed to load for some other reason). You need to install the 3dmol extension:
\n jupyter labextension install jupyterlab_3dmol

\n
\n"", + ""text/html"": [ + ""
\n"", + ""

You appear to be running in JupyterLab (or JavaScript failed to load for some other reason). You need to install the 3dmol extension:
\n"", + "" jupyter labextension install jupyterlab_3dmol

\n"", + ""
\n"", + """" + ] + }, + ""metadata"": {}, + ""output_type"": ""display_data"" + } + ], + ""source"": [ + ""# draw molecules before alignment\n"", + ""p = py3Dmol.view(width=400,height=400)\n"", + ""p.addModel(Chem.MolToMolBlock(ref), 'sdf')\n"", + ""p.addModel(Chem.MolToMolBlock(probe), 'sdf')\n"", + ""p.setStyle({'stick':{}})\n"", + ""p.setBackgroundColor('0xeeeeee')\n"", + ""p.show()"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 8, + ""metadata"": {}, + ""outputs"": [ + { + ""name"": ""stdout"", + ""output_type"": ""stream"", + ""text"": [ + ""0.7750470464618044\n"" + ] + } + ], + ""source"": [ + ""score = cpyshapeit.AlignMol(ref, temp)\n"", + ""print(score)"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": 9, + ""metadata"": {}, + ""outputs"": [ + { + ""data"": { + ""application/3dmoljs_load.v0"": ""
\n

You appear to be running in JupyterLab (or JavaScript failed to load for some other reason). You need to install the 3dmol extension:
\n jupyter labextension install jupyterlab_3dmol

\n
\n"", + ""text/html"": [ + ""
\n"", + ""

You appear to be running in JupyterLab (or JavaScript failed to load for some other reason). You need to install the 3dmol extension:
\n"", + "" jupyter labextension install jupyterlab_3dmol

\n"", + ""
\n"", + """" + ] + }, + ""metadata"": {}, + ""output_type"": ""display_data"" + } + ], + ""source"": [ + ""# draw molecules after alignment\n"", + ""p = py3Dmol.view(width=400,height=400)\n"", + ""p.addModel(Chem.MolToMolBlock(ref), 'sdf')\n"", + ""p.addModel(Chem.MolToMolBlock(temp), 'sdf')\n"", + ""p.setStyle({'stick':{}})\n"", + ""p.setBackgroundColor('0xeeeeee')\n"", + ""p.show()"" + ] + }, + { + ""cell_type"": ""code"", + ""execution_count"": null, + ""metadata"": {}, + ""outputs"": [], + ""source"": [] + } + ], + ""metadata"": { + ""kernelspec"": { + ""display_name"": ""Python 3"", + ""language"": ""python"", + ""name"": ""python3"" + }, + ""language_info"": { + ""codemirror_mode"": { + ""name"": ""ipython"", + ""version"": 3 + }, + ""file_extension"": "".py"", + ""mimetype"": ""text/x-python"", + ""name"": ""python"", + ""nbconvert_exporter"": ""python"", + ""pygments_lexer"": ""ipython3"", + ""version"": ""3.7.9"" + } + }, + ""nbformat"": 4, + ""nbformat_minor"": 4 +} +","Unknown" +"In Silico","rdkit/shape-it","include/moleculeRotation.h",".h","2199","58","/******************************************************************************* +moleculeRotation.h - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#ifndef __SILICOSIT_SHAPEIT_MOLECULEROTATION_H__ +#define __SILICOSIT_SHAPEIT_MOLECULEROTATION_H__ + +// General + +// Shape-it +#include +#include +#ifndef USE_RDKIT +namespace OpenBabel { +class OBMol; +} +using Molecule = OpenBabel::OBMol; +#else +namespace RDKit { +class ROMol; +} +using Molecule = RDKit::ROMol; +#endif +void positionMolecule(Molecule &, const Coordinate &, const SiMath::Matrix &); +void repositionMolecule(Molecule &, const SiMath::Matrix &, const Coordinate &); +void rotateMolecule(Molecule &, const SiMath::Vector &); + +#endif +","Unknown" +"In Silico","rdkit/shape-it","include/bestResults.h",".h","2579","75","/******************************************************************************* +bestResults.h - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#ifndef __SILICOSIT_SHAPEIT_BESTRESULTS_H__ +#define __SILICOSIT_SHAPEIT_BESTRESULTS_H__ + +// General +#include +#include +#include +#include + +// OpenBabel + +// Shape-it +#include + +class BestResults { +private: + std::vector _bestList; ///< Local list to best N solutions + + double _lowest; ///< lowest score in the list + unsigned int _size; ///< total number of elements to be stored in the list + unsigned int _filled; ///< number of elements stored in the list sofar + + class _compInfo { + public: + bool operator()(const SolutionInfo *a, const SolutionInfo *b) { + return a->score > b->score; + }; + }; + +public: + BestResults(unsigned int n = 100); + ~BestResults(void); + + bool add(SolutionInfo &res); + + void writeMolecules(Options *); + void writeScores(Options *); + const std::vector &getBestList() const { return _bestList; }; +}; + +#endif +","Unknown" +"In Silico","rdkit/shape-it","include/gaussianVolume.h",".h","3414","99","/******************************************************************************* +gaussianVolume.h - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#ifndef __SILICOSIT_SHAPEIT_GAUSSIANVOLUME_H__ +#define __SILICOSIT_SHAPEIT_GAUSSIANVOLUME_H__ + +// General +#include +#include +#include +#include +#include + +// Shape-it +#include +#include +#include +#include +#include + +const double GCI = 2.828427125; +const double GLI = 1.480960979; +const double VCUTOFF = 2.0; +const unsigned int LEVEL = 6; +const double EPS = 0.03; +const double GRADSCALE = 0.9; +const double PENALTY = 5.00; + +#ifndef USE_RDKIT +namespace OpenBabel { +class OBMol; +} +using Molecule = OpenBabel::OBMol; +#else +namespace RDKit { +class ROMol; +} +using Molecule = RDKit::ROMol; +#endif + +class GaussianVolume { +public: + double volume; ///< Molecular volume + double overlap; ///< Self-overlap of the molecule + Coordinate centroid; ///< center of the gaussian volume + SiMath::Matrix + rotation; ///< rotation matrix to align molecule to principal axes + std::vector + gaussians; ///< vector of all atom gaussians and their overlaps + std::vector *> + childOverlaps; ///< vector to keep track of which overlaps are formed with + ///< one gaussian + std::vector + levels; ///< indicates where in the vector the level of overlaps changes + + GaussianVolume(void); + ~GaussianVolume(void); +}; + +void listAtomVolumes(const Molecule &mol, GaussianVolume &gv); +void initOrientation(GaussianVolume &); +double atomOverlap(const GaussianVolume &, const GaussianVolume &); +double GAlpha(unsigned int); +double getScore(const std::string &, double, double, double); +void checkVolumes(const GaussianVolume &, const GaussianVolume &, + AlignmentInfo &); + +#endif +","Unknown" +"In Silico","rdkit/shape-it","include/solutionInfo.h",".h","2624","87","/******************************************************************************* +solutionInfo.h - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#ifndef __SILICOSIT_SHAPEIT_SOLUTIONINFO_H__ +#define __SILICOSIT_SHAPEIT_SOLUTIONINFO_H__ + +// General +#include +#include + +#ifndef USE_RDKIT +// OpenBabel +#include +#else +#include +#endif + +// Shape-it +#include +#include +#include +#include +#include + +class SolutionInfo { +public: + std::string refName; + double refAtomVolume; + Coordinate refCenter; + SiMath::Matrix refRotation; + +#ifndef USE_RDKIT + OpenBabel::OBMol dbMol; +#else + RDKit::RWMol dbMol; +#endif + std::string dbName; + double dbAtomVolume; + Coordinate dbCenter; + SiMath::Matrix dbRotation; + + double atomOverlap; + double score; + SiMath::Vector rotor; + + SolutionInfo(void); + ~SolutionInfo(void); + + void printScores(Options &); +}; + +void setAllScores(SolutionInfo &); +void updateSolutionInfo(SolutionInfo &, const AlignmentInfo &, double, + const GaussianVolume &); + +#endif +","Unknown" +"In Silico","rdkit/shape-it","include/options.h",".h","2709","81","/******************************************************************************* +options.h - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#ifndef __SILICOSIT_SHAPEIT_OPTIONS_H__ +#define __SILICOSIT_SHAPEIT_OPTIONS_H__ + +// General +#include +#include +#include + +// Shape-it +const std::string tanimoto = ""Shape-it::Tanimoto""; +const std::string tversky_ref = ""Shape-it::Tversky_Ref""; +const std::string tversky_db = ""Shape-it::Tversky_Db""; + +class Options { +public: + std::string format; // -f + std::string refInpFile; // -r --reference + std::ifstream *refInpStream; + + std::string dbInpFile; // -d --dbase + std::ifstream *dbInpStream; + + std::string molOutFile; // -o --out + std::ofstream *molOutStream; + + std::string scoreOutFile; // -s --score + std::ofstream *scoreOutStream; + + unsigned int bestHits; // --best + double cutOff; // --cutOff + double maxIter; // --maxIterations + + std::string whichScore; // --rankBy + + bool scoreOnly; // --scoreOnly + bool showRef; // --noRef + + bool version; // -v --version + bool help; // -h --help + + Options(void); + ~Options(void); + + std::string print(void) const; +}; + +#endif +","Unknown" +"In Silico","rdkit/shape-it","include/mainErr.h",".h","1852","49","/******************************************************************************* +mainErr.h - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#ifndef __SILICOSIT_SHAPEIT_MAINERR_H__ +#define __SILICOSIT_SHAPEIT_MAINERR_H__ + +// General +#include +#include +#include + +// OpenBabel + +// Shape-it + +void mainErr(const std::string &); + +#endif +","Unknown" +"In Silico","rdkit/shape-it","include/shapeAlignment.h",".h","2621","79","/******************************************************************************* +shapeAlignment.h - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#ifndef __SILICOSIT_SHAPEIT_SHAPEALIGNMENT_H__ +#define __SILICOSIT_SHAPEIT_SHAPEALIGNMENT_H__ + +// General +#include +#include +#include + +// OpenBabel + +// Shape-it +#include +#include +#include +#include + +using MatrixMap = std::map; +using MatIter = std::map::iterator; + +class ShapeAlignment { +private: + const GaussianVolume *_gRef; + const GaussianVolume *_gDb; + + unsigned int _rAtoms; + unsigned int _rGauss; + unsigned int _dAtoms; + unsigned int _dGauss; + unsigned int _maxSize; + unsigned int _maxIter; + + MatrixMap _matrixMap; + + double *_updateMatrixMap(const AtomGaussian &, const AtomGaussian &); + +public: + ShapeAlignment(const GaussianVolume &, const GaussianVolume &); + ~ShapeAlignment(); + + AlignmentInfo gradientAscent(SiMath::Vector); + AlignmentInfo simulatedAnnealing(SiMath::Vector); + + void setMaxIterations(unsigned int); +}; + +#endif","Unknown" +"In Silico","rdkit/shape-it","include/printHeader.h",".h","1821","46","/******************************************************************************* +printHeader.h - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#ifndef __SILICOSIT_SHAPEIT_PRINTHEADER_H__ +#define __SILICOSIT_SHAPEIT_PRINTHEADER_H__ + +// General +#include + +// Shape-it +#include + +void printHeader(void); + +#endif +","Unknown" +"In Silico","rdkit/shape-it","include/config.h",".h","81","4","#define SHAPEIT_VERSION 2 +#define SHAPEIT_RELEASE 0 +#define SHAPEIT_SUBRELEASE 0 +","Unknown" +"In Silico","rdkit/shape-it","include/coordinate.h",".h","1976","57","/******************************************************************************* +coordinate.h - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#ifndef __SILICOSIT_SHAPEIT_COORDINATE_H__ +#define __SILICOSIT_SHAPEIT_COORDINATE_H__ + +// General +#include + +// OpenBabel + +// Shape-it + +class Coordinate { +public: + double x; + double y; + double z; + + Coordinate(void); + Coordinate(double, double, double); +}; + +std::ostream &operator<<(std::ostream &, const Coordinate &); + +#endif +","Unknown" +"In Silico","rdkit/shape-it","include/printUsage.h",".h","1836","48","/******************************************************************************* +printUsage.h - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#ifndef __SILICOSIT_SHAPEIT_PRINTUSAGE_H__ +#define __SILICOSIT_SHAPEIT_PRINTUSAGE_H__ + +// General +#include + +// OpenBabel + +// Shape-it +#include + +void printUsage(void); + +#endif +","Unknown" +"In Silico","rdkit/shape-it","include/siMath.h",".h","9432","275","/******************************************************************************* +siMath.h - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#ifndef __SILICOS_PHARAO_SIMATH_H__ +#define __SILICOS_PHARAO_SIMATH_H__ + +// General +#include +#include +#include + +// OpenBabel + +// Shape-it +#ifndef INF +#define INF HUGE_VAL +#endif + +#ifndef PI +#define PI 3.14159265358979323846 +#endif + +#ifndef TAU +#define TAU 1e-12 +#endif + +#ifndef min +template inline T min(T x, T y) { return (x < y) ? x : y; } +#endif + +#ifndef max +template inline T max(T x, T y) { return (x > y) ? x : y; } +#endif + +#ifndef sign +template inline T sign(const T &a, const T &b) { + return (b >= 0.0) ? (a >= 0 ? a : -a) : (a >= 0 ? -a : a); +} +#endif + +namespace SiMath { + +inline double triangle(const double &a, const double &b) { + double A(fabs(a)), B(fabs(b)); + if (A > B) { + return A * sqrt(1.0 + (B / A) * (B / A)); + } else if (B == 0) { + return 0; + } + return B * sqrt(1.0 + (A / B) * (A / B)); +} + +class Vector { +private: + unsigned int _n; ///< Number of data points in vector + std::vector _pVector; ///< std::vector to hold all values + +public: + Vector() : _n(0), _pVector(0){}; ///< Empty vector + Vector(const unsigned int n) + : _n(n), _pVector(n){}; ///< vector of length n, no initial value + Vector(const unsigned int n, const double &v) + : _n(n), + _pVector(n, v){}; ///< vector of length n, initial constant value v + Vector(const unsigned int n, + const double *); ///< Copy of data stored in an array double[n] + Vector(const std::vector + &); ///< Copy of data stored in std::vector + + Vector(const Vector &); + + ~Vector(); + + void clear(); + void reset(unsigned int); + + void resize(unsigned int); + + double getValueAt(const unsigned int); + double getValueAt(const unsigned int) const; + + double max() const; + double max(unsigned int &) const; + double min() const; + double min(unsigned int &) const; + double sum() const; + double mean() const; + double stDev() const; + double stDev(double m) const; + unsigned int size() const { return _n; }; + + Vector &operator=(const Vector &); ///< copy assignment, resets the size of + ///< the Vector if needed + Vector & + operator=(const double &); ///< set all elements in Vector to constant value + Vector & + operator+=(const double &); ///< add constant value to all elements in Vector + Vector &operator+=(const Vector &); ///< add full Vector element-wise + Vector &operator-=( + const double &); ///< subtract constant value to all elements in Vector + Vector &operator-=(const Vector &); ///< subtract full Vector element-wise + Vector & + operator*=(const double &); ///< multiply all elements with a constant value + Vector &operator*=(const Vector &); ///< multiply full Vector element-wise + Vector & + operator/=(const double &); ///< divide all elements with a constant value + Vector &operator/=(const Vector &); ///< divide full Vector element-wise + Vector &operator-(); ///< change sign of all elements in Vector + Vector operator+(const Vector &) const; ///< operator to write C = A + B + Vector operator-(const Vector &) const; ///< operator to write C = A - B + Vector operator*(const Vector &) const; ///< operator to write C = A * B + Vector operator/(const Vector &) const; ///< operator to write C = A / B + + bool operator==( + const Vector &) const; ///< check if two vectors are the same, which is + ///< only true if all elements are the same + bool operator!=(const Vector &) const; ///< check if two vectors are different + + inline double &operator[](const unsigned int i) { + return _pVector[i]; + }; ///< set i-th element from vector + inline double operator[](const unsigned int i) const { + return _pVector[i]; + }; ///< get i-th element from vector (const implementation) + + void swap(const unsigned int, const unsigned int); + + double dotProd(const Vector &); + + const double *getArrayPointer() const { + return &(_pVector[0]); + }; ///< direct access to the data + double *getArrayPointer() { + return &(_pVector[0]); + }; ///< direct access to the data +}; + +class Matrix { +private: + unsigned int _nRows; + unsigned int _nCols; + double **_pMatrix; + +public: + Matrix() : _nRows(0), _nCols(0), _pMatrix(NULL){}; + Matrix(const unsigned int, const unsigned int); + Matrix(const unsigned int, const unsigned int, const double &); + Matrix(const Matrix &); + + Matrix(const unsigned int, const unsigned int, const Vector &); + + ~Matrix(); + + void reset(const unsigned int, const unsigned int); + void clear(); + + inline unsigned int nbrRows() const { return _nRows; }; + inline unsigned int nbrColumns() const { return _nCols; }; + + double getValueAt(const unsigned int, const unsigned int); + const double getValueAt(const unsigned int, const unsigned int) const; + Vector getRow(const unsigned int) const; + Vector getColumn(const unsigned int) const; + + void setValueAt(const unsigned int, const unsigned int, double); + void setRow(const unsigned int, Vector &); + void setColumn(const unsigned int, Vector &); + + void swapRows(unsigned int, unsigned int); + void swapColumns(unsigned int, unsigned int); + Matrix transpose(void); + + Matrix &operator=(const Matrix &); ///< copy assignment, resets the size of + ///< the matrix if needed + Matrix & + operator=(const double &); ///< set all elements in matrix to constant value + Matrix & + operator+=(const double &); ///< add constant value to all elements in matrix + Matrix &operator+=(const Matrix &); ///< add full matrix element-wise + Matrix &operator-=( + const double &); ///< subtract constant value from all elements in matrix + Matrix &operator-=(const Matrix &); ///< subtract full matrix element-wise + Matrix & + operator*=(const double &); ///< multiply all elements with a constant value + Matrix &operator*=(const Matrix &); ///< multiply full matrix element-wise + Matrix & + operator/=(const double &); ///< divide all elements with a constant value + Matrix &operator/=(const Matrix &); ///< divide full matrix element-wise + Matrix &operator-(); ///< change sign of all elements in matrix + + Matrix + operator+(const Matrix &) const; ///< add two matrices element by element and + ///< store the result in a new matrix + Matrix operator-( + const Matrix &) const; ///< substract two matrices element by element and + ///< store the result in a new matrix + Matrix + operator*(const Matrix &) const; ///< multiply two matrices element by element + ///< and store the result in a new matrix + Matrix + operator/(const Matrix &) const; ///< divide two matrices element by element + ///< and store the result in a new matrix + + inline double *operator[](const unsigned int i) { return _pMatrix[i]; }; + inline const double *operator[](const unsigned int i) const { + return _pMatrix[i]; + }; +}; + +Vector rowProduct(const Matrix &A, const Vector &U); +Vector colProduct(const Vector &U, const Matrix &A); + +class SVD { +public: + SVD(const Matrix &, bool bU = true, bool bV = true); + + Vector getSingularValues() { return _S; }; + Matrix getSingularMatrix(); + + Matrix getU() { return _U; }; + Matrix getV() { return _V; }; + + double norm2() { return _S[0]; }; + + double cond() { return _S[0] / _S[_S.size() - 1]; }; + + int rank(); + +private: + int _m; ///< number of rows + int _n; ///< number of columns + Matrix _U; ///< Left singular vectors + Matrix _V; ///< Right singular vectors + Vector _S; ///< Singular values + + bool _computeV; ///< Check if V should be computed + bool _computeU; ///< Check if U should be computed +}; + +double randD(double, double); + +}; // end of namespace SiMath + +#endif +","Unknown" +"In Silico","rdkit/shape-it","include/alignLib.h",".h","2731","65","/******************************************************************************* +alignLib.h - Shape-it + +Copyright 2021 by Greg Landrum and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ +#ifndef SHAPEIT_ALIGNLIB_H +#define SHAPEIT_ALIGNLIB_H + +#include ""bestResults.h"" +#include ""gaussianVolume.h"" +#include ""options.h"" +#include ""solutionInfo.h"" +#include + +#ifndef USE_RDKIT +#include +using Molecule = OpenBabel::OBMol; +#else +#include +using Molecule = RDKit::ROMol; +#endif + +namespace shapeit { +SolutionInfo alignMols(const Molecule &refMol, const Molecule &dbMol, + const std::string &whichScore = tanimoto, + double maxIter = 0, double cutoff = 0.0, + BestResults *bestHits = nullptr); + +SolutionInfo alignMolToVolume(const GaussianVolume &refVolume, + const Molecule &dbMol, + const std::string &whichScore = tanimoto, + double maxIter = 0, double cutoff = 0.0, + BestResults *bestHits = nullptr); + +SolutionInfo alignVolumes(const GaussianVolume &refVolume, + const GaussianVolume &dbVolume, + const std::string &whichScore, double maxIter); +} // namespace shapeit +#endif","Unknown" +"In Silico","rdkit/shape-it","include/alignmentInfo.h",".h","2018","54","/******************************************************************************* +alignmentInfo.h - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#ifndef __SILICOSIT_SHAPEIT_ALIGNMENTINFO_H__ +#define __SILICOSIT_SHAPEIT_ALIGNMENTINFO_H__ + +// General +#include + +// Shape-it +#include +#include + +class AlignmentInfo { +public: + double overlap; ///< volume overlap of the atom gaussians + SiMath::Vector rotor; ///< optimal rotation + + AlignmentInfo(void); + ~AlignmentInfo(void); +}; + +#endif +","Unknown" +"In Silico","rdkit/shape-it","include/atomGaussian.h",".h","2292","60","/******************************************************************************* +atomGaussian.h - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#ifndef __SILICOSIT_SHAPEIT_ATOMGAUSSIAN_H__ +#define __SILICOSIT_SHAPEIT_ATOMGAUSSIAN_H__ + +// General +#include + +// OpenBabel + +// Shape-it +#include +#include + +class AtomGaussian { +public: + Coordinate center; ///< center of the gaussian + double alpha; ///< alpha parameter of the gaussian representation + double volume; ///< self-volume of the gaussian + double C; ///< constant from gaussian g(r) = C.exp(-alpha(center -r )^2) + unsigned int nbr; ///< nbr of atoms that make up this overlap + + AtomGaussian(void); + ~AtomGaussian(void); +}; + +AtomGaussian atomIntersection(AtomGaussian &, AtomGaussian &); + +#endif","Unknown" +"In Silico","rdkit/shape-it","include/parseCommandLine.h",".h","1939","51","/******************************************************************************* +parseCommandLine.h - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#ifndef __SILICOSIT_SHAPEIT_PARSECOMMANDLINE_H__ +#define __SILICOSIT_SHAPEIT_PARSECOMMANDLINE_H__ + +// General +#include +#include +#include + +// OpenBabel + +// Shape-it +#include +#include + +Options parseCommandLine(int argc, char *argv[]); + +#endif +","Unknown" +"In Silico","rdkit/shape-it","src/solutionInfo.cpp",".cpp","4030","113","/******************************************************************************* +solutionInfo.cpp - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#include + +#ifndef USE_RDKIT +// OpenBabel +#include +#endif + +SolutionInfo::SolutionInfo() + : refName(""""), refAtomVolume(0.0), refCenter(0, 0, 0), refRotation(3, 3, 0), + dbName(""""), dbAtomVolume(0.0), dbMol(), dbCenter(0, 0, 0), + dbRotation(3, 3, 0), atomOverlap(0.0), score(0.0), rotor(4, 0.0) { + rotor[0] = 1.0; +} + +SolutionInfo::~SolutionInfo() = default; + +void SolutionInfo::printScores(Options &uo) { + *(uo.scoreOutStream) + << dbName << ""\t"" << refName << ""\t"" << std::setprecision(3) + << atomOverlap / (refAtomVolume + dbAtomVolume - atomOverlap) << ""\t"" + << std::setprecision(3) + << atomOverlap / (0.95 * refAtomVolume + 0.05 * dbAtomVolume) << ""\t"" + << std::setprecision(3) + << atomOverlap / (0.05 * refAtomVolume + 0.95 * dbAtomVolume) << ""\t"" + << std::setprecision(5) << atomOverlap << ""\t"" << std::setprecision(5) + << refAtomVolume << ""\t"" << std::setprecision(5) << dbAtomVolume + << std::endl; + return; +} + +void updateSolutionInfo(SolutionInfo &s, const AlignmentInfo &res, double score, + const GaussianVolume &gv) { + s.dbAtomVolume = gv.overlap; + s.dbCenter = gv.centroid; + s.dbRotation = gv.rotation; + s.atomOverlap = res.overlap; + s.score = score; + s.rotor = res.rotor; + return; +} + +void setAllScores(SolutionInfo &res) { + std::ostringstream ss; + + ss.str(""""); + ss << res.atomOverlap / + (res.refAtomVolume + res.dbAtomVolume - res.atomOverlap); +#ifndef USE_RDKIT + OpenBabel::OBPairData *label1 = new OpenBabel::OBPairData(); + label1->SetAttribute(tanimoto); + label1->SetValue(ss.str()); + res.dbMol.SetData(label1); +#else + res.dbMol.setProp(tanimoto, ss.str()); +#endif + ss.str(""""); + ss << res.atomOverlap / (0.95 * res.refAtomVolume + 0.05 * res.dbAtomVolume); +#ifndef USE_RDKIT + OpenBabel::OBPairData *label2 = new OpenBabel::OBPairData(); + label2->SetAttribute(tversky_ref); + label2->SetValue(ss.str()); + res.dbMol.SetData(label2); +#else + res.dbMol.setProp(tversky_ref, ss.str()); +#endif + + ss.str(""""); + ss << res.atomOverlap / (0.05 * res.refAtomVolume + 0.95 * res.dbAtomVolume); +#ifndef USE_RDKIT + OpenBabel::OBPairData *label3 = new OpenBabel::OBPairData(); + label3->SetAttribute(tversky_db); + label3->SetValue(ss.str()); + res.dbMol.SetData(label3); +#else + res.dbMol.setProp(tversky_db, ss.str()); +#endif + + return; +} +","C++" +"In Silico","rdkit/shape-it","src/coordinate.cpp",".cpp","1928","44","/******************************************************************************* +coordinate.cpp - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#include + +Coordinate::Coordinate() : x(0.0), y(0.0), z(0.0) {} + +Coordinate::Coordinate(double x, double y, double z) : x(x), y(y), z(z){}; + +std::ostream &operator<<(std::ostream &os, const Coordinate &A) { + os << ""("" << A.x << "","" << A.y << "","" << A.z << "")""; + return os; +}; +","C++" +"In Silico","rdkit/shape-it","src/printUsage.cpp",".cpp","8752","193","/******************************************************************************* +printUsage.cpp - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#include + +void printUsage() { + std::cerr << std::endl; + std::cerr << ""TASK:"" << std::endl << std::endl; + std::cerr << "" Shape-it is a tool to align pairs of molecules based on "" + ""their maximal"" + << std::endl; + std::cerr << "" volume overlap."" << std::endl; + std::cerr << std::endl; + std::cerr << std::endl; + std::cerr << ""REQUIRED OPTIONS: "" << std::endl; + std::cerr << "" -r, --reference "" << std::endl; + std::cerr << "" File of the reference molecule with 3D coordinates."" + << std::endl; + std::cerr << "" Only the first molecule in the reference file will "" + ""be used."" + << std::endl; + std::cerr << "" Shape-it can also handle a gzipped files if the "" + ""extension is '.gz'"" + << std::endl; + std::cerr << "" All input formats which are recognized by OpenBabel "" + ""are allowed."" + << std::endl; + std::cerr << "" -d, --dbase "" << std::endl; + std::cerr << "" File of the database molecules with 3D coordinates."" + << std::endl; + std::cerr << "" Shape-it can also handle gzipped files if the "" + ""extension is '.gz'"" + << std::endl; + std::cerr << "" All input formats which are recognized by OpenBabel "" + ""are allowed."" + << std::endl; + std::cerr << std::endl; + std::cerr << std::endl; + std::cerr << ""OUTPUT OPTIONS: "" << std::endl; + std::cerr << ""One of these two output options is required:"" << std::endl; + std::cerr << std::endl; + std::cerr << "" -o, --out "" << std::endl; + std::cerr << "" File to write all database or the N best molecules "" + ""such that their"" + << std::endl; + std::cerr << "" coordinates correspond to the best alignment with "" + ""the reference molecule."" + << std::endl; + std::cerr << "" The first molecule in the file is the reference "" + ""molecule. When this file"" + << std::endl; + std::cerr << "" if of type 'sdf', then each molecule contains a set "" + ""of properties in which"" + << std::endl; + std::cerr << "" the respective scores are reported. These fields "" + ""are labeled with an"" + << std::endl; + std::cerr << "" identifier starting with the tag Shape-it::"" + << std::endl; + std::cerr << std::endl; + std::cerr << "" -s, --scores "" << std::endl; + std::cerr + << "" Tab-delimited text file with the scores of molecules."" + << std::endl; + std::cerr << "" When the N best scoring molecules are reported the "" + ""molecules are ranked"" + << std::endl; + std::cerr << "" with the descending scores."" << std::endl; + std::cerr << std::endl; + std::cerr << std::endl; + std::cerr << ""OPTIONAL OPTIONS: "" << std::endl; + std::cerr << std::endl; + std::cerr << "" -f, --format "" << std::endl; + std::cerr << "" Specifies the format of the reference, database and "" + ""output files. If not"" + << std::endl; + std::cerr << "" provided, then the formats are determined from the "" + ""respective file extensions."" + << std::endl; + std::cerr << "" The specified format string should be one of the "" + ""formats recognised"" + << std::endl; + std::cerr << "" by OpenBabel."" << std::endl; + std::cerr << std::endl; + std::cerr << "" --best "" << std::endl; + std::cerr << "" When this option is used, only the N best scoring "" + ""alignments will be"" + << std::endl; + std::cerr << "" reported. The scoring function is defined by the "" + ""--rankBy option."" + << std::endl; + std::cerr << "" By default all molecules in the database are "" + ""reported with their"" + << std::endl; + std::cerr << "" respective scores without any ordering."" + << std::endl; + std::cerr << std::endl; + std::cerr << "" --scoreOnly"" << std::endl; + std::cerr << "" When this option is used the molecules are not "" + ""aligned, only the volume"" + << std::endl; + std::cerr << "" overlap between the reference and the given pose is "" + ""computed."" + << std::endl; + std::cerr << std::endl; + std::cerr << "" --addIterations "" << std::endl; + std::cerr << "" Sets the number of additional iterations in the "" + ""simulated annealing"" + << std::endl; + std::cerr << "" optimization step. The default value is set to 0, "" + ""which refers to only"" + << std::endl; + std::cerr << "" a local gradient ascent. Increasing the number of "" + ""iterations will add"" + << std::endl; + std::cerr << "" additional steps, and might give better alignments "" + ""but it also takes"" + << std::endl; + std::cerr << "" more time."" << std::endl; + std::cerr << std::endl; + std::cerr << "" --rankBy "" << std::endl; + std::cerr << "" This option can be used in combination with --best "" + ""of --cutoff to rank"" + << std::endl; + std::cerr << "" the molecules according to a given scoring "" + ""function. The type of scoring"" + << std::endl; + std::cerr << "" function is indicated with a code:"" << std::endl; + std::cerr << "" - TANIMOTO = Taninoto"" << std::endl; + std::cerr << "" - TVERSKY_REF = reference Tversky"" << std::endl; + std::cerr << "" - TVERSKY_DB = database Tversky"" << std::endl; + std::cerr << "" By default TANIMOTO is used."" << std::endl; + std::cerr << std::endl; + std::cerr << "" --cutoff "" << std::endl; + std::cerr << "" Defines a cutoff value. Only molecules with a score "" + ""higher than the"" + << std::endl; + std::cerr << "" cutoff are reported in the results files. Default "" + ""value is set to"" + << std::endl; + std::cerr << "" 0.0. The scoring function is defined by the "" + ""--rankBy option."" + << std::endl; + std::cerr << std::endl; + std::cerr << "" --noRef"" << std::endl; + std::cerr << "" By default the reference molecule is written in the "" + ""output files."" + << std::endl; + std::cerr << "" Use this option to switch off this behavior."" + << std::endl; + std::cerr << std::endl; + std::cerr << std::endl; + std::cerr << ""HELP: "" << std::endl; + std::cerr << std::endl; + std::cerr << "" -h, --help"" << std::endl; + std::cerr << "" Prints this help overview."" << std::endl; + std::cerr << std::endl; + std::cerr << "" -v, --version"" << std::endl; + std::cerr << "" Prints the version of the program."" << std::endl; + std::cerr << std::endl; + return; +} +","C++" +"In Silico","rdkit/shape-it","src/options.cpp",".cpp","3825","138","/******************************************************************************* +options.cpp - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#include +#include + +Options::Options() { + refInpFile = """"; + refInpStream = nullptr; + + dbInpFile = """"; + dbInpStream = nullptr; + + molOutFile = """"; + molOutStream = nullptr; + + scoreOutFile = """"; + scoreOutStream = nullptr; + + bestHits = 0; + cutOff = 0.0; + maxIter = 0; + + whichScore = tanimoto; + + scoreOnly = false; + showRef = true; + + version = false; + help = false; +} + +Options::~Options() { + // reference input + if (!refInpFile.empty()) { + refInpFile = """"; + }; + if (refInpStream) { + delete refInpStream; + refInpStream = nullptr; + }; + + // Database input + if (!dbInpFile.empty()) { + dbInpFile = """"; + }; + if (dbInpStream) { + delete dbInpStream; + dbInpStream = nullptr; + }; + + // Molecule output + if (!molOutFile.empty()) { + molOutFile = """"; + }; + if (molOutStream) { + delete molOutStream; + molOutStream = nullptr; + }; + + // Score output + if (!scoreOutFile.empty()) { + scoreOutFile = """"; + }; + if (scoreOutStream) { + delete scoreOutStream; + scoreOutStream = nullptr; + }; +} + +std::string Options::print() const { + std::ostringstream os; + os << std::endl; + os << ""COMMAND_LINE OPTIONS:"" << std::endl; + os << std::endl; + os << "" -> Reference file: "" << refInpFile << std::endl; + os << "" -> Database file: "" << dbInpFile << std::endl; + os << "" -> Output file: "" << (molOutFile.empty() ? ""no"" : molOutFile) + << std::endl; + os << "" -> Scores file: "" + << (scoreOutFile.empty() ? ""no"" : scoreOutFile) << std::endl; + os << "" -> Best hits: ""; + if (bestHits) { + os << bestHits << std::endl; + } else { + os << ""no"" << std::endl; + } + os << "" -> Scoring only: "" << (scoreOnly ? ""yes"" : ""no"") << std::endl; + os << "" -> Extra iterations: ""; + if (maxIter) { + os << maxIter << std::endl; + } else { + os << ""no"" << std::endl; + } + os << "" -> Rank by: "" << whichScore << std::endl; + os << "" -> Cutoff: ""; + if (cutOff) { + os << cutOff << std::endl; + } else { + os << ""no"" << std::endl; + } + os << "" -> Output reference "" << (showRef ? ""yes"" : ""no"") << std::endl; + + os << std::endl; + std::string r = os.str(); + return r; +} +","C++" +"In Silico","rdkit/shape-it","src/siMath.cpp",".cpp","26205","1032","/******************************************************************************* +siMath.cpp - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#include + +using namespace SiMath; + +Vector::Vector(const unsigned int n, const double *v) : _n(n), _pVector(n) { + for (unsigned int i = 0; i < _n; ++i) + _pVector[i] = v[i]; +} + +Vector::Vector(const std::vector &v) : _n(v.size()), _pVector(_n) { + for (unsigned int i = 0; i < _n; ++i) + _pVector[i] = v[i]; +} + +Vector::Vector(const Vector &v) : _n(v._n), _pVector(_n) { + for (unsigned int i = 0; i < _n; ++i) + _pVector[i] = v._pVector[i]; +} + +Vector::~Vector() { _pVector.clear(); } + +void Vector::clear() { + _pVector.clear(); + _n = 0; +} + +void Vector::reset(unsigned int n) { + if (_n != n) // only reset the vector itself if the new size is larger + _pVector.resize(n); + _n = n; + for (unsigned int i = 0; i < _n; ++i) + _pVector[i] = 0; +} + +void Vector::resize(unsigned int n) { + if (_n != n) + _pVector.resize(n); + _n = n; +} + +double Vector::getValueAt(const unsigned int i) { return _pVector[i]; } + +double Vector::getValueAt(const unsigned int i) const { return _pVector[i]; } + +double Vector::max() const { + double d = _pVector[0]; + for (unsigned int i = 1; i < _n; ++i) { + if (_pVector[i] > d) { + d = _pVector[i]; + } + } + return d; +} + +double Vector::max(unsigned int &index) const { + double d = _pVector[0]; + for (unsigned int i = 1; i < _n; ++i) { + if (_pVector[i] > d) { + d = _pVector[i]; + index = i; + } + } + return d; +} + +double Vector::min() const { + double d = _pVector[0]; + for (unsigned int i = 1; i < _n; ++i) { + if (_pVector[i] < d) { + d = _pVector[i]; + } + } + return d; +} + +double Vector::min(unsigned int &index) const { + double d = _pVector[0]; + for (unsigned int i = 1; i < _n; ++i) { + if (_pVector[i] > d) { + d = _pVector[i]; + index = i; + } + } + return d; +} + +double Vector::sum() const { + double m(0.0); + for (unsigned int i = 0; i < _n; ++i) + m += _pVector[i]; + return m; +} + +double Vector::mean() const { + double m(0.0); + for (unsigned int i = 0; i < _n; ++i) + m += _pVector[i]; + return m / _n; +} + +double Vector::stDev() const { + double m(0.0); + for (unsigned int i = 0; i < _n; ++i) + m += _pVector[i]; + double s(0.0); + for (unsigned int i = 0; i < _n; ++i) + s += (m - _pVector[i]) * (m - _pVector[i]); + return sqrt(s / (_n - 1)); +} + +double Vector::stDev(double m) const { + double s(0.0); + for (unsigned int i = 0; i < _n; ++i) + s += (m - _pVector[i]) * (m - _pVector[i]); + return sqrt(s / (_n - 1)); +} + +Vector &Vector::operator=(const Vector &src) { + if (_n != src._n) { + _n = src._n; + _pVector.resize(_n); + } + for (unsigned int i = 0; i < _n; ++i) + _pVector[i] = src._pVector[i]; + return *this; +} + +Vector &Vector::operator=(const double &v) { + for (unsigned int i = 0; i < _n; ++i) + _pVector[i] = v; + return *this; +} + +Vector &Vector::operator+=(const double &v) { + for (unsigned int i = 0; i < _n; ++i) + _pVector[i] += v; + return *this; +} + +Vector &Vector::operator+=(const Vector &V) { + for (unsigned int i = 0; i < _n; ++i) + _pVector[i] += V._pVector[i]; + return *this; +} + +Vector &Vector::operator-=(const double &v) { + for (unsigned int i = 0; i < _n; ++i) + _pVector[i] -= v; + return *this; +} + +Vector &Vector::operator-=(const Vector &V) { + for (unsigned int i = 0; i < _n; ++i) + _pVector[i] -= V._pVector[i]; + return *this; +} + +Vector &Vector::operator*=(const double &v) { + for (unsigned int i = 0; i < _n; ++i) + _pVector[i] *= v; + return *this; +} + +Vector &Vector::operator*=(const Vector &V) { + for (unsigned int i = 0; i < _n; ++i) + _pVector[i] *= V._pVector[i]; + return *this; +} + +Vector &Vector::operator/=(const double &v) { + for (unsigned int i = 0; i < _n; ++i) + _pVector[i] /= v; + return *this; +} + +Vector &Vector::operator/=(const Vector &V) { + for (unsigned int i = 0; i < _n; ++i) + _pVector[i] /= V._pVector[i]; + return *this; +} + +Vector &Vector::operator-() { + for (unsigned int i = 0; i < _n; ++i) + _pVector[i] = -_pVector[i]; + return *this; +} + +Vector Vector::operator+(const Vector &V) const { + Vector r(_n); + for (unsigned int i = 0; i < _n; ++i) + r[i] = _pVector[i] + V._pVector[i]; + return r; +} + +Vector Vector::operator-(const Vector &V) const { + Vector r(_n); + for (unsigned int i = 0; i < _n; ++i) + r[i] = _pVector[i] - V._pVector[i]; + return r; +} + +Vector Vector::operator*(const Vector &V) const { + Vector r(_n); + for (unsigned int i = 0; i < _n; ++i) + r[i] = _pVector[i] * V._pVector[i]; + return r; +} + +Vector Vector::operator/(const Vector &V) const { + Vector r(_n); + for (unsigned int i = 0; i < _n; ++i) + r[i] = _pVector[i] / V._pVector[i]; + return r; +} + +bool Vector::operator==(const Vector &V) const { + for (unsigned int i = 0; i < _n; ++i) { + if (_pVector[i] != V._pVector[i]) + return false; + } + return true; +} + +bool Vector::operator!=(const Vector &V) const { + for (unsigned int i = 0; i < _n; ++i) { + if (_pVector[i] != V._pVector[i]) + return true; + } + return false; +} + +double Vector::dotProd(const Vector &v) { + double d(0.0); + for (unsigned int i = 0; i < _n; ++i) { + d += _pVector[i] * v[i]; + } + return d; +} + +void Vector::swap(const unsigned int i, const unsigned int j) { + double dummy = _pVector[i]; + _pVector[i] = _pVector[j]; + _pVector[j] = dummy; + return; +} + +Matrix::Matrix(const unsigned int n, const unsigned int m) + : _nRows(n), _nCols(m), _pMatrix(nullptr) { + if (n && m) { + auto *dummy = new double[n * m]; // data + _pMatrix = new double *[n]; // row pointers + for (unsigned int i = 0; i < n; ++i) { + _pMatrix[i] = dummy; + dummy += m; + } + } +} + +Matrix::Matrix(const unsigned int n, const unsigned int m, const double &v) + : _nRows(n), _nCols(m), _pMatrix(nullptr) { + if (n && m) { + auto *dummy = new double[n * m]; + _pMatrix = new double *[n]; + for (unsigned int i = 0; i < n; ++i) { + _pMatrix[i] = dummy; + dummy += m; + } + for (unsigned int i = 0; i < n; ++i) + for (unsigned int j = 0; j < m; ++j) + _pMatrix[i][j] = v; + } +} + +Matrix::Matrix(const unsigned int n, const unsigned int m, const Vector &vec) + : _nRows(n), _nCols(m), _pMatrix(nullptr) { + auto *dummy(new double[n * m]); + _pMatrix = new double *[n]; + for (unsigned int i = 0; i < n; ++i) { + _pMatrix[i] = dummy; + dummy += m; + } + for (unsigned int i = 0; i < n; ++i) { + for (unsigned int j = 0; j < m; ++j) { + _pMatrix[i][j] = vec[i * m + j]; + } + } +} + +Matrix::Matrix(const Matrix &src) + : _nRows(src._nRows), _nCols(src._nCols), _pMatrix(nullptr) { + if (_nRows && _nCols) { + auto *dummy(new double[_nRows * _nCols]); + _pMatrix = new double *[_nRows]; + for (unsigned int i = 0; i < _nRows; ++i) { + _pMatrix[i] = dummy; + dummy += _nCols; + } + for (unsigned int i = 0; i < _nRows; ++i) + for (unsigned int j = 0; j < _nCols; ++j) + _pMatrix[i][j] = src[i][j]; + } +} + +Matrix::~Matrix() { + if (_pMatrix != nullptr) { + if (_pMatrix[0] != nullptr) + delete[](_pMatrix[0]); + delete[](_pMatrix); + } + _pMatrix = nullptr; +} + +double Matrix::getValueAt(const unsigned int i, const unsigned int j) { + return _pMatrix[i][j]; +} + +const double Matrix::getValueAt(const unsigned int i, + const unsigned int j) const { + return _pMatrix[i][j]; +} + +Vector Matrix::getRow(const unsigned int i) const { + Vector v(_nCols); + for (unsigned int j = 0; j < _nCols; ++j) + v[j] = _pMatrix[i][j]; + return v; +} + +Vector Matrix::getColumn(const unsigned int i) const { + Vector v(_nRows); + for (unsigned int j = 0; j < _nRows; ++j) + v[j] = _pMatrix[j][i]; + + return v; +} + +inline void Matrix::setValueAt(const unsigned int i, const unsigned int j, + double v) { + _pMatrix[i][j] = v; +} + +void Matrix::setRow(const unsigned int i, Vector &src) { + for (unsigned int j = 0; j < _nCols; ++j) + _pMatrix[i][j] = src[j]; +} + +void Matrix::setColumn(const unsigned int i, Vector &src) { + for (unsigned int j = 0; j < _nRows; ++j) + _pMatrix[j][i] = src[j]; +} + +Matrix &Matrix::operator=(const Matrix &M) { + // check dimensions + if (_nRows != M.nbrRows() || _nCols != M.nbrColumns()) { + if (_nRows && _pMatrix != nullptr) { + // delete old matrix + if (_nCols && _pMatrix[0] != nullptr) + delete[] _pMatrix[0]; + delete[] _pMatrix; + } + _pMatrix = nullptr; + // create a new matrix + _nRows = M.nbrRows(); + _nCols = M.nbrColumns(); + _pMatrix = new double *[_nRows]; + _pMatrix[0] = new double[_nRows * _nCols]; + for (unsigned int i = 1; i < _nRows; ++i) + _pMatrix[i] = _pMatrix[i - 1] + _nCols; + } + // fill in all new values + for (unsigned int i = 0; i < _nRows; ++i) + for (unsigned int j = 0; j < _nCols; ++j) + _pMatrix[i][j] = M[i][j]; + return *this; +} + +Matrix &Matrix::operator=(const double &v) { + for (unsigned int i = 0; i < _nRows; ++i) + for (unsigned int j = 0; j < _nCols; ++j) + _pMatrix[i][j] = v; + return *this; +} + +Matrix &Matrix::operator+=(const double &v) { + for (int i = 0; i < _nRows; i++) + for (int j = 0; j < _nCols; j++) + _pMatrix[i][j] += v; + return *this; +} + +Matrix &Matrix::operator+=(const Matrix &M) { + for (unsigned int i = 0; i < _nRows; ++i) + for (unsigned int j = 0; j < _nCols; ++j) + _pMatrix[i][j] += M[i][j]; + return *this; +} + +Matrix &Matrix::operator-=(const double &v) { + for (int i = 0; i < _nRows; i++) + for (int j = 0; j < _nCols; j++) + _pMatrix[i][j] -= v; + return *this; +} + +Matrix &Matrix::operator-=(const Matrix &M) { + for (unsigned int i = 0; i < _nRows; ++i) + for (unsigned int j = 0; j < _nCols; ++j) + _pMatrix[i][j] -= M[i][j]; + return *this; +} + +Matrix &Matrix::operator*=(const double &v) { + for (unsigned int i = 0; i < _nRows; ++i) + for (unsigned int j = 0; j < _nCols; ++j) + _pMatrix[i][j] *= v; + return *this; +} + +Matrix &Matrix::operator*=(const Matrix &M) { + for (unsigned int i = 0; i < _nRows; ++i) + for (unsigned int j = 0; j < _nCols; ++j) + _pMatrix[i][j] *= M[i][j]; + return *this; +} + +Matrix &Matrix::operator/=(const double &v) { + for (unsigned int i = 0; i < _nRows; ++i) + for (unsigned int j = 0; j < _nCols; ++j) + _pMatrix[i][j] /= v; + return *this; +} + +Matrix &Matrix::operator/=(const Matrix &M) { + for (unsigned int i = 0; i < _nRows; ++i) + for (unsigned int j = 0; j < _nCols; ++j) + _pMatrix[i][j] /= M[i][j]; + return *this; +} + +Matrix &Matrix::operator-() { + for (unsigned int i = 0; i < _nRows; ++i) + for (unsigned int j = 0; j < _nCols; ++j) + _pMatrix[i][j] = -_pMatrix[i][j]; + + return *this; +} + +Matrix Matrix::operator+(const Matrix &M) const { + Matrix B(M); + for (unsigned int i = 0; i < _nRows; ++i) + for (unsigned int j = 0; j < _nCols; ++j) + B[i][j] = _pMatrix[i][j] + M[i][j]; + return B; +} + +Matrix Matrix::operator-(const Matrix &M) const { + Matrix B(M); + for (unsigned int i = 0; i < _nRows; ++i) + for (unsigned int j = 0; j < _nCols; ++j) + B[i][j] = _pMatrix[i][j] - M[i][j]; + return B; +} + +Matrix Matrix::operator*(const Matrix &M) const { + Matrix B(M); + for (unsigned int i = 0; i < _nRows; ++i) + for (unsigned int j = 0; j < _nCols; ++j) + B[i][j] = _pMatrix[i][j] * M[i][j]; + return B; +} + +Matrix Matrix::operator/(const Matrix &M) const { + Matrix B(M); + for (unsigned int i = 0; i < _nRows; ++i) + for (unsigned int j = 0; j < _nCols; ++j) + B[i][j] = _pMatrix[i][j] / M[i][j]; + return B; +} + +void Matrix::swapRows(unsigned int i, unsigned int j) { + double dummy; + for (unsigned int k = 0; k < _nCols; ++k) // loop over all columns + { + dummy = _pMatrix[i][k]; // store original element at [i,k] + _pMatrix[i][k] = _pMatrix[j][k]; // replace [i,k] with [j,k] + _pMatrix[j][k] = dummy; // replace [j,k] with element originally at [i,k] + } + return; +} + +void Matrix::swapColumns(unsigned int i, unsigned int j) { + double dummy; + for (unsigned int k = 0; k < _nRows; ++k) // loop over all rows + { + dummy = _pMatrix[k][i]; // store original element at [k,i] + _pMatrix[k][i] = _pMatrix[k][j]; // replace [k,i] with [k,j] + _pMatrix[k][j] = dummy; // replace [k,j] with element orignally at [k,i] + } + return; +} + +void Matrix::reset(const unsigned int r, const unsigned int c) { + // check dimensions + if (_nRows != r || _nCols != c) { + if (_nRows != 0 && _nCols != 0 && _pMatrix != nullptr) { + // delete old matrix + if (_pMatrix[0] != nullptr) + delete[] _pMatrix[0]; + delete[] _pMatrix; + } + // create a new matrix + _nRows = r; + _nCols = c; + if (_nRows == 0 || _nCols == 0) { + _pMatrix = nullptr; + return; + } + _pMatrix = new double *[_nRows]; + _pMatrix[0] = new double[_nRows * _nCols]; + for (unsigned int i = 1; i < _nRows; ++i) + _pMatrix[i] = _pMatrix[i - 1] + _nCols; + } + // fill in all new values + for (unsigned int i = 0; i < _nRows; ++i) + for (unsigned int j = 0; j < _nCols; ++j) + _pMatrix[i][j] = 0; +} + +void Matrix::clear() { + // delete old matrix + if (_pMatrix != nullptr) { + if (_pMatrix[0] != nullptr) + delete[] _pMatrix[0]; + delete[] _pMatrix; + } + _pMatrix = nullptr; + _nRows = 0; + _nCols = 0; +} + +Matrix Matrix::transpose() { + Matrix T(_nCols, _nRows); + for (unsigned int i(0); i < _nRows; ++i) { + for (unsigned int j(0); j < _nCols; ++j) { + T[j][i] = _pMatrix[i][j]; + } + } + return T; +} + +SiMath::Vector SiMath::rowProduct(const SiMath::Matrix &A, + const SiMath::Vector &U) { + Vector v(A.nbrRows(), 0.0); + + for (unsigned int i = 0; i < A.nbrRows(); ++i) { + double s(0.0); + for (unsigned int j = 0; j < A.nbrColumns(); ++j) { + s += A[i][j] * U[j]; + } + v[i] = s; + } + return v; +} + +SiMath::Vector SiMath::colProduct(const SiMath::Vector &U, + const SiMath::Matrix &A) { + Vector v(A.nbrColumns(), 0.0); + for (unsigned int i = 0; i < A.nbrColumns(); ++i) { + double s(0.0); + for (unsigned int j = 0; j < A.nbrRows(); ++j) { + s += U[j] * A[j][i]; + } + v[i] = s; + } + return v; +} + +SVD::SVD(const Matrix &Aorig, bool bU, bool bV) + : _m(Aorig.nbrRows()), _n(Aorig.nbrColumns()), _U(), _V(), _S(0), + _computeV(bV), _computeU(bU) { + // dimensionality of the problem + int nu = min(_m, _n); + int nct = min(_m - 1, _n); + int nrt = max(0, std::min(_n - 2, _m)); + + // define the dimensions of the internal matrices and vetors + _S.reset(min(_m + 1, _n)); + + if (_computeU) + _U.reset(_m, nu); + + if (_computeV) + _V.reset(_n, _n); + + // local working vectors + Vector e(_n); + Vector work(_m); + + // make a copy of A to do the computations on + Matrix Acopy(Aorig); + + // loop indices + int i = 0, j = 0, k = 0; + + // Reduce A to bidiagonal form, storing the diagonal elements + // in _S and the super-diagonal elements in e. + + for (k = 0; k < max(nct, nrt); k++) { + if (k < nct) { + // Compute the transformation for the k-th column and place the k-th + // diagonal in _S[k]. + _S[k] = 0; + for (i = k; i < _m; i++) { + _S[k] = triangle(_S[k], Acopy[i][k]); + } + if (_S[k] != 0.0) { + if (Acopy[k][k] < 0.0) { + _S[k] = -_S[k]; + } + for (i = k; i < _m; i++) { + Acopy[i][k] /= _S[k]; + } + Acopy[k][k] += 1.0; + } + _S[k] = -_S[k]; + } + for (j = k + 1; j < _n; j++) { + if ((k < nct) && (_S[k] != 0.0)) { + // Apply the transformation to Acopy + double t = 0; + for (i = k; i < _m; i++) { + t += Acopy[i][k] * Acopy[i][j]; + } + t = -t / Acopy[k][k]; + for (i = k; i < _m; i++) { + Acopy[i][j] += t * Acopy[i][k]; + } + } + + // Place the k-th row of A into e for the subsequent calculation of the + // row transformation. + e[j] = Acopy[k][j]; + } + + // Place the transformation in _U for subsequent back multiplication. + if (_computeU & (k < nct)) { + for (i = k; i < _m; i++) { + _U[i][k] = Acopy[i][k]; + } + } + + if (k < nrt) { + // Compute the k-th row transformation and place the k-th super-diagonal + // in e[k]. Compute 2-norm without under/overflow. + e[k] = 0.0; + for (i = k + 1; i < _n; i++) { + e[k] = triangle(e[k], e[i]); + } + if (e[k] != 0.0) { + if (e[k + 1] < 0.0) { // switch sign + e[k] = -e[k]; + } + for (i = k + 1; i < _n; i++) { // scale + e[i] /= e[k]; + } + e[k + 1] += 1.0; + } + e[k] = -e[k]; + if ((k + 1 < _m) & (e[k] != 0.0)) { + // Apply the transformation. + + for (i = k + 1; i < _m; i++) { + work[i] = 0.0; + } + for (j = k + 1; j < _n; j++) { + for (i = k + 1; i < _m; i++) { + work[i] += e[j] * Acopy[i][j]; + } + } + for (j = k + 1; j < _n; j++) { + double t = -e[j] / e[k + 1]; + for (i = k + 1; i < _m; i++) { + Acopy[i][j] += t * work[i]; + } + } + } + + // Place the transformation in _V for subsequent back multiplication. + if (_computeV) { + for (i = k + 1; i < _n; i++) { + _V[i][k] = e[i]; + } + } + } + } + + // Set up the final bidiagonal matrix of order p. + int p = min(_n, _m + 1); + if (nct < _n) { + _S[nct] = Acopy[nct][nct]; + } + if (_m < p) { + _S[p - 1] = 0.0; + } + if (nrt + 1 < p) { + e[nrt] = Acopy[nrt][p - 1]; + } + e[p - 1] = 0.0; + + // If required, generate U. + if (_computeU) { + for (j = nct; j < nu; j++) { + for (i = 0; i < _m; i++) { + _U[i][j] = 0.0; + } + _U[j][j] = 1.0; + } + for (k = nct - 1; k >= 0; k--) { + if (_S[k] != 0.0) { + for (j = k + 1; j < nu; j++) { + double t = 0; + for (i = k; i < _m; i++) { + t += _U[i][k] * _U[i][j]; + } + t = -t / _U[k][k]; + for (i = k; i < _m; i++) { + _U[i][j] += t * _U[i][k]; + } + } + for (i = k; i < _m; i++) { + _U[i][k] = -_U[i][k]; + } + _U[k][k] = 1.0 + _U[k][k]; + for (i = 0; i < k - 1; i++) { + _U[i][k] = 0.0; + } + } else { + for (i = 0; i < _m; i++) { + _U[i][k] = 0.0; + } + _U[k][k] = 1.0; + } + } + } + + // If required, generate _V. + if (_computeV) { + for (k = _n - 1; k >= 0; k--) { + if ((k < nrt) & (e[k] != 0.0)) { + for (j = k + 1; j < nu; j++) { + double t = 0; + for (i = k + 1; i < _n; i++) { + t += _V[i][k] * _V[i][j]; + } + t = -t / _V[k + 1][k]; + for (i = k + 1; i < _n; i++) { + _V[i][j] += t * _V[i][k]; + } + } + } + for (i = 0; i < _n; i++) { + _V[i][k] = 0.0; + } + _V[k][k] = 1.0; + } + } + + // Main iteration loop for the singular values. + int pp = p - 1; + int iter = 0; + double eps = pow(2.0, -52.0); + while (p > 0) { + k = 0; + unsigned int mode = 0; + + // Here is where a test for too many iterations would go. + // This section of the program inspects for negligible elements in the s and + // e arrays. On completion the variables mode and k are set as follows. + + // mode = 1 if s(p) and e[k-1] are negligible and k

= -1; k--) { + if (k == -1) { + break; + } + if (fabs(e[k]) <= eps * (fabs(_S[k]) + fabs(_S[k + 1]))) { + e[k] = 0.0; + break; + } + } + if (k == p - 2) { + mode = 4; + } else { + int ks(p - 1); // start from ks == p-1 + for (; ks >= k; ks--) { + if (ks == k) { + break; + } + double t = ((ks != p) ? fabs(e[ks]) : 0.0) + + ((ks != k + 1) ? fabs(e[ks - 1]) : 0.0); + if (fabs(_S[ks]) <= eps * t) { + _S[ks] = 0.0; + break; + } + } + if (ks == k) { + mode = 3; + } else if (ks == p - 1) { + mode = 1; + } else { + mode = 2; + k = ks; + } + } + k++; + + // Perform the task indicated by the selected mode. + switch (mode) { + + case 1: { // Deflate negligible _S[p] + double f = e[p - 2]; + e[p - 2] = 0.0; + for (j = p - 2; j >= k; j--) { + double t = SiMath::triangle(_S[j], f); + double cs = _S[j] / t; + double sn = f / t; + _S[j] = t; + if (j != k) { + f = -sn * e[j - 1]; + e[j - 1] = cs * e[j - 1]; + } + + // update V + if (_computeV) { + for (i = 0; i < _n; i++) { + t = cs * _V[i][j] + sn * _V[i][p - 1]; + _V[i][p - 1] = -sn * _V[i][j] + cs * _V[i][p - 1]; + _V[i][j] = t; + } + } + } + } break; // end case 1 + + case 2: { // Split at negligible _S[k] + double f = e[k - 1]; + e[k - 1] = 0.0; + for (j = k; j < p; j++) { + double t = triangle(_S[j], f); + double cs = _S[j] / t; + double sn = f / t; + _S[j] = t; + f = -sn * e[j]; + e[j] = cs * e[j]; + + if (_computeU) { + for (i = 0; i < _m; i++) { + t = cs * _U[i][j] + sn * _U[i][k - 1]; + _U[i][k - 1] = -sn * _U[i][j] + cs * _U[i][k - 1]; + _U[i][j] = t; + } + } + } + } break; // end case 2 + + case 3: { // Perform one qr step. + + // Calculate the shift. + double scale = + max(max(max(max(fabs(_S[p - 1]), fabs(_S[p - 2])), fabs(e[p - 2])), + fabs(_S[k])), + fabs(e[k])); + double sp = _S[p - 1] / scale; + double spm1 = _S[p - 2] / scale; + double epm1 = e[p - 2] / scale; + double sk = _S[k] / scale; + double ek = e[k] / scale; + double b = ((spm1 + sp) * (spm1 - sp) + epm1 * epm1) / 2.0; + double c = (sp * epm1) * (sp * epm1); + double shift = 0.0; + if ((b != 0.0) || (c != 0.0)) { + shift = sqrt(b * b + c); + if (b < 0.0) { + shift = -shift; + } + shift = c / (b + shift); + } + double f = (sk + sp) * (sk - sp) + shift; + double g = sk * ek; + + // Chase zeros. + + for (j = k; j < p - 1; j++) { + double t = SiMath::triangle(f, g); + double cs = f / t; + double sn = g / t; + if (j != k) { + e[j - 1] = t; + } + f = cs * _S[j] + sn * e[j]; + e[j] = cs * e[j] - sn * _S[j]; + g = sn * _S[j + 1]; + _S[j + 1] = cs * _S[j + 1]; + + if (_computeV) { + for (i = 0; i < _n; i++) { + t = cs * _V[i][j] + sn * _V[i][j + 1]; + _V[i][j + 1] = -sn * _V[i][j] + cs * _V[i][j + 1]; + _V[i][j] = t; + } + } + t = SiMath::triangle(f, g); + cs = f / t; + sn = g / t; + _S[j] = t; + f = cs * e[j] + sn * _S[j + 1]; + _S[j + 1] = -sn * e[j] + cs * _S[j + 1]; + g = sn * e[j + 1]; + e[j + 1] = cs * e[j + 1]; + + if (_computeU && (j < _m - 1)) { + for (i = 0; i < _m; i++) { + t = cs * _U[i][j] + sn * _U[i][j + 1]; + _U[i][j + 1] = -sn * _U[i][j] + cs * _U[i][j + 1]; + _U[i][j] = t; + } + } + } + e[p - 2] = f; + iter++; + } break; // end case 3 + + // convergence step + case 4: { + + // Make the singular values positive. + if (_S[k] <= 0.0) { + _S[k] = (_S[k] < 0.0) ? -_S[k] : 0.0; + + if (_computeV) { + for (i = 0; i <= pp; i++) { + _V[i][k] = -_V[i][k]; + } + } + } + + // Order the singular values. + while (k < pp) { + if (_S[k] >= _S[k + 1]) + break; + + // swap values and columns if necessary + _S.swap(k, k + 1); + + if (_computeV && (k < _n - 1)) + _V.swapColumns(k, k + 1); + + if (_computeU && (k < _m - 1)) + _U.swapColumns(k, k + 1); + + k++; + } + iter = 0; + p--; + } break; // end case 4 + } + } +} + +Matrix SVD::getSingularMatrix() { + unsigned int n = _S.size(); + Matrix A(n, n, 0.0); + // set diagonal elements + for (int i = 0; i < n; i++) { + A[i][i] = _S[i]; + } + + return A; +} + +int SVD::rank() { + double eps = pow(2.0, -52.0); + double tol = max(_m, _n) * _S[0] * eps; + int r = 0; + for (int i = 0; i < _S.size(); i++) { + if (_S[i] > tol) { + r++; + } + } + return r; +} + +double SiMath::randD(double a, double b) { + double d(a); + d += (b - a) * ((double)rand() / RAND_MAX); + return d; +} +","C++" +"In Silico","rdkit/shape-it","src/parseCommandLine.cpp",".cpp","5585","162","/******************************************************************************* +parseCommandLine.cpp - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#include + +Options parseCommandLine(int argc, char *argv[]) { + static struct option Arguments[] = { + {""version"", no_argument, nullptr, 'v'}, + {""reference"", required_argument, nullptr, 'r'}, + {""dbase"", required_argument, nullptr, 'd'}, + {""scores"", required_argument, nullptr, 's'}, + {""out"", required_argument, nullptr, 'o'}, + {""format"", required_argument, nullptr, 'f'}, + {""scoreOnly"", no_argument, nullptr, 1}, + {""rankBy"", required_argument, nullptr, 2}, + {""best"", required_argument, nullptr, 4}, + {""addIterations"", required_argument, nullptr, 5}, + {""cutoff"", required_argument, nullptr, 6}, + {""noRef"", no_argument, nullptr, 11}, + {""help"", no_argument, nullptr, 'h'}}; + + Options o; + + int choice; + opterr = 0; + int optionIndex = 0; + std::string s; + + while ((choice = getopt_long(argc, argv, ""vhpr:d:s:o:f:"", Arguments, + &optionIndex)) != -1) { + switch (choice) { + case 'v': //....................................................version + o.version = true; + break; + + case 'r': //..................................................reference + o.refInpFile = optarg; + o.refInpStream = new std::ifstream(optarg); + if (!o.refInpStream->good()) { + mainErr(""Error opening input file for reference (-r)""); + } + break; + + case 'd': //......................................................dbase + o.dbInpFile = optarg; + o.dbInpStream = new std::ifstream(optarg); + if (!o.dbInpStream->good()) { + mainErr(""Error opening input file for database (-d)""); + } + break; + + case 's': //.....................................................scores + o.scoreOutFile = optarg; + o.scoreOutStream = new std::ofstream(optarg); + if (!o.scoreOutStream->good()) { + mainErr(""Error opening output file for scores (-s)""); + } + break; + + case 'o': //........................................................out + o.molOutFile = optarg; + o.molOutStream = new std::ofstream(optarg); + if (!o.molOutStream->good()) { + mainErr(""Error opening output file for molecules (-o)""); + } + break; + + case 'f': //.....................................................format + o.format = optarg; +#ifdef USE_RDKIT + if (!o.format.empty() && o.format != ""SDF"") { + mainErr(""RDKit implementation currently only supports SDF (-f)""); + } +#endif + break; + + case 1: //....................................................scoreOnly + o.scoreOnly = true; + break; + + case 2: //.......................................................rankBy + s = optarg; + transform(s.begin(), s.end(), s.begin(), toupper); + if (s == ""TANIMOTO"") { + o.whichScore = tanimoto; + } else if (s == ""TVERSKY_DB"") { + o.whichScore = tversky_db; + } else if (s == ""TVERSKY_REF"") { + o.whichScore = tversky_ref; + } + break; + + case 4: //.........................................................best + o.bestHits = strtol(optarg, nullptr, 10); + break; + + case 5: //................................................addIterations + o.maxIter = strtol(optarg, nullptr, 10); + break; + + case 6: //.......................................................cutoff + o.cutOff = strtod(optarg, nullptr); + if (o.cutOff > 1) { + o.cutOff = 1.0; + } else if (o.cutOff < 0) { + o.cutOff = 0.0; + } + break; + + case 11: //.......................................................noRef + o.showRef = false; + break; + + case 'h': //.......................................................help + o.help = true; + break; + + default: + mainErr(""Unknown command line option""); + } + } + + // If no options are given print the help + if (optind == 1) { + o.help = true; + } + + argc -= optind; + argv += optind; + return o; +} +","C++" +"In Silico","rdkit/shape-it","src/bestResults.cpp",".cpp","3248","115","/******************************************************************************* +bestResults.cpp - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#include + +BestResults::BestResults(unsigned int n) { + _bestList.clear(); + _size = n; + _lowest = 0.0; + _filled = 0; +} + +BestResults::~BestResults() { + std::vector::iterator it; + for (it = _bestList.begin(); it != _bestList.end(); ++it) { + if (*it != NULL) { + delete *it; + *it = NULL; + } + } +} + +bool BestResults::add(SolutionInfo &res) { + std::vector::reverse_iterator it; + if (_filled < _size) { + auto *i = new SolutionInfo(res); + _bestList.push_back(i); + ++_filled; + } else if (res.score < _lowest) { + return false; + } else { + // delete last element + it = _bestList.rbegin(); + if (*it != NULL) { + delete *it; + *it = NULL; + } + + // make new info element in the list + *it = new SolutionInfo(res); + } + + std::sort(_bestList.begin(), _bestList.end(), BestResults::_compInfo()); + it = _bestList.rbegin(); + _lowest = (*it)->score; + + return true; +} + +#if 0 +void +BestResults::writeMolecules(Options* uo) +{ + if (uo->molOutWriter == NULL) + { + return; + } + + std::vector::iterator it; + for (it = _bestList.begin(); it != _bestList.end(); ++it) + { + if (*it != NULL) + { + uo->molOutWriter->Write(&((*it)->dbMol), uo->molOutStream); + } + } + return; +} +#endif + +void BestResults::writeScores(Options *uo) { + if (uo->scoreOutStream == nullptr) { + return; + } + + std::vector score(3); + std::vector::iterator it; + for (it = _bestList.begin(); it != _bestList.end(); ++it) { + if (*it != NULL) { + (*it)->printScores(*uo); + } + } + return; +} +","C++" +"In Silico","rdkit/shape-it","src/moleculeRotation.cpp",".cpp","7206","175","/******************************************************************************* +moleculeRotation.cpp - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#include + +#ifndef USE_RDKIT +// OpenBabel +#include +#include + +void positionMolecule(OpenBabel::OBMol &m, const Coordinate ¢roid, + const SiMath::Matrix &rotation) { + std::vector::iterator i; + for (OpenBabel::OBAtom *a = m.BeginAtom(i); a; a = m.NextAtom(i)) { + // Translate point + double x = a->GetX() - centroid.x; + double y = a->GetY() - centroid.y; + double z = a->GetZ() - centroid.z; + + // Rotate according to eigenvectors SVD + a->SetVector(rotation[0][0] * x + rotation[1][0] * y + rotation[2][0] * z, + rotation[0][1] * x + rotation[1][1] * y + rotation[2][1] * z, + rotation[0][2] * x + rotation[1][2] * y + rotation[2][2] * z); + } + return; +} + +void repositionMolecule(OpenBabel::OBMol &m, const SiMath::Matrix &rotation, + const Coordinate ¢roid) { + std::vector::iterator i; + for (OpenBabel::OBAtom *a = m.BeginAtom(i); a; a = m.NextAtom(i)) { + // Get coordinates + double x = a->GetX(); + double y = a->GetY(); + double z = a->GetZ(); + + // Rotate according to eigenvectors SVD + double xx = rotation[0][0] * x + rotation[0][1] * y + rotation[0][2] * z; + double yy = rotation[1][0] * x + rotation[1][1] * y + rotation[1][2] * z; + double zz = rotation[2][0] * x + rotation[2][1] * y + rotation[2][2] * z; + + a->SetVector(xx + centroid.x, yy + centroid.y, zz + centroid.z); + } + return; +} + +void rotateMolecule(OpenBabel::OBMol &m, const SiMath::Vector &rotor) { + // Build rotation matrix + SiMath::Matrix rot(3, 3, 0.0); + double r1 = rotor[1] * rotor[1]; + double r2 = rotor[2] * rotor[2]; + double r3 = rotor[3] * rotor[3]; + + rot[0][0] = 1.0 - 2.0 * r2 - 2.0 * r3; + rot[0][1] = 2.0 * (rotor[1] * rotor[2] - rotor[0] * rotor[3]); + rot[0][2] = 2.0 * (rotor[1] * rotor[3] + rotor[0] * rotor[2]); + rot[1][0] = 2.0 * (rotor[1] * rotor[2] + rotor[0] * rotor[3]); + rot[1][1] = 1.0 - 2 * r3 - 2 * r1; + rot[1][2] = 2.0 * (rotor[2] * rotor[3] - rotor[0] * rotor[1]); + rot[2][0] = 2.0 * (rotor[1] * rotor[3] - rotor[0] * rotor[2]); + rot[2][1] = 2.0 * (rotor[2] * rotor[3] + rotor[0] * rotor[1]); + rot[2][2] = 1.0 - 2 * r2 - 2 * r1; + + std::vector::iterator i; + for (OpenBabel::OBAtom *a = m.BeginAtom(i); a; a = m.NextAtom(i)) { + // Translate point + double x = a->GetX(); + double y = a->GetY(); + double z = a->GetZ(); + + // rotate according to eigenvectors SVD + a->SetVector(rot[0][0] * x + rot[0][1] * y + rot[0][2] * z, + rot[1][0] * x + rot[1][1] * y + rot[1][2] * z, + rot[2][0] * x + rot[2][1] * y + rot[2][2] * z); + } + return; +} +#else +#include +#include +#include + +void positionMolecule(RDKit::ROMol &m, const Coordinate ¢roid, + const SiMath::Matrix &rotation) { + RDKit::Conformer &conf = m.getConformer(); + RDGeom::Point3D rdcentroid(centroid.x, centroid.y, centroid.z); + for (unsigned int i = 0; i < m.getNumAtoms(); ++i) { + RDGeom::Point3D tp = conf.getAtomPos(i) - rdcentroid; + conf.setAtomPos( + i, RDGeom::Point3D(rotation[0][0] * tp.x + rotation[1][0] * tp.y + + rotation[2][0] * tp.z, + rotation[0][1] * tp.x + rotation[1][1] * tp.y + + rotation[2][1] * tp.z, + rotation[0][2] * tp.x + rotation[1][2] * tp.y + + rotation[2][2] * tp.z)); + } +} + +void repositionMolecule(RDKit::ROMol &m, const SiMath::Matrix &rotation, + const Coordinate ¢roid) { + RDKit::Conformer &conf = m.getConformer(); + RDGeom::Point3D rdcentroid(centroid.x, centroid.y, centroid.z); + for (unsigned int i = 0; i < m.getNumAtoms(); ++i) { + RDGeom::Point3D tp = conf.getAtomPos(i); + conf.setAtomPos( + i, RDGeom::Point3D(rotation[0][0] * tp.x + rotation[0][1] * tp.y + + rotation[0][2] * tp.z, + rotation[1][0] * tp.x + rotation[1][1] * tp.y + + rotation[1][2] * tp.z, + rotation[2][0] * tp.x + rotation[2][1] * tp.y + + rotation[2][2] * tp.z)); + conf.getAtomPos(i) += rdcentroid; + } + return; +} + +void rotateMolecule(RDKit::ROMol &m, const SiMath::Vector &rotor) { + RDKit::Conformer &conf = m.getConformer(); + // Build rotation matrix + SiMath::Matrix rot(3, 3, 0.0); + double r1 = rotor[1] * rotor[1]; + double r2 = rotor[2] * rotor[2]; + double r3 = rotor[3] * rotor[3]; + + rot[0][0] = 1.0 - 2.0 * r2 - 2.0 * r3; + rot[0][1] = 2.0 * (rotor[1] * rotor[2] - rotor[0] * rotor[3]); + rot[0][2] = 2.0 * (rotor[1] * rotor[3] + rotor[0] * rotor[2]); + rot[1][0] = 2.0 * (rotor[1] * rotor[2] + rotor[0] * rotor[3]); + rot[1][1] = 1.0 - 2 * r3 - 2 * r1; + rot[1][2] = 2.0 * (rotor[2] * rotor[3] - rotor[0] * rotor[1]); + rot[2][0] = 2.0 * (rotor[1] * rotor[3] - rotor[0] * rotor[2]); + rot[2][1] = 2.0 * (rotor[2] * rotor[3] + rotor[0] * rotor[1]); + rot[2][2] = 1.0 - 2 * r2 - 2 * r1; + + for (unsigned int i = 0; i < m.getNumAtoms(); ++i) { + RDGeom::Point3D tp = conf.getAtomPos(i); + conf.setAtomPos( + i, RDGeom::Point3D( + rot[0][0] * tp.x + rot[0][1] * tp.y + rot[0][2] * tp.z, + rot[1][0] * tp.x + rot[1][1] * tp.y + rot[1][2] * tp.z, + rot[2][0] * tp.x + rot[2][1] * tp.y + rot[2][2] * tp.z)); + } +} + +#endif","C++" +"In Silico","rdkit/shape-it","src/catch_main.cpp",".cpp","1547","31","// +// Copyright (C) 2021 Greg Landrum and the Shape-it contributors +// +/* +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. +*/ +#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do + // this in one cpp file +#include ""catch2/catch_all.hpp"" +","C++" +"In Silico","rdkit/shape-it","src/main.cpp",".cpp","10944","370","/******************************************************************************* +main.cpp - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +// General +#include +#include +#include +#include +#include + +#ifndef USE_RDKIT +// OpenBabel +#include +#include +#else +#include +#include +#include +#endif + +// Pharao +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +//*--------------------------------------------------------------------------*// +//* MAIN MAIN +//*// +//*--------------------------------------------------------------------------*// +int main(int argc, char *argv[]) { + // Initialise random number generator + srandom(time(nullptr)); + clock_t t0 = clock(); + + // Print header + printHeader(); + + // Read options + Options uo = parseCommandLine(argc, argv); + if (uo.version) { + printHeader(); + exit(0); + } + + if (uo.help) { + printUsage(); + exit(0); + } + std::cerr << uo.print(); + + // Files + if (uo.dbInpFile.empty()) { + mainErr(""Missing database file. This is a required option (-d).""); + } + if (uo.refInpFile.empty()) { + mainErr(""Missing ref file. This is a required option (-r).""); + } + + if (uo.molOutFile.empty() && uo.scoreOutFile.empty()) { + mainErr(""At least one of the -o or -s option should be used.""); + } + + // Create a list to store the best results + BestResults *bestHits = nullptr; + if (uo.bestHits != 0) { + bestHits = new BestResults(uo.bestHits); + } + + // Print header line to score output file + if (!uo.scoreOutFile.empty()) { + *(uo.scoreOutStream) << ""dbName"" + << ""\t"" + << ""refName"" + << ""\t"" << tanimoto << ""\t"" << tversky_ref << ""\t"" + << tversky_db << ""\t"" + << ""overlap"" + << ""\t"" + << ""refVolume"" + << ""\t"" + << ""dbVolume"" << std::endl; + } + + // Create reference molecule + std::string refName; +#ifndef USE_RDKIT + OpenBabel::OBMol refMol; + OpenBabel::OBConversion refInpReader; + if (uo.format.empty()) { + refInpReader.SetInFormat(refInpReader.FormatFromExt(uo.refInpFile)); + } else { + refInpReader.SetInFormat(refInpReader.FindFormat(uo.format)); + } + refInpReader.Read(&refMol, uo.refInpStream); + refName = refMol.GetTitle(); +#else + bool takeOwnership = false; + bool sanitize = true; + + bool removeHs = false; + RDKit::ForwardSDMolSupplier refsuppl(uo.refInpStream, takeOwnership, sanitize, + removeHs); + std::unique_ptr refmptr(refsuppl.next()); + if (!refmptr) { + mainErr(""Could not parse reference molecule""); + } + RDKit::ROMol &refMol = *refmptr; + refMol.getPropIfPresent(""_Name"", refName); +#endif + if (refName == """") { + refName = ""Unnamed_ref""; + } + + // Create the refence set of Gaussians + GaussianVolume refVolume; + + // List all Gaussians and their respective intersections + listAtomVolumes(refMol, refVolume); + + // Move the Gaussian towards its center of geometry and align with principal + // axes + if (!uo.scoreOnly) { + initOrientation(refVolume); + } + + // Write reference molecule to output +#ifndef USE_RDKIT + std::unique_ptr dbOutWriter( + new OpenBabel::OBConversion()); + if (uo.format.empty()) { + dbOutWriter->SetOutFormat(dbOutWriter->FormatFromExt(uo.molOutFile)); + } else { + dbOutWriter->SetOutFormat(dbOutWriter->FindFormat(uo.format)); + } + if (uo.showRef && !uo.molOutFile.empty()) { + dbOutWriter->Write(&refMol, uo.molOutStream); + } +#else + std::unique_ptr dbOutWriter; + if (uo.molOutStream != nullptr) { + dbOutWriter.reset(new RDKit::SDWriter(uo.molOutStream, false)); + dbOutWriter->write(refMol); + } +#endif + + // Open database stream + unsigned molCount(0); + std::ostringstream ss; +#ifndef USE_RDKIT + OpenBabel::OBMol dbMol; + OpenBabel::OBConversion dbInpReader; + if (uo.format.empty()) { + dbInpReader.SetInFormat(dbInpReader.FormatFromExt(uo.dbInpFile)); + } else { + dbInpReader.SetInFormat(dbInpReader.FindFormat(uo.format)); + } + dbInpReader.SetInStream(uo.dbInpStream); + + while (dbInpReader.Read(&dbMol)) { +#else + RDKit::ForwardSDMolSupplier dbsuppl(uo.dbInpStream, takeOwnership, sanitize, + removeHs); + while (!dbsuppl.atEnd()) { + std::unique_ptr dbmptr(dbsuppl.next()); + if (!dbmptr) { + continue; + } + RDKit::ROMol &dbMol = *dbmptr; +#endif + ++molCount; + + // Keep track of the number of molecules processed so far + if ((molCount % 10) == 0) { + std::cerr << "".""; + if ((molCount % 500) == 0) { + std::cerr << "" "" << molCount << "" molecules"" << std::endl; + } + } + + std::string dbName; +#ifndef USE_RDKIT + dbName = dbMol.GetTitle(); +#else + dbMol.getPropIfPresent(""_Name"", dbName); +#endif + if (dbName == """") { + ss.str(""""); + ss << ""MOL_"" << molCount; + dbName = ss.str(); +#ifndef USE_RDKIT + dbMol.SetTitle(dbName); +#else + dbMol.setProp(""_Name"", dbName); +#endif + } + + // Create the set of Gaussians of database molecule + GaussianVolume dbVolume; + listAtomVolumes(dbMol, dbVolume); + + // Overlap with reference + AlignmentInfo res; + double bestScore(0.0); + + SolutionInfo bestSolution; + if (uo.scoreOnly) { + res.overlap = atomOverlap(refVolume, dbVolume); + res.rotor[0] = 1.0; + bestScore = getScore(uo.whichScore, res.overlap, refVolume.overlap, + dbVolume.overlap); + bestSolution.refAtomVolume = refVolume.overlap; + updateSolutionInfo(bestSolution, res, bestScore, dbVolume); + } else { + initOrientation(dbVolume); + + bestSolution = std::move(shapeit::alignVolumes( + refVolume, dbVolume, uo.whichScore, uo.maxIter)); + } + +#ifndef USE_RDKIT + bestSolution.dbMol = dbMol; +#else + bestSolution.dbMol = dbMol; +#endif + bestSolution.refName = refName; + bestSolution.dbName = dbName; + + // Cleanup local pointers to atom-gaussians + dbVolume.gaussians.clear(); + dbVolume.levels.clear(); + for (auto &childOverlap : dbVolume.childOverlaps) { + delete childOverlap; + childOverlap = nullptr; + } + dbVolume.childOverlaps.clear(); + + // At this point the information of the solution is stored in bestSolution + // Check if the result is better than the cutoff + if (bestSolution.score < uo.cutOff) { + continue; + } + + // Post-process molecules + if (uo.bestHits || !uo.molOutFile.empty()) { + // Add the score properties + setAllScores(bestSolution); + + if (!uo.scoreOnly) { + // Translate and rotate the molecule towards its centroid and inertia + // axes + positionMolecule(bestSolution.dbMol, bestSolution.dbCenter, + bestSolution.dbRotation); + + // Rotate molecule with the optimal + rotateMolecule(bestSolution.dbMol, bestSolution.rotor); + + // Rotate and translate the molecule with the inverse rotation and + // translation of the reference molecule + repositionMolecule(bestSolution.dbMol, refVolume.rotation, + refVolume.centroid); + } + + if (uo.bestHits) { + bestHits->add(bestSolution); + } else if (!uo.molOutFile.empty() && dbOutWriter != nullptr) { +#ifndef USE_RDKIT + dbOutWriter->Write(&(bestSolution.dbMol), uo.molOutStream); +#else + dbOutWriter->write(bestSolution.dbMol); +#endif + } + } + + if ((uo.bestHits == 0) && !uo.scoreOutFile.empty()) { + bestSolution.printScores(uo); + } + +#ifndef USE_RDKIT + // Clear current molecule + dbMol.Clear(); +#endif + } + + if (uo.bestHits) { + if (!uo.molOutFile.empty()) { + for (const auto molptr : bestHits->getBestList()) { + if (molptr != nullptr && dbOutWriter != nullptr) { +#ifndef USE_RDKIT + dbOutWriter->Write(&(molptr->dbMol), uo.molOutStream); +#else + dbOutWriter->write(molptr->dbMol); +#endif + } + } + delete uo.molOutStream; + uo.molOutStream = nullptr; + } + if (!uo.scoreOutFile.empty()) { + bestHits->writeScores(&uo); + delete uo.scoreOutStream; + uo.scoreOutStream = nullptr; + } + } + + // Clear current streams + if (uo.dbInpStream != nullptr) { + delete uo.dbInpStream; + uo.dbInpStream = nullptr; + } + if (uo.refInpStream != nullptr) { + delete uo.refInpStream; + uo.refInpStream = nullptr; + } + + // Done processing database + std::cerr << std::endl; + std::cerr << ""Processed "" << molCount << "" molecules"" << std::endl; + double tt = (double)(clock() - t0) / CLOCKS_PER_SEC; + std::cerr << molCount << "" molecules in "" << tt << "" seconds (""; + std::cerr << molCount / tt << "" molecules per second)"" << std::endl; + + // Cleanup local db volume + refVolume.gaussians.clear(); + for (auto &childOverlap : refVolume.childOverlaps) { + delete childOverlap; + childOverlap = nullptr; + } + + exit(0); +} +","C++" +"In Silico","rdkit/shape-it","src/basic_tests.cpp",".cpp","5691","157","// +// Copyright (C) 2021 Greg Landrum and the Shape-it contributors +/* +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. +*/ + +#include ""catch2/catch_all.hpp"" + +#include +#include +#include + +using namespace RDKit; + +TEST_CASE(""align mols"", ""[library][molecules]"") { + std::string ref = R""CTAB(3l5u_lig_ZEC + 3D + Structure written by MMmdl. + 20 21 0 0 1 0 999 V2000 + 15.0500 -34.9220 -18.1430 O 0 0 0 0 0 0 + 14.9110 -34.7040 -19.4790 C 0 0 0 0 0 0 + 14.7350 -35.7750 -20.3500 C 0 0 0 0 0 0 + 14.6060 -35.5430 -21.7160 C 0 0 0 0 0 0 + 14.3620 -36.6080 -23.0370 S 0 0 0 0 0 0 + 14.3210 -35.3400 -24.1850 C 0 0 0 0 0 0 + 14.0030 -35.5290 -25.8940 S 0 0 0 0 0 0 + 15.1750 -34.7990 -26.7570 N 0 0 0 0 0 0 + 12.6760 -34.9070 -26.2170 O 0 0 0 0 0 0 + 13.9630 -36.9930 -26.2180 O 0 0 0 0 0 0 + 14.4970 -34.1790 -23.5590 N 0 0 0 0 0 0 + 14.6510 -34.2470 -22.2350 C 0 0 0 0 0 0 + 14.8270 -33.1870 -21.3480 C 0 0 0 0 0 0 + 14.9560 -33.4070 -19.9800 C 0 0 0 0 0 0 + 15.1610 -34.0820 -17.6920 H 0 0 0 0 0 0 + 14.6990 -36.7830 -19.9650 H 0 0 0 0 0 0 + 15.1440 -34.8130 -27.7660 H 0 0 0 0 0 0 + 15.9340 -34.3310 -26.2820 H 0 0 0 0 0 0 + 14.8640 -32.1730 -21.7190 H 0 0 0 0 0 0 + 15.0910 -32.5720 -19.3090 H 0 0 0 0 0 0 + 1 2 1 0 0 0 + 1 15 1 0 0 0 + 2 3 2 0 0 0 + 2 14 1 0 0 0 + 3 4 1 0 0 0 + 3 16 1 0 0 0 + 4 5 1 0 0 0 + 4 12 2 0 0 0 + 5 6 1 0 0 0 + 6 7 1 0 0 0 + 6 11 2 0 0 0 + 7 8 1 0 0 0 + 7 9 2 0 0 0 + 7 10 2 0 0 0 + 8 17 1 0 0 0 + 8 18 1 0 0 0 + 11 12 1 0 0 0 + 12 13 1 0 0 0 + 13 14 2 0 0 0 + 13 19 1 0 0 0 + 14 20 1 0 0 0 +M END)CTAB""; + std::string probe = R""CTAB(3hof_lig_DHC + 3D + Structure written by MMmdl. + 20 20 0 0 1 0 999 V2000 + 14.6290 -34.5170 -18.4190 C 0 0 0 0 0 0 + 15.6070 -34.6620 -17.5400 O 0 0 0 0 0 0 + 14.9220 -34.5200 -19.8370 C 0 0 0 0 0 0 + 14.7370 -35.7220 -20.3520 C 0 0 0 0 0 0 + 14.9680 -35.9740 -21.7740 C 0 0 0 0 0 0 + 14.8780 -34.9380 -22.6930 C 0 0 0 0 0 0 + 15.1020 -35.2380 -24.0360 C 0 0 0 0 0 0 + 15.4390 -36.6310 -24.4550 C 0 0 0 0 0 0 + 15.5160 -37.6070 -23.4830 C 0 0 0 0 0 0 + 15.2760 -37.2740 -22.1560 C 0 0 0 0 0 0 + 15.6830 -36.9520 -25.7670 O 0 0 0 0 0 0 + 15.0160 -34.2570 -24.9550 O 0 0 0 0 0 0 + 13.4860 -34.4200 -18.0300 O 0 5 0 0 0 0 + 15.2430 -33.6100 -20.3240 H 0 0 0 0 0 0 + 14.4110 -36.5360 -19.7210 H 0 0 0 0 0 0 + 14.6410 -33.9380 -22.3590 H 0 0 0 0 0 0 + 15.7620 -38.6220 -23.7550 H 0 0 0 0 0 0 + 15.3330 -38.0570 -21.4140 H 0 0 0 0 0 0 + 15.1950 -34.6170 -25.8260 H 0 0 0 0 0 0 + 15.8806 -37.8889 -25.8363 H 0 0 0 0 0 0 + 1 2 2 0 0 0 + 1 3 1 0 0 0 + 1 13 1 0 0 0 + 3 4 2 0 0 0 + 3 14 1 0 0 0 + 4 5 1 0 0 0 + 4 15 1 0 0 0 + 5 6 2 0 0 0 + 5 10 1 0 0 0 + 6 7 1 0 0 0 + 6 16 1 0 0 0 + 7 8 2 0 0 0 + 7 12 1 0 0 0 + 8 9 1 0 0 0 + 8 11 1 0 0 0 + 9 10 2 0 0 0 + 9 17 1 0 0 0 + 10 18 1 0 0 0 + 11 20 1 0 0 0 + 12 19 1 0 0 0 +M CHG 1 13 -1 +M END)CTAB""; + + bool sanitize = true; + bool removeHs = false; + std::unique_ptr refMol{MolBlockToMol(ref, sanitize, removeHs)}; + REQUIRE(refMol); + std::unique_ptr prbMol{MolBlockToMol(probe, sanitize, removeHs)}; + SECTION(""basics"") { + auto solution = shapeit::alignMols(*refMol, *prbMol); + CHECK(solution.score == Catch::Approx(0.647).margin(0.01)); + } + SECTION(""self"") { + ROMol m2(*refMol); + auto solution = shapeit::alignMols(*refMol, m2); + CHECK(solution.score == Catch::Approx(1.00).margin(0.01)); + } + SECTION(""align to volume"") { + GaussianVolume refVolume; + listAtomVolumes(*refMol, refVolume); + initOrientation(refVolume); + auto solution = shapeit::alignMolToVolume(refVolume, *prbMol); + + refVolume.gaussians.clear(); + for (auto &childOverlap : refVolume.childOverlaps) { + delete childOverlap; + childOverlap = nullptr; + } + refVolume.childOverlaps.clear(); + } +}","C++" +"In Silico","rdkit/shape-it","src/alignLib.cpp",".cpp","6035","181","/******************************************************************************* +alignLib.cpp - Shape-it + +Copyright 2021 by Greg Landrum and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ +#include + +#include +#include +#include +#include +#include + +namespace shapeit { + +SolutionInfo +alignMols(const Molecule &refMol, const Molecule &dbMol, + const std::string &whichScore, double maxIter, double cutoff, + BestResults *bestHits) { // Create the refence set of Gaussians + GaussianVolume refVolume; + + // List all Gaussians and their respective intersections + listAtomVolumes(refMol, refVolume); + + // Move the Gaussian towards its center of geometry and align with principal + // axes + initOrientation(refVolume); + auto res = + alignMolToVolume(refVolume, dbMol, whichScore, maxIter, cutoff, bestHits); + +#ifndef USE_RDKIT + res.refName = refMol.GetTitle(); +#else + refMol.getProp(""_Name"", res.refName); +#endif + + // Cleanup local pointers to atom-gaussians + refVolume.gaussians.clear(); + refVolume.levels.clear(); + for (const auto ci : refVolume.childOverlaps) { + delete ci; + } + refVolume.childOverlaps.clear(); + + return res; +} + +SolutionInfo alignMolToVolume(const GaussianVolume &refVolume, + const Molecule &dbMol, + const std::string &whichScore, double maxIter, + double cutoff, BestResults *bestHits) { + // Create the set of Gaussians of database molecule + GaussianVolume dbVolume; + listAtomVolumes(dbMol, dbVolume); + initOrientation(dbVolume); + + // Overlap with reference + AlignmentInfo res; + double bestScore(0.0); + + SolutionInfo bestSolution = + std::move(alignVolumes(refVolume, dbVolume, whichScore, maxIter)); + bestSolution.refName = """"; +#ifndef USE_RDKIT + bestSolution.dbMol = dbMol; + bestSolution.dbName = dbMol.GetTitle(); +#else + bestSolution.dbMol = dbMol; + dbMol.getProp(""_Name"", bestSolution.dbName); +#endif + + // Cleanup local pointers to atom-gaussians + dbVolume.gaussians.clear(); + dbVolume.levels.clear(); + for (auto &childOverlap : dbVolume.childOverlaps) { + delete childOverlap; + childOverlap = nullptr; + } + dbVolume.childOverlaps.clear(); + + if (bestSolution.score < cutoff) { + return bestSolution; + } + + // Add the score properties + setAllScores(bestSolution); + + // Translate and rotate the molecule towards its centroid and inertia + // axes + positionMolecule(bestSolution.dbMol, bestSolution.dbCenter, + bestSolution.dbRotation); + + // Rotate molecule with the optimal + rotateMolecule(bestSolution.dbMol, bestSolution.rotor); + + // Rotate and translate the molecule with the inverse rotation and + // translation of the reference molecule + repositionMolecule(bestSolution.dbMol, refVolume.rotation, + refVolume.centroid); + + if (bestHits) { + bestHits->add(bestSolution); + } + return bestSolution; +} + +SolutionInfo alignVolumes(const GaussianVolume &refVolume, + const GaussianVolume &dbVolume, + const std::string &whichScore, double maxIter) { + SolutionInfo res; + res.refAtomVolume = refVolume.overlap; + res.refCenter = refVolume.centroid; + res.refRotation = refVolume.rotation; + + ShapeAlignment aligner(refVolume, dbVolume); + aligner.setMaxIterations(maxIter); + + AlignmentInfo alignment; + double bestScore = 0; + for (unsigned int l = 0; l < 4; ++l) { + SiMath::Vector quat(4, 0.0); + quat[l] = 1.0; + AlignmentInfo nextAlignment = aligner.gradientAscent(quat); + checkVolumes(refVolume, dbVolume, nextAlignment); + double ss = getScore(whichScore, nextAlignment.overlap, refVolume.overlap, + dbVolume.overlap); + if (ss > bestScore) { + alignment = nextAlignment; + bestScore = ss; + } + + if (bestScore > 0.98) { + break; + } + } + + // Check if additional simulated annealing steps are requested and start + // from the current best solution + if (maxIter > 0) { + AlignmentInfo nextRes = aligner.simulatedAnnealing(alignment.rotor); + checkVolumes(refVolume, dbVolume, nextRes); + double ss = getScore(whichScore, nextRes.overlap, refVolume.overlap, + dbVolume.overlap); + if (ss > bestScore) { + bestScore = ss; + alignment = nextRes; + } + } + // Optimal alignment information is stored in res and bestScore + // => result reporting and post-processing + updateSolutionInfo(res, alignment, bestScore, dbVolume); + + return std::move(res); +} +} // namespace shapeit","C++" +"In Silico","rdkit/shape-it","src/atomGaussian.cpp",".cpp","2606","68","/******************************************************************************* +atomGaussian.cpp - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#include + +AtomGaussian::AtomGaussian() + : center(0.0, 0.0, 0.0), alpha(0.0), volume(0.0), C(0.0), nbr(0) {} + +AtomGaussian::~AtomGaussian() = default; + +AtomGaussian atomIntersection(AtomGaussian &a, AtomGaussian &b) { + AtomGaussian c; + + // new alpha + c.alpha = a.alpha + b.alpha; + + // new center + c.center.x = (a.alpha * a.center.x + b.alpha * b.center.x) / c.alpha; + c.center.y = (a.alpha * a.center.y + b.alpha * b.center.y) / c.alpha; + c.center.z = (a.alpha * a.center.z + b.alpha * b.center.z) / c.alpha; + + // self-volume + double d = (a.center.x - b.center.x) * (a.center.x - b.center.x) + + (a.center.y - b.center.y) * (a.center.y - b.center.y) + + (a.center.z - b.center.z) * (a.center.z - b.center.z); + + c.C = a.C * b.C * exp(-a.alpha * b.alpha / c.alpha * d); + + double scale = PI / (c.alpha); + + c.volume = c.C * scale * sqrt(scale); + + // set the number of gaussians + c.nbr = a.nbr + b.nbr; + + return c; +} +","C++" +"In Silico","rdkit/shape-it","src/shapeAlignment.cpp",".cpp","20140","633","/******************************************************************************* +shapeAlignment.cpp - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#include + +ShapeAlignment::ShapeAlignment(const GaussianVolume &gRef, + const GaussianVolume &gDb) + : _gRef(&gRef), _gDb(&gDb), _rAtoms(0), _rGauss(0), _dAtoms(0), _dGauss(0), + _maxSize(0), _maxIter(50), _matrixMap() { + // Loop over the single atom volumes of both molecules and make the + // combinations + _rAtoms = gRef.levels[0]; + _dAtoms = gDb.levels[0]; + _rGauss = gRef.gaussians.size(); + _dGauss = gDb.gaussians.size(); + _maxSize = _rGauss * _dGauss + 1; +} + +ShapeAlignment::~ShapeAlignment() { + _gRef = nullptr; + _gDb = nullptr; + + // Clear the matrix map + for (auto &mi : _matrixMap) { + delete[] mi.second; + mi.second = nullptr; + } +} + +AlignmentInfo ShapeAlignment::gradientAscent(SiMath::Vector rotor) { + // Create a queue to hold the pairs to process + std::queue> processQueue; + + // Helper variables + // Overlap matrix is stored as a double error + double *Aij; + double Aq[4]; + + double Vij(0.0); + double qAq(0.0); + + std::vector *d1(nullptr); + std::vector *d2(nullptr); + std::vector::iterator it1; + + // Gradient information + SiMath::Vector overGrad(4, 0.0); + + // Hessian + SiMath::Matrix overHessian(4, 4, 0.0); + + // Overlap volume + double atomOverlap(0.0); + double pharmOverlap(0.0); + + // Solution info + AlignmentInfo res; + + double oldVolume(0.0); + unsigned int iterations(0); + unsigned int mapIndex(0); + + // unsigned int DBSize = _gDb->pharmacophores.size(); + + while (iterations < 20) { + // reset volume + atomOverlap = 0.0; + pharmOverlap = 0.0; + iterations++; + + // reset gradient + overGrad = 0.0; + + // reset hessian + overHessian = 0.0; + + double lambda(0.0); + + // iterator over the matrix map + MatIter matIter; + + // create atom-atom overlaps + for (unsigned int i(0); i < _rAtoms; ++i) { + for (unsigned int j(0); j < _dAtoms; ++j) { + mapIndex = (i * _dGauss) + j; + + if ((matIter = _matrixMap.find(mapIndex)) == _matrixMap.end()) { + Aij = _updateMatrixMap(_gRef->gaussians[i], _gDb->gaussians[j]); + + // add to map + _matrixMap[mapIndex] = Aij; + } else { + Aij = matIter->second; + } + + // rotor product + Aq[0] = Aij[0] * rotor[0] + Aij[1] * rotor[1] + Aij[2] * rotor[2] + + Aij[3] * rotor[3]; + Aq[1] = Aij[4] * rotor[0] + Aij[5] * rotor[1] + Aij[6] * rotor[2] + + Aij[7] * rotor[3]; + Aq[2] = Aij[8] * rotor[0] + Aij[9] * rotor[1] + Aij[10] * rotor[2] + + Aij[11] * rotor[3]; + Aq[3] = Aij[12] * rotor[0] + Aij[13] * rotor[1] + Aij[14] * rotor[2] + + Aij[15] * rotor[3]; + + qAq = rotor[0] * Aq[0] + rotor[1] * Aq[1] + rotor[2] * Aq[2] + + rotor[3] * Aq[3]; + + // compute overlap volume + Vij = Aij[16] * exp(-qAq); + + // check if overlap is sufficient enough, should be more than 0.1 for + // atom - atom overlap + if (Vij / + (_gRef->gaussians[i].volume + _gDb->gaussians[j].volume - Vij) < + EPS) { + continue; + } + + // add to overlap volume + atomOverlap += Vij; + + // update gradient -2Vij (Aijq); + double v2 = 2.0 * Vij; + + lambda -= v2 * qAq; + + overGrad[0] -= v2 * Aq[0]; + overGrad[1] -= v2 * Aq[1]; + overGrad[2] -= v2 * Aq[2]; + overGrad[3] -= v2 * Aq[3]; + + // overHessian += 2*Vij(2*Aijq'qAij-Aij); (only upper triangular part) + overHessian[0][0] += v2 * (2.0 * Aq[0] * Aq[0] - Aij[0]); + overHessian[0][1] += v2 * (2.0 * Aq[0] * Aq[1] - Aij[1]); + overHessian[0][2] += v2 * (2.0 * Aq[0] * Aq[2] - Aij[2]); + overHessian[0][3] += v2 * (2.0 * Aq[0] * Aq[3] - Aij[3]); + overHessian[1][1] += v2 * (2.0 * Aq[1] * Aq[1] - Aij[5]); + overHessian[1][2] += v2 * (2.0 * Aq[1] * Aq[2] - Aij[6]); + overHessian[1][3] += v2 * (2.0 * Aq[1] * Aq[3] - Aij[7]); + overHessian[2][2] += v2 * (2.0 * Aq[2] * Aq[2] - Aij[10]); + overHessian[2][3] += v2 * (2.0 * Aq[2] * Aq[3] - Aij[11]); + overHessian[3][3] += v2 * (2.0 * Aq[3] * Aq[3] - Aij[15]); + + // loop over child nodes and add to queue + d1 = _gRef->childOverlaps[i]; + d2 = _gDb->childOverlaps[j]; + + // first add (i,child(j)) + if (d2 != nullptr) { + for (it1 = d2->begin(); it1 != d2->end(); ++it1) { + processQueue.push(std::make_pair(i, *it1)); + } + } + + // second add (child(i),j) + if (d1 != nullptr) { + for (it1 = d1->begin(); it1 != d1->end(); ++it1) { + processQueue.push(std::make_pair(*it1, j)); + } + } + } + } + + while (!processQueue.empty()) { + // get next element from queue + std::pair nextPair = processQueue.front(); + processQueue.pop(); + + unsigned int i = nextPair.first; + unsigned int j = nextPair.second; + + // check cache + mapIndex = (i * _dGauss) + j; + if ((matIter = _matrixMap.find(mapIndex)) == _matrixMap.end()) { + Aij = _updateMatrixMap(_gRef->gaussians[i], _gDb->gaussians[j]); + _matrixMap[mapIndex] = Aij; + } else { + Aij = matIter->second; + } + + // rotor product + Aq[0] = Aij[0] * rotor[0] + Aij[1] * rotor[1] + Aij[2] * rotor[2] + + Aij[3] * rotor[3]; + Aq[1] = Aij[4] * rotor[0] + Aij[5] * rotor[1] + Aij[6] * rotor[2] + + Aij[7] * rotor[3]; + Aq[2] = Aij[8] * rotor[0] + Aij[9] * rotor[1] + Aij[10] * rotor[2] + + Aij[11] * rotor[3]; + Aq[3] = Aij[12] * rotor[0] + Aij[13] * rotor[1] + Aij[14] * rotor[2] + + Aij[15] * rotor[3]; + + qAq = rotor[0] * Aq[0] + rotor[1] * Aq[1] + rotor[2] * Aq[2] + + rotor[3] * Aq[3]; + + // compute overlap volume + Vij = Aij[16] * exp(-qAq); + + // check if overlap is sufficient enough + if (fabs(Vij) / (_gRef->gaussians[i].volume + _gDb->gaussians[j].volume - + fabs(Vij)) < + EPS) { + continue; + } + + atomOverlap += Vij; + + double v2 = 2.0 * Vij; + + lambda -= v2 * qAq; + + // update gradient -2Vij (Cij*Aij*q); + overGrad[0] -= v2 * Aq[0]; + overGrad[1] -= v2 * Aq[1]; + overGrad[2] -= v2 * Aq[2]; + overGrad[3] -= v2 * Aq[3]; + + // hessian 2*Vij(2*AijqqAij-Aij); (only upper triangular part) + overHessian[0][0] += v2 * (2.0 * Aq[0] * Aq[0] - Aij[0]); + overHessian[0][1] += v2 * (2.0 * Aq[0] * Aq[1] - Aij[1]); + overHessian[0][2] += v2 * (2.0 * Aq[0] * Aq[2] - Aij[2]); + overHessian[0][3] += v2 * (2.0 * Aq[0] * Aq[3] - Aij[3]); + overHessian[1][1] += v2 * (2.0 * Aq[1] * Aq[1] - Aij[5]); + overHessian[1][2] += v2 * (2.0 * Aq[1] * Aq[2] - Aij[6]); + overHessian[1][3] += v2 * (2.0 * Aq[1] * Aq[3] - Aij[7]); + overHessian[2][2] += v2 * (2.0 * Aq[2] * Aq[2] - Aij[10]); + overHessian[2][3] += v2 * (2.0 * Aq[2] * Aq[3] - Aij[11]); + overHessian[3][3] += v2 * (2.0 * Aq[3] * Aq[3] - Aij[15]); + + // loop over child nodes and add to queue + d1 = _gRef->childOverlaps[i]; + d2 = _gDb->childOverlaps[j]; + if (d1 != nullptr && _gRef->gaussians[i].nbr > _gDb->gaussians[j].nbr) { + for (it1 = d1->begin(); it1 != d1->end(); ++it1) { + // add (child(i),j) + processQueue.push(std::make_pair(*it1, j)); + } + } else { + // first add (i,child(j)) + if (d2 != nullptr) { + for (it1 = d2->begin(); it1 != d2->end(); ++it1) { + processQueue.push(std::make_pair(i, *it1)); + } + } + if (d1 != nullptr && + _gDb->gaussians[j].nbr - _gRef->gaussians[i].nbr < 2) { + for (it1 = d1->begin(); it1 != d1->end(); ++it1) { + // add (child(i),j) + processQueue.push(std::make_pair(*it1, j)); + } + } + } + } + + // check if the new volume is better than the previously found one + // if not quit the loop + if (iterations > 6 && atomOverlap < oldVolume + 0.0001) { + break; + } + + // store latest volume found + oldVolume = atomOverlap; + + // no measurable overlap between two volumes + if (std::isnan(lambda) || std::isnan(oldVolume) || oldVolume == 0) { + break; + } + + // update solution + if (oldVolume > res.overlap) { + res.overlap = atomOverlap; + res.rotor = rotor; + if (res.overlap / (_gRef->overlap + _gDb->overlap - res.overlap) > 0.99) { + break; + } + } + + // update the gradient and hessian + overHessian -= lambda; + + // fill lower triangular of the hessian matrix + overHessian[1][0] = overHessian[0][1]; + overHessian[2][0] = overHessian[0][2]; + overHessian[2][1] = overHessian[1][2]; + overHessian[3][0] = overHessian[0][3]; + overHessian[3][1] = overHessian[1][3]; + overHessian[3][2] = overHessian[2][3]; + + // update gradient to make h + overGrad[0] -= lambda * rotor[0]; + overGrad[1] -= lambda * rotor[1]; + overGrad[2] -= lambda * rotor[2]; + overGrad[3] -= lambda * rotor[3]; + + // update gradient based on inverse hessian + SiMath::Vector tmp = rowProduct(overHessian, overGrad); + double h = overGrad[0] * tmp[0] + overGrad[1] * tmp[1] + + overGrad[2] * tmp[2] + overGrad[3] * tmp[3]; + + // small scaling of the gradient + h = 1 / h * + (overGrad[0] * overGrad[0] + overGrad[1] * overGrad[1] + + overGrad[2] * overGrad[2] + overGrad[3] * overGrad[3]); + overGrad *= h; + + // update rotor based on gradient information + rotor -= overGrad; + + // normalise rotor such that it has unit norm + double nr = sqrt(rotor[0] * rotor[0] + rotor[1] * rotor[1] + + rotor[2] * rotor[2] + rotor[3] * rotor[3]); + + rotor[0] /= nr; + rotor[1] /= nr; + rotor[2] /= nr; + rotor[3] /= nr; + + } // end of endless while loop + return res; +} + +AlignmentInfo ShapeAlignment::simulatedAnnealing(SiMath::Vector rotor) { + // create a queue to hold the pairs to process + std::queue> processQueue; + + // helper variables + // overlap matrix is stored as a double error + double *Aij; + double Aq[4]; + + // map store store already computed matrices + MatIter matIter; + + double Vij(0.0), qAq(0.0); + + std::vector *d1(nullptr); + std::vector *d2(nullptr); + std::vector::iterator it1; + + // overlap volume + double atomOverlap(0.0); + double pharmOverlap(0.0); + + double dTemperature = 1.1; + + // solution info + AlignmentInfo res; + + SiMath::Vector oldRotor(rotor); + SiMath::Vector bestRotor(rotor); + + double oldVolume(0.0); + double bestVolume(0.0); + unsigned int iterations(0); + unsigned int sameCount(0); + unsigned int mapIndex(0); + // unsigned int DBSize = _gDb->pharmacophores.size(); + + while (iterations < _maxIter) { + // reset volume + atomOverlap = 0.0; + pharmOverlap = 0.0; + + ++iterations; + + // temperature of the simulated annealing step + double T = sqrt((1.0 + iterations) / dTemperature); + + // create atom-atom overlaps + for (unsigned int i = 0; i < _rAtoms; ++i) { + for (unsigned int j = 0; j < _dAtoms; ++j) { + mapIndex = (i * _dGauss) + j; + + if ((matIter = _matrixMap.find(mapIndex)) == _matrixMap.end()) { + Aij = _updateMatrixMap(_gRef->gaussians[i], _gDb->gaussians[j]); + _matrixMap[mapIndex] = Aij; + } else { + Aij = matIter->second; + } + + // rotor product + Aq[0] = Aij[0] * rotor[0] + Aij[1] * rotor[1] + Aij[2] * rotor[2] + + Aij[3] * rotor[3]; + Aq[1] = Aij[4] * rotor[0] + Aij[5] * rotor[1] + Aij[6] * rotor[2] + + Aij[7] * rotor[3]; + Aq[2] = Aij[8] * rotor[0] + Aij[9] * rotor[1] + Aij[10] * rotor[2] + + Aij[11] * rotor[3]; + Aq[3] = Aij[12] * rotor[0] + Aij[13] * rotor[1] + Aij[14] * rotor[2] + + Aij[15] * rotor[3]; + + qAq = rotor[0] * Aq[0] + rotor[1] * Aq[1] + rotor[2] * Aq[2] + + rotor[3] * Aq[3]; + + // compute overlap volume + Vij = Aij[16] * exp(-qAq); + + // check if overlap is sufficient enough, should be more than 0.1 for + // atom - atom overlap + if (Vij / + (_gRef->gaussians[i].volume + _gDb->gaussians[j].volume - Vij) < + EPS) { + continue; + } + + // add to overlap volume + atomOverlap += Vij; + + // loop over child nodes and add to queue + d1 = _gRef->childOverlaps[i]; + d2 = _gDb->childOverlaps[j]; + + // first add (i,child(j)) + if (d2 != nullptr) { + for (it1 = d2->begin(); it1 != d2->end(); ++it1) { + processQueue.push(std::make_pair(i, *it1)); + } + } + // second add (child(i),j) + if (d1 != nullptr) { + for (it1 = d1->begin(); it1 != d1->end(); ++it1) { + processQueue.push(std::make_pair(*it1, j)); + } + } + } + } + + while (!processQueue.empty()) { + // get next element from queue + std::pair nextPair = processQueue.front(); + processQueue.pop(); + + unsigned int i = nextPair.first; + unsigned int j = nextPair.second; + + // check cache + mapIndex = (i * _dGauss) + j; + if ((matIter = _matrixMap.find(mapIndex)) == _matrixMap.end()) { + Aij = _updateMatrixMap(_gRef->gaussians[i], _gDb->gaussians[j]); + _matrixMap[mapIndex] = Aij; + } else { + Aij = matIter->second; + } + + // rotor product + Aq[0] = Aij[0] * rotor[0] + Aij[1] * rotor[1] + Aij[2] * rotor[2] + + Aij[3] * rotor[3]; + Aq[1] = Aij[4] * rotor[0] + Aij[5] * rotor[1] + Aij[6] * rotor[2] + + Aij[7] * rotor[3]; + Aq[2] = Aij[8] * rotor[0] + Aij[9] * rotor[1] + Aij[10] * rotor[2] + + Aij[11] * rotor[3]; + Aq[3] = Aij[12] * rotor[0] + Aij[13] * rotor[1] + Aij[14] * rotor[2] + + Aij[15] * rotor[3]; + + qAq = rotor[0] * Aq[0] + rotor[1] * Aq[1] + rotor[2] * Aq[2] + + rotor[3] * Aq[3]; + + // compute overlap volume + Vij = Aij[16] * exp(-qAq); + + // check if overlap is sufficient enough + if (fabs(Vij) / (_gRef->gaussians[i].volume + _gDb->gaussians[j].volume - + fabs(Vij)) < + EPS) { + continue; + } + + // even number of overlap atoms => addition to volume + atomOverlap += Vij; + + // loop over child nodes and add to queue + d1 = _gRef->childOverlaps[i]; + d2 = _gDb->childOverlaps[j]; + if (d1 != nullptr && _gRef->gaussians[i].nbr > _gDb->gaussians[j].nbr) { + for (it1 = d1->begin(); it1 != d1->end(); ++it1) { + // add (child(i),j) + processQueue.push(std::make_pair(*it1, j)); + } + } else { + // first add (i,child(j)) + if (d2 != nullptr) { + for (it1 = d2->begin(); it1 != d2->end(); ++it1) { + processQueue.push(std::make_pair(i, *it1)); + } + } + if (d1 != nullptr && + _gDb->gaussians[j].nbr - _gRef->gaussians[i].nbr < 2) { + for (it1 = d1->begin(); it1 != d1->end(); ++it1) { + // add (child(i),j) + processQueue.push(std::make_pair(*it1, j)); + } + } + } + } + + // check if the new volume is better than the previously found one + double overlapVol = atomOverlap; + if (overlapVol < oldVolume) { + double D = exp(-sqrt(oldVolume - overlapVol)) / T; + if (SiMath::randD(0, 1) < D) { + oldRotor = rotor; + oldVolume = overlapVol; + sameCount = 0; + } else { + ++sameCount; + if (sameCount == 30) { + iterations = _maxIter; + } + } + } else { + // store latest volume found + oldVolume = overlapVol; + oldRotor = rotor; + + // update best found so far + bestRotor = rotor; + bestVolume = overlapVol; + sameCount = 0; + + // check if it is better than the best solution found so far + if (overlapVol > res.overlap) { + res.overlap = atomOverlap; + res.rotor = rotor; + if ((res.overlap / (_gRef->overlap + _gDb->overlap - res.overlap)) > + 0.99) { + break; + } + } + } + + // make random permutation + // double range = 0.05; + double range = 0.1 / T; + rotor[0] = oldRotor[0] + SiMath::randD(-range, range); + rotor[1] = oldRotor[1] + SiMath::randD(-range, range); + rotor[2] = oldRotor[2] + SiMath::randD(-range, range); + rotor[3] = oldRotor[3] + SiMath::randD(-range, range); + + // normalise rotor such that it has unit norm + double nr = sqrt(rotor[0] * rotor[0] + rotor[1] * rotor[1] + + rotor[2] * rotor[2] + rotor[3] * rotor[3]); + rotor[0] /= nr; + rotor[1] /= nr; + rotor[2] /= nr; + rotor[3] /= nr; + + } // end of endless while loop + + return res; +} + +void ShapeAlignment::setMaxIterations(unsigned int i) { + _maxIter = i; + return; +} + +double *ShapeAlignment::_updateMatrixMap(const AtomGaussian &a, + const AtomGaussian &b) { + auto *A = new double[17]; + + // variables to store sum and difference of components + double dx = (a.center.x - b.center.x); + double dx2 = dx * dx; + double dy = (a.center.y - b.center.y); + double dy2 = dy * dy; + double dz = (a.center.z - b.center.z); + double dz2 = dz * dz; + double sx = (a.center.x + b.center.x); + double sx2 = sx * sx; + double sy = (a.center.y + b.center.y); + double sy2 = sy * sy; + double sz = (a.center.z + b.center.z); + double sz2 = sz * sz; + + // update overlap matrix + double C = a.alpha * b.alpha / (a.alpha + b.alpha); + A[0] = C * (dx2 + dy2 + dz2); + A[1] = C * (dy * sz - dz * sy); + A[2] = C * (dz * sx - dx * sz); + A[3] = C * (dx * sy - dy * sx); + A[4] = A[1]; + A[5] = C * (dx2 + sy2 + sz2); + A[6] = C * (dx * dy - sx * sy); + A[7] = C * (dx * dz - sx * sz); + A[8] = A[2]; + A[9] = A[6]; + A[10] = C * (sx2 + dy2 + sz2); + A[11] = C * (dy * dz - sy * sz); + A[12] = A[3]; + A[13] = A[7]; + A[14] = A[11]; + A[15] = C * (sx2 + sy2 + dz2); + + // last elements holds overlap scaling constant + // even number of overlap atoms => addition to volume + // odd number => substraction + if ((a.nbr + b.nbr) % 2 == 0) { + A[16] = a.C * b.C * pow(PI / (a.alpha + b.alpha), 1.5); + } else { + A[16] = -a.C * b.C * pow(PI / (a.alpha + b.alpha), 1.5); + } + + return A; +} +","C++" +"In Silico","rdkit/shape-it","src/alignmentInfo.cpp",".cpp","1794","41","/******************************************************************************* +alignmentInfo.cpp - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#include + +AlignmentInfo::AlignmentInfo() : overlap(0.0), rotor(4, 0.0) { + rotor[0] = 1.0; +} + +AlignmentInfo::~AlignmentInfo() = default; +","C++" +"In Silico","rdkit/shape-it","src/printHeader.cpp",".cpp","3615","89","/******************************************************************************* +printHeader.cpp - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#include +#ifndef USE_RDKIT +// OpenBabel +#include +#else +#include +#endif + +void printHeader() { + std::cerr << ""+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"" + ""++++++++++++"" + << std::endl; + std::cerr << "" Shape-it v"" << SHAPEIT_VERSION << ""."" << SHAPEIT_RELEASE + << ""."" << SHAPEIT_SUBRELEASE << "" | ""; + std::cerr << __DATE__ "" "" << __TIME__ << std::endl; + std::cerr << std::endl; + std::cerr << "" -> GCC: "" << __VERSION__ << std::endl; +#ifndef USE_RDKIT + std::cerr << "" -> OpenBabel: "" << BABEL_VERSION << std::endl; +#else + std::cerr << "" -> RDKit: "" << RDKit::rdkitVersion << std::endl; +#endif + std::cerr << std::endl; + std::cerr + << R""DOC( Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, + and the Shape-it contributors + + Shape-it is free software: you can redistribute it and/or modify + it under the terms of the MIT license. + + Shape-it 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 + MIT License for more details. +)DOC"" << std::endl; +#ifndef USE_RDKIT + std::cerr << "" Shape-it is linked against OpenBabel version 2."" << std::endl; + std::cerr + << "" OpenBabel is free software; you can redistribute it and/or modify"" + << std::endl; + std::cerr << "" it under the terms of the GNU General Public License as "" + ""published by"" + << std::endl; + std::cerr << "" the Free Software Foundation version 2 of the License."" + << std::endl; +#else + std::cerr << "" Shape-it is linked against the RDKit (https://www.rdkit.org)."" + << std::endl; +#endif + std::cerr << ""+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"" + ""++++++++++++"" + << std::endl; + std::cerr << std::endl; + return; +} +","C++" +"In Silico","rdkit/shape-it","src/mainErr.cpp",".cpp","1761","40","/******************************************************************************* +mainErr.cpp - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#include + +void mainErr(const std::string &msg) { + std::cerr << ""**MainError** "" << msg << std::endl; + exit(1); +} +","C++" +"In Silico","rdkit/shape-it","src/gaussianVolume.cpp",".cpp","19217","629","/******************************************************************************* +gaussianVolume.cpp - Shape-it + +Copyright 2012-2021 by Silicos-it, a division of Imacosi BVBA, Hans De Winter, +and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Shape-it can be linked against either OpenBabel version 3 or the RDKit. + + OpenBabel 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 version 2 of the License. + +***********************************************************************/ + +#include + +#ifndef USE_RDKIT +// OpenBabel +#include +#include +#include +#include +#else +#include +#include +#endif + +// OpenBabel + +GaussianVolume::GaussianVolume() + : volume(0.0), overlap(0.0), centroid(0.0, 0.0, 0.0), rotation(3, 3, 0.0), + gaussians(), childOverlaps(), levels() {} + +GaussianVolume::~GaussianVolume() = default; + +double GAlpha(unsigned int an) { + switch (an) { + case 1: ///< H + return 1.679158285; + break; + case 3: ///< Li + return 0.729980658; + break; + case 5: ///< B + return 0.604496983; + break; + case 6: ///< C + return 0.836674025; + break; + case 7: ///< N + return 1.006446589; + break; + case 8: ///< O + return 1.046566798; + break; + case 9: ///< F + return 1.118972618; + break; + case 11: ///< Na + return 0.469247983; + break; + case 12: ///< Mg + return 0.807908026; + break; + case 14: ///< Si + return 0.548296583; + break; + case 15: ///< P + return 0.746292571; + break; + case 16: ///< S + return 0.746292571; + break; + case 17: ///< Cl + return 0.789547080; + break; + case 19: ///< K + return 0.319733941; + break; + case 20: ///< Ca + return 0.604496983; + break; + case 26: ///< Fe + return 1.998337133; + break; + case 29: ///< Cu + return 1.233667312; + break; + case 30: ///< Zn + return 1.251481772; + break; + case 35: ///< Br + return 0.706497569; + break; + case 53: ///< I + return 0.616770720; + break; + default: ///< * + return 1.074661303; + } + return 1.074661303; +}; + +namespace { +#ifndef USE_RDKIT + +unsigned int initFromMol(const Molecule &mol, GaussianVolume &gv) { + // Prepare the vector to store the atom and overlap volumes; + unsigned int N = 0; + for (unsigned int i = 1; i <= mol.NumAtoms(); ++i) { + const OpenBabel::OBAtom *a = mol.GetAtom(i); + if (a->GetAtomicNum() == 1) { + continue; + } else { + ++N; + } + } + gv.gaussians.resize(N); + gv.childOverlaps.resize(N); + gv.levels.push_back(N); // first level + gv.volume = 0.0; + gv.centroid.x = 0; + gv.centroid.y = 0; + gv.centroid.z = 0; + int atomIndex = 0; // keeps track of the atoms processed so far + int vecIndex = N; // keeps track of the last element added to the vectors + for (unsigned int i = 1; i <= mol.NumAtoms(); ++i) { + const OpenBabel::OBAtom *a = mol.GetAtom(i); + // Skip hydrogens + if (a->GetAtomicNum() == 1) { + continue; + } + + // First atom append self to the list + // Store it at [index] + gv.gaussians[atomIndex].center.x = a->GetX(); + gv.gaussians[atomIndex].center.y = a->GetY(); + gv.gaussians[atomIndex].center.z = a->GetZ(); + gv.gaussians[atomIndex].alpha = GAlpha(a->GetAtomicNum()); + gv.gaussians[atomIndex].C = GCI; + double radius = OpenBabel::OBElements::GetVdwRad(a->GetAtomicNum()); + gv.gaussians[atomIndex].volume = + (4.0 * PI / 3.0) * radius * radius * radius; + ++atomIndex; + } + return N; +} +#else +unsigned int initFromMol(const Molecule &mol, GaussianVolume &gv) { + // Prepare the vector to store the atom and overlap volumes; + unsigned int N = 0; + for (const auto a : mol.atoms()) { + if (a->getAtomicNum() != 1) { + ++N; + } + } + gv.gaussians.resize(N); + gv.childOverlaps.resize(N); + gv.levels.push_back(N); // first level + gv.volume = 0.0; + gv.centroid.x = 0; + gv.centroid.y = 0; + gv.centroid.z = 0; + int atomIndex = 0; // keeps track of the atoms processed so far + int vecIndex = N; // keeps track of the last element added to the vectors + const auto &conf = mol.getConformer(); + for (const auto a : mol.atoms()) { + // Skip hydrogens + if (a->getAtomicNum() == 1) { + continue; + } + + // First atom append self to the list + // Store it at [index] + const auto &p = conf.getAtomPos(a->getIdx()); + gv.gaussians[atomIndex].center.x = p.x; + gv.gaussians[atomIndex].center.y = p.y; + gv.gaussians[atomIndex].center.z = p.z; + gv.gaussians[atomIndex].alpha = GAlpha(a->getAtomicNum()); + gv.gaussians[atomIndex].C = GCI; + // double radius = et.GetVdwRad(a->GetAtomicNum()); + double radius = + RDKit::PeriodicTable::getTable()->getRvdw(a->getAtomicNum()); + gv.gaussians[atomIndex].volume = + (4.0 * PI / 3.0) * radius * radius * radius; + ++atomIndex; + } + return N; +} + +#endif + +} // namespace + +void listAtomVolumes(const Molecule &mol, GaussianVolume &gv) { + // Prepare the vector to store the atom and overlap volumes; + unsigned int N = initFromMol(mol, gv); + + // Vector to keep track of parents of an overlap + std::vector> parents(N); + + // Create a vector to keep track of the overlaps + // Overlaps are stored as sets + std::vector *> overlaps(N); + + // Start by iterating over the single atoms and build map of overlaps + int vecIndex = N; // keeps track of the last element added to the vectors + for (unsigned int atomIndex = 0; atomIndex < N; ++atomIndex) { + // Add empty child overlaps + auto *vec = new std::vector(); + gv.childOverlaps[atomIndex] = vec; + + // Update volume and centroid + gv.volume += gv.gaussians[atomIndex].volume; + gv.centroid.x += + gv.gaussians[atomIndex].volume * gv.gaussians[atomIndex].center.x; + gv.centroid.y += + gv.gaussians[atomIndex].volume * gv.gaussians[atomIndex].center.y; + gv.centroid.z += + gv.gaussians[atomIndex].volume * gv.gaussians[atomIndex].center.z; + + // Add new empty set of possible overlaps + auto *tmp = new std::set(); + overlaps[atomIndex] = tmp; + + // Loop over the current list of processed atoms and add overlaps + for (int i = 0; i < atomIndex; ++i) { + // Create overlap gaussian + AtomGaussian ga = + atomIntersection(gv.gaussians[i], gv.gaussians[atomIndex]); + + // Check if the atom-atom overlap volume is large enough + if (ga.volume / (gv.gaussians[i].volume + gv.gaussians[atomIndex].volume - + ga.volume) < + EPS) { + continue; + } + + // Add gaussian volume, and empty overlap set + gv.gaussians.push_back(ga); + auto *vec = new std::vector(); + gv.childOverlaps.push_back(vec); + + // Update local variables of parents and possible overlaps + parents.emplace_back(i, atomIndex); + auto *dummy = new std::set(); + overlaps.push_back(dummy); + + // Update volume and centroid (negative contribution of atom-atom overlap) + gv.volume -= ga.volume; + gv.centroid.x -= ga.volume * ga.center.x; + gv.centroid.y -= ga.volume * ga.center.y; + gv.centroid.z -= ga.volume * ga.center.z; + + // Update overlap information of the parent atom + overlaps[i]->insert(atomIndex); + gv.childOverlaps[i]->push_back(vecIndex); + + // Move to next index in vector + ++vecIndex; + } + } + + // Position in list of gaussians where atom gaussians end + unsigned int startLevel = N; + unsigned int nextLevel = gv.gaussians.size(); + + // Update level information + gv.levels.push_back(nextLevel); + + // Loop overall possible levels of overlaps from 2 to 6 + for (unsigned int l = 2; l < LEVEL; ++l) { + // List of atom-atom overlaps is made => gv.gaussians[startLevel .. + // nextLevel-1]; Now update the overlap lists for each overlap in this level + // Create the next overlap Gaussian + // And add it to the vector of overlaps + for (unsigned int i = startLevel; i < nextLevel; ++i) { + // Parent indices + unsigned int a1 = parents[i].first; + unsigned int a2 = parents[i].second; + + // Append volume to end of overlap vector + // Add new empty set + std::set *tmp = overlaps[i]; + std::set_intersection( + overlaps[a1]->begin(), overlaps[a1]->end(), overlaps[a2]->begin(), + overlaps[a2]->end(), + std::insert_iterator>(*tmp, tmp->begin())); + + // Check if the overlap list is empty + if (overlaps[i]->empty()) { + continue; + } + + // Get the possible overlaps from the parent gaussians + // and create the new overlap volume + for (auto overlapIdx : *overlaps[i]) { + if (overlapIdx <= a2) { + continue; + } + + // Create a new overlap gaussian + AtomGaussian ga = + atomIntersection(gv.gaussians[i], gv.gaussians[overlapIdx]); + + // Check if the volume is large enough + if (ga.volume / (gv.gaussians[i].volume + + gv.gaussians[overlapIdx].volume - ga.volume) < + EPS) { + continue; + } + + gv.gaussians.push_back(ga); + auto *vec = new std::vector(); + gv.childOverlaps.push_back(vec); + + // Update local variables + parents.emplace_back(i, overlapIdx); + auto *tmp = new std::set(); + overlaps.push_back(tmp); + + // Update volume, centroid and moments + // Overlaps consisting of an even number of atoms have a negative + // contribution + if ((ga.nbr % 2) == 0) { + // Update volume and centroid + gv.volume -= ga.volume; + gv.centroid.x -= ga.volume * ga.center.x; + gv.centroid.y -= ga.volume * ga.center.y; + gv.centroid.z -= ga.volume * ga.center.z; + } else { + // Update volume and centroid + gv.volume += ga.volume; + gv.centroid.x += ga.volume * ga.center.x; + gv.centroid.y += ga.volume * ga.center.y; + gv.centroid.z += ga.volume * ga.center.z; + } + + // Update child list of the first + gv.childOverlaps[i]->push_back(vecIndex); + + // Move to next index in vector + ++vecIndex; + } + } + + // Update levels + startLevel = nextLevel; + nextLevel = gv.gaussians.size(); + + // Update level information + gv.levels.push_back(nextLevel); + } + + // cleanup current set of computed overlaps + for (auto &overlap : overlaps) { + delete overlap; + overlap = nullptr; + } + + parents.clear(); + + // Update self-overlap + gv.overlap = atomOverlap(gv, gv); + + return; +} + +void initOrientation(GaussianVolume &gv) { + double x(0.0), y(0.0), z(0.0); + + // Scale centroid and moments with self volume + gv.centroid.x /= gv.volume; + gv.centroid.y /= gv.volume; + gv.centroid.z /= gv.volume; + + // Compute moments of inertia from mass matrix + SiMath::Matrix mass(3, 3, 0.0); + + // Loop over all gaussians + for (auto &g : gv.gaussians) { + // Translate to center + g.center.x -= gv.centroid.x; + g.center.y -= gv.centroid.y; + g.center.z -= gv.centroid.z; + + x = g.center.x; + y = g.center.y; + z = g.center.z; + + if ((g.nbr % 2) == 0) { + // Update upper triangle + mass[0][0] -= g.volume * x * x; + mass[0][1] -= g.volume * x * y; + mass[0][2] -= g.volume * x * z; + mass[1][1] -= g.volume * y * y; + mass[1][2] -= g.volume * y * z; + mass[2][2] -= g.volume * z * z; + } else { + // Update upper triangle + mass[0][0] += g.volume * x * x; + mass[0][1] += g.volume * x * y; + mass[0][2] += g.volume * x * z; + mass[1][1] += g.volume * y * y; + mass[1][2] += g.volume * y * z; + mass[2][2] += g.volume * z * z; + } + } + + // Set lower triangle + mass[1][0] = mass[0][1]; + mass[2][0] = mass[0][2]; + mass[2][1] = mass[1][2]; + + // Normalize mass matrix + mass /= gv.volume; + + // Compute SVD of the mass matrix + SiMath::SVD svd(mass, true, true); + gv.rotation = svd.getU(); + + double det = gv.rotation[0][0] * gv.rotation[1][1] * gv.rotation[2][2] + + gv.rotation[2][1] * gv.rotation[1][0] * gv.rotation[0][2] + + gv.rotation[0][1] * gv.rotation[1][2] * gv.rotation[2][0] - + gv.rotation[0][0] * gv.rotation[1][2] * gv.rotation[2][1] - + gv.rotation[1][1] * gv.rotation[2][0] * gv.rotation[0][2] - + gv.rotation[2][2] * gv.rotation[0][1] * gv.rotation[1][0]; + + // Check if it is a rotation matrix and not a mirroring + if (det < 0) { + // Switch sign of third column + gv.rotation[0][2] = -gv.rotation[0][2]; + gv.rotation[1][2] = -gv.rotation[1][2]; + gv.rotation[2][2] = -gv.rotation[2][2]; + } + + // Rotate all gaussians + for (auto &g : gv.gaussians) { + x = g.center.x; + y = g.center.y; + z = g.center.z; + g.center.x = + gv.rotation[0][0] * x + gv.rotation[1][0] * y + gv.rotation[2][0] * z; + g.center.y = + gv.rotation[0][1] * x + gv.rotation[1][1] * y + gv.rotation[2][1] * z; + g.center.z = + gv.rotation[0][2] * x + gv.rotation[1][2] * y + gv.rotation[2][2] * z; + } + + return; +} + +double atomOverlap(const GaussianVolume &gRef, const GaussianVolume &gDb) { + // Create a queue to hold the pairs to process + std::queue> processQueue; + + // loop over the single atom volumes of both molecules and make the + // combinations + unsigned int N1(gRef.levels[0]); + unsigned int N2(gDb.levels[0]); + + double Cij(0.0), Vij(0.0); + + double dx(0.0), dy(0.0), dz(0.0); + + std::vector *d1(nullptr), *d2(nullptr); + std::vector::iterator it1; + + // Overlap volume + double overlapVol(0.0); + + // First compute atom-atom overlaps + for (unsigned int i(0); i < N1; ++i) { + for (unsigned int j(0); j < N2; ++j) { + // Scaling constant + Cij = gRef.gaussians[i].alpha * gDb.gaussians[j].alpha / + (gRef.gaussians[i].alpha + gDb.gaussians[j].alpha); + + // Variables to store sum and difference of components + dx = (gRef.gaussians[i].center.x - gDb.gaussians[j].center.x); + dx *= dx; + dy = (gRef.gaussians[i].center.y - gDb.gaussians[j].center.y); + dy *= dy; + dz = (gRef.gaussians[i].center.z - gDb.gaussians[j].center.z); + dz *= dz; + + // Compute overlap volume + Vij = gRef.gaussians[i].C * gDb.gaussians[j].C * + pow(PI / (gRef.gaussians[i].alpha + gDb.gaussians[j].alpha), 1.5) * + exp(-Cij * (dx + dy + dz)); + + // Check if overlap is sufficient enough + if (Vij / (gRef.gaussians[i].volume + gDb.gaussians[j].volume - Vij) < + EPS) { + continue; + } + + // Add to overlap volume + overlapVol += Vij; + + // Loop over child nodes and add to queue + d1 = gRef.childOverlaps[i]; + d2 = gDb.childOverlaps[j]; + + // First add (i,child(j)) + if (d2 != nullptr) { + for (it1 = d2->begin(); it1 != d2->end(); ++it1) { + processQueue.push(std::make_pair(i, *it1)); + } + } + // Second add (child(i,j)) + if (d1 != nullptr) { + for (it1 = d1->begin(); it1 != d1->end(); ++it1) { + // add (child(i),j) + processQueue.push(std::make_pair(*it1, j)); + } + } + } + } + + while (!processQueue.empty()) { + // Get next element from queue + std::pair nextPair = processQueue.front(); + processQueue.pop(); + + unsigned int i = nextPair.first; + unsigned int j = nextPair.second; + + // Scaling constant + Cij = gRef.gaussians[i].alpha * gDb.gaussians[j].alpha / + (gRef.gaussians[i].alpha + gDb.gaussians[j].alpha); + + // Variables to store sum and difference of components + dx = (gRef.gaussians[i].center.x - gDb.gaussians[j].center.x); + dx *= dx; + dy = (gRef.gaussians[i].center.y - gDb.gaussians[j].center.y); + dy *= dy; + dz = (gRef.gaussians[i].center.z - gDb.gaussians[j].center.z); + dz *= dz; + + // Compute overlap volume + Vij = gRef.gaussians[i].C * gDb.gaussians[j].C * + pow(PI / (gRef.gaussians[i].alpha + gDb.gaussians[j].alpha), 1.5) * + exp(-Cij * (dx + dy + dz)); + + // Check if overlap is sufficient enough + if (Vij / (gRef.gaussians[i].volume + gDb.gaussians[j].volume - Vij) < + EPS) { + continue; + } + + // Even number of overlap atoms => addition to volume + // Odd number => substraction + if ((gRef.gaussians[i].nbr + gDb.gaussians[j].nbr) % 2 == 0) { + overlapVol += Vij; + } else { + overlapVol -= Vij; + } + + // Loop over child nodes and add to queue + d1 = gRef.childOverlaps[i]; + d2 = gDb.childOverlaps[j]; + if (d1 != nullptr && gRef.gaussians[i].nbr > gDb.gaussians[j].nbr) { + for (it1 = d1->begin(); it1 != d1->end(); ++it1) { + // Add (child(i),j) + processQueue.push(std::make_pair(*it1, j)); + } + } else { + // First add (i,child(j)) + if (d2 != nullptr) { + for (it1 = d2->begin(); it1 != d2->end(); ++it1) { + processQueue.push(std::make_pair(i, *it1)); + } + } + if (d1 != nullptr && gDb.gaussians[j].nbr - gRef.gaussians[i].nbr < 2) { + for (it1 = d1->begin(); it1 != d1->end(); ++it1) { + // add (child(i),j) + processQueue.push(std::make_pair(*it1, j)); + } + } + } + } + + return overlapVol; +} + +double getScore(const std::string &id, double Voa, double Vra, double Vda) { + // set the score by which molecules are being compared + if (id == tanimoto) { + return Voa / (Vra + Vda - Voa); + } else if (id == tversky_ref) { + return Voa / (0.95 * Vra + 0.05 * Vda); + } else if (id == tversky_db) { + return Voa / (0.05 * Vra + 0.95 * Vda); + } + + return 0.0; +} + +void checkVolumes(const GaussianVolume &gRef, const GaussianVolume &gDb, + AlignmentInfo &res) { + if (res.overlap > gRef.overlap) { + res.overlap = gRef.overlap; + } + if (res.overlap > gDb.overlap) { + res.overlap = gDb.overlap; + } + return; +} +","C++" +"In Silico","rdkit/shape-it","src/Wrap/cpyshapeit.cpp",".cpp","2143","54","/******************************************************************************* + +Copyright 2021 by Greg Landrum and the Shape-it contributors + +This file is part of Shape-it. + +Permission is hereby granted, free of charge, to any person obtaining a copy of +this software and associated documentation files (the ""Software""), to deal in +the Software without restriction, including without limitation the rights to +use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software is furnished to do so, +subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +***********************************************************************/ + +#include + +#include ""alignLib.h"" +#include ""options.h"" + +namespace python = boost::python; +using namespace RDKit; + +namespace { +double alignMol(const ROMol &ref, ROMol &probe, const std::string &whichScore, + double maxIter, double cutoff) { + auto sinfo = shapeit::alignMols(ref, probe, whichScore, maxIter, cutoff); + const Conformer &conf = sinfo.dbMol.getConformer(); + probe.clearConformers(); + probe.addConformer(new Conformer(conf)); + return sinfo.score; +} +} // namespace + +void wrap_pyshapeit() { + python::def(""AlignMol"", &alignMol, + (python::arg(""ref""), python::arg(""probe""), + python::arg(""whichScore"") = tanimoto, + python::arg(""maxIter"") = 0., python::arg(""cutoff"") = 0.), + ""aligns probe to ref, probe is modified""); +} + +BOOST_PYTHON_MODULE(cpyshapeit) { wrap_pyshapeit(); } +","C++" +"In Silico","rdkit/shape-it","pyshapeit/__init__.py",".py","61","4","# Copyright (C) 2021 Greg Landrum + +from .cpyshapeit import * +","Python" +"In Silico","rdkit/shape-it","pyshapeit/basic_test.py",".py","6504","176","# +# Copyright 2021 by Greg Landrum and the Shape-it contributors +# +# This file is part of Shape-it. +# +# Permission is hereby granted, free of charge, to any person obtaining a copy of +# this software and associated documentation files (the ""Software""), to deal in +# the Software without restriction, including without limitation the rights to +# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of +# the Software, and to permit persons to whom the Software is furnished to do so, +# subject to the following conditions: +# +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. +# +# THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS +# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER +# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN +# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +from rdkit import Chem +from rdkit.Chem import rdMolAlign +import cpyshapeit + +import unittest + + +class TestCase(unittest.TestCase): + def testMols(self): + ref = Chem.MolFromMolBlock('''3l5u_lig_ZEC + 3D + Structure written by MMmdl. + 20 21 0 0 1 0 999 V2000 + 15.0500 -34.9220 -18.1430 O 0 0 0 0 0 0 + 14.9110 -34.7040 -19.4790 C 0 0 0 0 0 0 + 14.7350 -35.7750 -20.3500 C 0 0 0 0 0 0 + 14.6060 -35.5430 -21.7160 C 0 0 0 0 0 0 + 14.3620 -36.6080 -23.0370 S 0 0 0 0 0 0 + 14.3210 -35.3400 -24.1850 C 0 0 0 0 0 0 + 14.0030 -35.5290 -25.8940 S 0 0 0 0 0 0 + 15.1750 -34.7990 -26.7570 N 0 0 0 0 0 0 + 12.6760 -34.9070 -26.2170 O 0 0 0 0 0 0 + 13.9630 -36.9930 -26.2180 O 0 0 0 0 0 0 + 14.4970 -34.1790 -23.5590 N 0 0 0 0 0 0 + 14.6510 -34.2470 -22.2350 C 0 0 0 0 0 0 + 14.8270 -33.1870 -21.3480 C 0 0 0 0 0 0 + 14.9560 -33.4070 -19.9800 C 0 0 0 0 0 0 + 15.1610 -34.0820 -17.6920 H 0 0 0 0 0 0 + 14.6990 -36.7830 -19.9650 H 0 0 0 0 0 0 + 15.1440 -34.8130 -27.7660 H 0 0 0 0 0 0 + 15.9340 -34.3310 -26.2820 H 0 0 0 0 0 0 + 14.8640 -32.1730 -21.7190 H 0 0 0 0 0 0 + 15.0910 -32.5720 -19.3090 H 0 0 0 0 0 0 + 1 2 1 0 0 0 + 1 15 1 0 0 0 + 2 3 2 0 0 0 + 2 14 1 0 0 0 + 3 4 1 0 0 0 + 3 16 1 0 0 0 + 4 5 1 0 0 0 + 4 12 2 0 0 0 + 5 6 1 0 0 0 + 6 7 1 0 0 0 + 6 11 2 0 0 0 + 7 8 1 0 0 0 + 7 9 2 0 0 0 + 7 10 2 0 0 0 + 8 17 1 0 0 0 + 8 18 1 0 0 0 + 11 12 1 0 0 0 + 12 13 1 0 0 0 + 13 14 2 0 0 0 + 13 19 1 0 0 0 + 14 20 1 0 0 0 +M END''') + probe = Chem.MolFromMolBlock('''3hof_lig_DHC + 3D + Structure written by MMmdl. + 20 20 0 0 1 0 999 V2000 + 14.6290 -34.5170 -18.4190 C 0 0 0 0 0 0 + 15.6070 -34.6620 -17.5400 O 0 0 0 0 0 0 + 14.9220 -34.5200 -19.8370 C 0 0 0 0 0 0 + 14.7370 -35.7220 -20.3520 C 0 0 0 0 0 0 + 14.9680 -35.9740 -21.7740 C 0 0 0 0 0 0 + 14.8780 -34.9380 -22.6930 C 0 0 0 0 0 0 + 15.1020 -35.2380 -24.0360 C 0 0 0 0 0 0 + 15.4390 -36.6310 -24.4550 C 0 0 0 0 0 0 + 15.5160 -37.6070 -23.4830 C 0 0 0 0 0 0 + 15.2760 -37.2740 -22.1560 C 0 0 0 0 0 0 + 15.6830 -36.9520 -25.7670 O 0 0 0 0 0 0 + 15.0160 -34.2570 -24.9550 O 0 0 0 0 0 0 + 13.4860 -34.4200 -18.0300 O 0 5 0 0 0 0 + 15.2430 -33.6100 -20.3240 H 0 0 0 0 0 0 + 14.4110 -36.5360 -19.7210 H 0 0 0 0 0 0 + 14.6410 -33.9380 -22.3590 H 0 0 0 0 0 0 + 15.7620 -38.6220 -23.7550 H 0 0 0 0 0 0 + 15.3330 -38.0570 -21.4140 H 0 0 0 0 0 0 + 15.1950 -34.6170 -25.8260 H 0 0 0 0 0 0 + 15.8806 -37.8889 -25.8363 H 0 0 0 0 0 0 + 1 2 2 0 0 0 + 1 3 1 0 0 0 + 1 13 1 0 0 0 + 3 4 2 0 0 0 + 3 14 1 0 0 0 + 4 5 1 0 0 0 + 4 15 1 0 0 0 + 5 6 2 0 0 0 + 5 10 1 0 0 0 + 6 7 1 0 0 0 + 6 16 1 0 0 0 + 7 8 2 0 0 0 + 7 12 1 0 0 0 + 8 9 1 0 0 0 + 8 11 1 0 0 0 + 9 10 2 0 0 0 + 9 17 1 0 0 0 + 10 18 1 0 0 0 + 11 20 1 0 0 0 + 12 19 1 0 0 0 +M CHG 1 13 -1 +M END''') + tmp = Chem.Mol(probe) + score = cpyshapeit.AlignMol(ref, tmp) + self.assertAlmostEqual(score, 0.647, 3) + expected = Chem.MolFromMolBlock('''3hof_lig_DHC + RDKit 3D + + 13 13 0 0 1 0 0 0 0 0999 V2000 + 13.8351 -36.1391 -27.1202 C 0 0 0 0 0 0 0 0 0 0 0 0 + 12.7314 -36.7492 -27.5199 O 0 0 0 0 0 0 0 0 0 0 0 0 + 13.8607 -35.4455 -25.8495 C 0 0 0 0 0 0 0 0 0 0 0 0 + 14.3613 -36.2184 -24.9028 C 0 0 0 0 0 0 0 0 0 0 0 0 + 14.4913 -35.7352 -23.5285 C 0 0 0 0 0 0 0 0 0 0 0 0 + 14.5939 -34.3755 -23.2705 C 0 0 0 0 0 0 0 0 0 0 0 0 + 14.7220 -33.9730 -21.9418 C 0 0 0 0 0 0 0 0 0 0 0 0 + 14.7341 -34.9830 -20.8422 C 0 0 0 0 0 0 0 0 0 0 0 0 + 14.6219 -36.3168 -21.1765 C 0 0 0 0 0 0 0 0 0 0 0 0 + 14.5069 -36.6821 -22.5117 C 0 0 0 0 0 0 0 0 0 0 0 0 + 14.8399 -34.6151 -19.5241 O 0 0 0 0 0 0 0 0 0 0 0 0 + 14.8305 -32.6610 -21.6569 O 0 0 0 0 0 0 0 0 0 0 0 0 + 14.8316 -36.1976 -27.8063 O 0 0 0 0 0 0 0 0 0 0 0 0 + 1 2 2 0 + 1 3 1 0 + 1 13 1 0 + 3 4 2 0 + 4 5 1 0 + 5 6 2 0 + 5 10 1 0 + 6 7 1 0 + 7 8 2 0 + 7 12 1 0 + 8 9 1 0 + 8 11 1 0 + 9 10 2 0 +M CHG 1 13 -1 +M END +''') + ssd = 0.0 + probeConf = probe.GetConformer() + expectedConf = expected.GetConformer() + for i in range(probeConf.GetNumAtoms()): + delt = probeConf.GetAtomPosition(i) - expectedConf.GetAtomPosition( + i) + ssd += delt.LengthSq() + self.assertGreater(ssd, 100) + ssd = 0.0 + probeConf = tmp.GetConformer() + expectedConf = expected.GetConformer() + for i in range(probeConf.GetNumAtoms()): + delt = probeConf.GetAtomPosition(i) - expectedConf.GetAtomPosition( + i) + ssd += delt.LengthSq() + self.assertAlmostEqual(ssd, 0, 3) +","Python" +"In Silico","gear-genomics/silica","server/server.py",".py","9156","194","#! /usr/bin/env python + +import os +import errno +import uuid +import re +import subprocess +import argparse +import json +import gzip +from subprocess import call +from flask import Flask, send_file, flash, send_from_directory, request, redirect, url_for, jsonify +from flask_cors import CORS +from werkzeug.utils import secure_filename + +app = Flask(__name__) +CORS(app) +SILICAWS = os.path.dirname(os.path.abspath(__file__)) + +app.config['SILICA'] = os.path.join(SILICAWS, "".."") +app.config['UPLOAD_FOLDER'] = os.path.join(app.config['SILICA'], ""data"") +app.config['MAX_CONTENT_LENGTH'] = 8 * 1024 * 1024 #maximum of 8MB + + +def allowed_file(filename): + return '.' in filename and filename.rsplit('.', 1)[1].lower() in set(['fasta', 'fa', 'json', 'csv', 'txt']) + + +uuid_re = re.compile(r'(^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})-{0,1}([ap]{0,1})([cj]{0,1})$') +def is_valid_uuid(s): + return uuid_re.match(s) is not None + + +@app.route('/api/v1/upload', methods=['POST']) +def generate(): + uuidstr = str(uuid.uuid4()) + + # Get subfolder + sf = os.path.join(app.config['UPLOAD_FOLDER'], uuidstr[0:2]) + if not os.path.exists(sf): + os.makedirs(sf) + + # Fasta file + primerData = request.form['fastaText'] + primerData = primerData.replace('\r\n','\n') + if primerData == '': + return jsonify(errors = [{""title"": ""Please provide a set of primers!""}]), 400 + ffaname = os.path.join(sf, ""silica_"" + uuidstr + ""_fasta.fa"") + with open(ffaname, ""w"") as primFile: + primFile.write(primerData) + + # Genome + val = request.form.get(""submit"", ""None provided"") + genome = request.form['genome'] + if genome == '': + return jsonify(errors = [{""title"": ""Please select a genome!""}]), 400 + genome = os.path.join(app.config['SILICA'], ""fm"", genome) + + # Run silica + outfile = os.path.join(sf, ""silica_"" + uuidstr + "".json.gz"") + paramfile = os.path.join(sf, ""silica_"" + uuidstr + ""_parameter.txt"") + logfile = os.path.join(sf, ""silica_"" + uuidstr + "".log"") + errfile = os.path.join(sf, ""silica_"" + uuidstr + "".err"") + with open(logfile, ""w"") as log: + with open(errfile, ""w"") as err: + with open(paramfile, ""w"") as param: + param.write(""genome="" + genome + '\n') + setAmpSize = onlyInt(request.form['setAmpSize']) + param.write(""maxProdSize="" + setAmpSize + '\n') + setTmCutoff = onlyFloat(request.form['setTmCutoff']) + param.write(""cutTemp="" + setTmCutoff + '\n') + if float(setTmCutoff) < 30.0: + return jsonify(errors = [{""title"": ""Mimnimal Primer Tm must be >= 30°C""}]), 400 + setKmer = onlyInt(request.form['setKmer']) + param.write(""kmer="" + setKmer + '\n') + if int(setKmer) < 15: + return jsonify(errors = [{""title"": ""Number of bp Used to Seach for Matches must be > 14 bp""}]), 400 + setEDis = onlyInt(request.form['setDist']) + param.write(""distance="" + setEDis + '\n') + if int(setEDis) != 0 and int(setEDis) != 1: + return jsonify(errors = [{""title"": ""Maximal Allowed Number of Mutations must be 0 or 1""}]), 400 + setCutoffPen = onlyFloat(request.form['setCutoffPen']) + param.write(""cutoffPenalty="" + setCutoffPen + '\n') + if float(setCutoffPen) < 0.0 and int(setCutoffPen) != -1: + return jsonify(errors = [{""title"": ""Keep Only PCR Products with Penalty Below must be > 0.0 or -1""}]), 400 + setPenTmDiff = onlyFloat(request.form['setPenTmDiff']) + param.write(""penaltyTmDiff="" + setPenTmDiff + '\n') + if float(setPenTmDiff) < 0.0: + return jsonify(errors = [{""title"": ""Penalty Factor for Single Primer Tm Mismatch must be >= 0.0""}]), 400 + setPenTmMismatch = onlyFloat(request.form['setPenTmMismatch']) + param.write(""penaltyTmMismatch="" + setPenTmMismatch + '\n') + if float(setPenTmMismatch) < 0.0: + return jsonify(errors = [{""title"": ""Penalty Factor for Tm Mismatch of Primers in a Pair must be >= 0.0""}]), 400 + setPenLength = onlyFloat(request.form['setPenLength']) + param.write(""penaltyLength="" + setPenLength + '\n') + if float(setPenLength) < 0.0: + return jsonify(errors = [{""title"": ""Penalty Factor for PCR Product Length must be >= 0.0""}]), 400 + setCtmMv = onlyFloat(request.form['setCtmMv']) + param.write(""monovalent="" + setCtmMv + '\n') + if float(setCtmMv) < 0.0: + return jsonify(errors = [{""title"": ""Concentration of Monovalent Ions must be >= 0.0 mMol""}]), 400 + setCtmDv = onlyFloat(request.form['setCtmDv']) + param.write(""divalent="" + setCtmDv + '\n') + if float(setCtmDv) < 0.0: + return jsonify(errors = [{""title"": ""Concentration of Divalent Ions must be >= 0.0 mMol""}]), 400 + setCtmDNA = onlyFloat(request.form['setCtmDNA']) + param.write(""dna="" + setCtmDNA + '\n') + if float(setCtmDNA) < 0.1: + return jsonify(errors = [{""title"": ""Concentration of Annealing(!) Oligos must be >= 0.1 nMol""}]), 400 + setCtmDNTP = onlyFloat(request.form['setCtmDNTP']) + param.write(""dntp="" + setCtmDNTP + '\n') + if float(setCtmDNTP) < 0.0: + return jsonify(errors = [{""title"": ""Concentration of the Sum of All dNTPs must be >= 0.0 mMol""}]), 400 + + try: + return_code = call(['dicey', 'search', '-g', genome, '-o', outfile, '-i', os.path.join(SILICAWS, ""../primer3_config/""), + '--maxProdSize', setAmpSize, '--cutTemp', setTmCutoff, + '--kmer', setKmer, '--distance', setEDis, + '--cutoffPenalty', setCutoffPen, '--penaltyTmDiff', setPenTmDiff, + '--penaltyTmMismatch', setPenTmMismatch, '--penaltyLength', setPenLength, + '--monovalent', setCtmMv, '--divalent', setCtmDv, + '--dna', setCtmDNA, '--dntp', setCtmDNTP, + ffaname], stdout=log, stderr=err) + except OSError as e: + if e.errno == errno.ENOENT: + return jsonify(errors = [{""title"": ""Binary dicey not found!""}]), 400 + else: + return jsonify(errors = [{""title"": ""OSError "" + str(e.errno) + "" running binary dicey!""}]), 400 + result = gzip.open(outfile).read() + if result is None: + datajs = [] + datajs[""errors""] = [] + else: + datajs = json.loads(result) + datajs['uuid'] = uuidstr + with open(errfile, ""r"") as err: + errInfo = "": "" + err.read() + if len(errInfo) > 3 or return_code != 0: + if len(errInfo) > 3: + datajs[""errors""] = [{""title"": ""Error in running silica"" + errInfo}] + datajs[""errors""] + if return_code != 0: + datajs[""errors""] = [{""title"": ""Run Error - Dicey did not return 0""}] + datajs[""errors""] + return jsonify(datajs), 400 + return jsonify(datajs), 200 + + +@app.route('/api/v1/results/', methods = ['GET', 'POST']) +def results(uuid): + if is_valid_uuid(uuid): + sf = os.path.join(app.config['UPLOAD_FOLDER'], uuid[0:2]) + if os.path.exists(sf): + sjsfilename = ""silica_"" + uuid + "".json.gz"" + if os.path.isfile(os.path.join(sf, sjsfilename)): + result = gzip.open(os.path.join(sf, sjsfilename)).read() + if result is None: + datajs = [] + datajs[""errors""] = [] + else: + datajs = json.loads(result) + datajs['uuid'] = uuid + with open(os.path.join(sf, ""silica_"" + uuid + "".err""), ""r"") as err: + errInfo = "": "" + err.read() + if len(errInfo) > 3: + datajs[""errors""] = [{""title"": ""Error in running silica"" + errInfo}] + datajs[""errors""] + return jsonify(datajs), 400 + return jsonify(datajs), 200 + return jsonify(errors = [{""title"": ""Link outdated or invalid!""}]), 400 + + +@app.route('/api/v1/genomeindex', methods=['POST']) +def genomeind(): + return send_from_directory(os.path.join(SILICAWS, ""../fm""),""genomeindexindex.json""), 200 + + +@app.route('/api/v1/health', methods=['GET']) +def health(): + return jsonify(status=""OK"") + + +def onlyFloat(txt): + onlyNumbDC = re.compile(r'[^0-9,.\-]') + txt = onlyNumbDC.sub( '', txt) + txt = txt.replace(',', '.') + return txt + + +def onlyInt(txt): + onlyNumb = re.compile(r'[^0-9\-]') + return onlyNumb.sub( '', txt) + + +if __name__ == '__main__': + app.run(host = '0.0.0.0', port=3300, debug = True, threaded=True) +","Python" +"In Silico","baoilleach/pharao","include/mainWar.h",".h","962","42","/******************************************************************************* +mainWar.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_MAINWAR_H__ +#define __SILICOS_PHARAO_MAINWAR_H__ + + + + +// General +#include +#include + +// OpenBabel + +// Pharao + + + +void mainWar(const std::string&); + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/pharMerger.h",".h","1158","55","/******************************************************************************* +pharMerger.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_PHARMERGER_H__ +#define __SILICOS_PHARAO_PHARMERGER_H__ + + + +// General +#include +#include + +// OpenBabel + +// Pharao +#include ""pharmacophore.h"" +#include ""utilities.h"" + + + +class PharMerger +{ + private: + + double _deltaSigma; + double _threshold; + + public: + + PharMerger(); + + void merge(Pharmacophore& phar); + }; + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/chargeFuncCalc.h",".h","1020","41","/******************************************************************************* +chargeFuncCalc.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_CHARGEFUNCCALC_H__ +#define __SILICOS_PHARAO_CHARGEFUNCCALC_H__ + + + +// General + +// OpenBabel +#include + +// Pharao +#include ""pharmacophore.h"" + + + +void chargeFuncCalc(OpenBabel::OBMol*, Pharmacophore*); + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/pharmacophore.h",".h","3712","171","/******************************************************************************* +pharmacophore.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_PHARMACOPHORE_H__ +#define __SILICOS_PHARAO_PHARMACOPHORE_H__ + + + +// General +#include +#include +#include +#include +#include +#include +#include + +// OpenBabel + +// Pharao +#include +#include +#include +#include + +#ifndef GCI +#define GCI 2.828427125 +#endif + +#ifndef GCI2 +#define GCI2 7.999999999 +#endif + +#ifndef PI +#define PI 3.14159265 +#endif + + + +enum FuncGroup +{ + AROM, ///< Aromatic ringsystem, calculated by the AromFuncCalc class + HDON, ///< Hydrogen donor, calculated by the HDonFuncCalc class + HACC, ///< Hydrogen acceptor, calculated by the HAccFuncCalc class + LIPO, ///< Lipophilicity, calculated by the LipoFuncCalc class + POSC, ///< Positive charge, calculated by the ChargeFuncCalc class + NEGC, ///< Negative charge, calculated by the ChargeFuncCalc class + HYBH, ///< Hybrid Type: HDON + HACC + HYBL, ///< Hybrid Type: AROM + LIPO + EXCL, ///< Exclusion sphere + UNDEF, ///< Undefined value (typically used for initialisation) +}; + + + +const std::string funcName[10] = +{ + ""SILICOS::PHARAO::AROM"", + ""SILICOS::PHARAO::HDON"", + ""SILICOS::PHARAO::HACC"", + ""SILICOS::PHARAO::LIPO"", + ""SILICOS::PHARAO::POSC"", + ""SILICOS::PHARAO::NEGC"", + ""SILICOS::PHARAO::HYBH"", + ""SILICOS::PHARAO::HYBL"", + ""SILICOS::PHARAO::EXCL"", + ""SILICOS::PHARAO::UNDEF"" +}; + + + +const bool funcHasNormal[10] = +{ + true, + true, + true, + false, + false, + false, + true, + true, + false, + false, +}; + + + +const double funcSigma[10] = +{ + 0.7, // AROM + 1.0, // HDON + 1.0, // HACC + 0.7, // LIPO + 1.0, // POSC + 1.0, // NEGC + 1.0, // HYBH + 0.7, // HYBL + 1.6, // EXCL + 1.0, // UNDEF +}; + + + +class PharmacophorePoint +{ + public: + + Coordinate point; ///< coordinates of the pharmacophore point + FuncGroup func; ///< type of functional group + Coordinate normal; ///< coordinates of the directionality of the pharmacophore + double alpha; ///< spread of the gaussian is inverse proportional to radius squared + bool hasNormal; ///< does the pharmacophore point has directionality + + PharmacophorePoint(void); + PharmacophorePoint(const PharmacophorePoint&); + PharmacophorePoint(const PharmacophorePoint*); +}; + + + +typedef std::vector Pharmacophore; +typedef std::multimap PharmacophoreMap; + + + +class PharmacophoreReader +{ + private: + + void _skipPharmacophore(std::ifstream*); + + public: + + PharmacophoreReader(void); + ~PharmacophoreReader(void); + + Pharmacophore read(std::ifstream*, std::string&); +}; + + + +class PharmacophoreWriter +{ + public: + + PharmacophoreWriter(void); + ~PharmacophoreWriter(void); + + void write(Pharmacophore&, std::ofstream*, const std::string&); +}; + + + +#endif","Unknown" +"In Silico","baoilleach/pharao","include/logOut.h",".h","1029","44","/******************************************************************************* +logOut.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_LOGOUT_H__ +#define __SILICOS_PHARAO_LOGOUT_H__ + + + +// General +#include +#include + +// OpenBabel +#include + +// Pharao +#include ""options.h"" +#include ""result.h"" + + + +void logOut(Result*, Options&); + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/pharaoConfig.h",".h","78","4","#define PHARAO_VERSION 3 +#define PHARAO_RELEASE 0 +#define PHARAO_SUBRELEASE 3 +","Unknown" +"In Silico","baoilleach/pharao","include/rankType.h",".h","916","36","/******************************************************************************* +rankType.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_RANKTYPE_H__ +#define __SILICOS_PHARAO_RANKTYPE_H__ + + + +enum RankType +{ + TANIMOTO, + TVERSKY_REF, + TVERSKY_DB +}; + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/solutionInfo.h",".h","1267","55","/******************************************************************************* +solutionInfo.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_SOLUTIONINFO_H__ +#define __SILICOS_PHARAO_SOLUTIONINFO_H__ + + + +// General + +// OpenBabel + +// Pharao +#include ""coordinate.h"" +#include ""siMath.h"" + + + +class SolutionInfo +{ + public: + + SiMath::Vector rotor; + double volume; + unsigned int iterations; + Coordinate center1; + Coordinate center2; + SiMath::Matrix rotation1; + SiMath::Matrix rotation2; + + SolutionInfo(void); + ~SolutionInfo(void); +}; + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/functionMapping.h",".h","1594","64","/******************************************************************************* +functionMapping.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_FUNCTIONMAPPING_H__ +#define __SILICOS_PHARAO_FUNCTIONMAPPING_H__ + + + +// General +#include +#include + +// OpenBabel + +// Pharao +#include ""pharmacophore.h"" +#include ""utilities.h"" + + + +class FunctionMapping +{ + public: + + FunctionMapping(Pharmacophore*, Pharmacophore*, double); + ~FunctionMapping(void); + + PharmacophoreMap getNextMap(void); + + private: + + bool _hasNext; + unsigned int _maxLevel; + double _epsilon; + + Pharmacophore* _ref; ///< Pointer to reference pharmacophore + Pharmacophore* _db; ///< Pointer to database pharmacophore + + std::vector _refIndex; + std::vector _dbIndex; + std::map > *> _matchMap; +}; + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/options.h",".h","2922","91","/******************************************************************************* +options.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_OPTIONS_H__ +#define __SILICOS_PHARAO_OPTIONS_H__ + + + +// General +#include +#include +#include +#include + +// OpenBabel +#include ""openbabel/obconversion.h"" + +// Pharao +#include ""fileType.h"" +#include ""rankType.h"" +#include ""pharmacophore.h"" + + + +class Options +{ + public: + + std::string refInpFile; // -r --reference + FileType refInpType; // --refType + std::ifstream* refInpStream; + + std::string dbInpFile; // -d --dbase + FileType dbInpType; // --dbType + std::ifstream* dbInpStream; + + std::string pharmOutFile; // -p --pharmacophore + std::ofstream* pharmOutStream; + PharmacophoreWriter* pharmOutWriter; + + std::string molOutFile; // -o --out + std::ofstream* molOutStream; + OpenBabel::OBConversion* molOutWriter; + + std::string scoreOutFile; // -s --scores + std::ofstream* scoreOutStream; + + double cutOff; // --cutOff + int best; // --best + RankType rankby; // --rankby + bool singleConf; // --singleConf + + std::vector funcGroupVec; // -f --funcGroup + bool noHybrid; // --noHybrid + double epsilon; // -e --epsilon + bool withExclusion; // --withExclusion + bool merge; // -m --merge + bool noNormal; // -n --noNormal + bool scoreOnly; // --scoreOnly + + bool isQuiet; // -q --quiet + bool version; // -v --version + bool help; // -h --help + + Options(void); + ~Options(void); + + std::string print(void) const; +}; + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/printProgress.h",".h","952","40","/******************************************************************************* +printProgress.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_PRINTPROGRESS_H__ +#define __SILICOS_PHARAO_PRINTPROGRESS_H__ + + + +// General +#include + +// OpenBabel + +// Pharao + + + +void printProgress(int); + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/compScore.h",".h","1000","44","/******************************************************************************* +compScore.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_COMPSCORE_H__ +#define __SILICOS_PHARAO_COMPSCORE_H__ + + + +// General + +// OpenBabel + +// Pharao +#include ""result.h"" + + + +class CompScore +{ + public: + bool operator()(const Result*, const Result*); +}; + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/utilities.h",".h","2202","79","/******************************************************************************* +utilities.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_UTILITIES_H__ +#define __SILICOS_PHARAO_UTILITIES_H__ + + + +// General + +// OpenBabel +#include ""openbabel/mol.h"" + +// Pharao +#include ""coordinate.h"" +#include ""pharmacophore.h"" +#include ""siMath.h"" +#include ""solutionInfo.h"" + +#ifndef GCI +#define GCI 2.828427125 +#endif + +#ifndef GCI2 +#define GCI2 7.999999999 +#endif + +#ifndef PI +#define PI 3.14159265 +#endif + + + +Coordinate translate(Coordinate& p, Coordinate& t); +Coordinate rotate(Coordinate& p, SiMath::Matrix& R); +void normalise(Coordinate & p); +double norm(Coordinate & p); +double dotProduct(Coordinate& p1, Coordinate& p2) ; +Coordinate crossProduct(Coordinate& p1, Coordinate& p2); +double cosine(Coordinate& p1, Coordinate& p2); +double distance(Coordinate& p1, Coordinate& p2); + +void normalise(SiMath::Vector& v); + +SiMath::Matrix quat2Rotation(SiMath::Vector& Q); + +void inverseHessian(SiMath::Matrix& H); + +double VolumeOverlap(PharmacophorePoint& p1, PharmacophorePoint& p2, bool n); +double VolumeOverlap(PharmacophorePoint* p1, PharmacophorePoint* p2, bool n); + +void TransformPharmacophore(Pharmacophore& pharm, SiMath::Matrix& U, Coordinate& center1, Coordinate& center2); +void positionPharmacophore(Pharmacophore& pharm, SiMath::Matrix& U, SolutionInfo& s); + +void TransformMolecule(OpenBabel::OBMol* m, SiMath::Matrix& U, Coordinate& center1, Coordinate& center2); +void positionMolecule(OpenBabel::OBMol* m, SiMath::Matrix& U, SolutionInfo& s); + + + +#endif + +","Unknown" +"In Silico","baoilleach/pharao","include/mainErr.h",".h","982","43","/******************************************************************************* +mainErr.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_MAINERR_H__ +#define __SILICOS_PHARAO_MAINERR_H__ + + + + +// General +#include +#include +#include + +// OpenBabel + +// Pharao + + + +void mainErr(const std::string&); + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/calcPharm.h",".h","1194","49","/******************************************************************************* +calcPharm.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_CALCPHARM_H__ +#define __SILICOS_PHARAO_CALCPHARM_H__ + + + +// General + +// OpenBabel +#include ""openbabel/mol.h"" + +// Pharao +#include ""pharmacophore.h"" +#include ""options.h"" +#include ""aromFuncCalc.h"" +#include ""chargeFuncCalc.h"" +#include ""hAccFuncCalc.h"" +#include ""hDonFuncCalc.h"" +#include ""lipoFuncCalc.h"" +#include ""hybridCalc.h"" + + + +void calcPharm(OpenBabel::OBMol*, Pharmacophore*, const Options&); + + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/printInfo.h",".h","1015","43","/******************************************************************************* +printInfo.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_PRINTINFO_H__ +#define __SILICOS_PHARAO_PRINTINFO_H__ + + + +// General +#include +#include +#include + +// OpenBabel + +// Pharao +#include ""printHeader.h"" + + + +void printInfo(const std::string&); + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/stringTokenizer.h",".h","1028","41","/******************************************************************************* +stringTokenizer.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_STRINGTOKENIZER_H__ +#define __SILICOS_PHARAO_STRINGTOKENIZER_H__ + + + +// General +#include +#include + +// OpenBabel + +// Pharao + + + +std::list stringTokenizer(const std::string&, const std::string&); + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/logPharmacophores.h",".h","1003","41","/******************************************************************************* +logPharmacophores.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_LOGPHARMACOPHORES_H__ +#define __SILICOS_PHARAO_LOGPHARMACOPHORES_H__ + + + +// General + +// OpenBabel + +// Pharao +#include ""result.h"" +#include ""options.h"" + + + +void logPharmacophores(Result*, Options&); + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/hAccFuncCalc.h",".h","1713","70","/******************************************************************************* +hAccFuncCalc.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_HACCFUNCCALC_H__ +#define __SILICOS_PHARAO_HACCFUNCCALC_H__ + + + +// General +#include +#include + +// OpenBabel +#include +#include +#include +#include + +// Pharao +#include ""pharmacophore.h"" + + + +#ifndef ROUND +#define ROUND(x) ((int) ((x) + 0.5)) +#endif + +#ifndef H_BOND_DIST +#define H_BOND_DIST 1.8 +#endif + +#ifndef H_RADIUS +#define H_RADIUS 1.2 +#endif + +#ifndef DENSITY +#define DENSITY 2.0 +#endif + +#ifndef PI +#define PI 3.14159265 +#endif + + + +void hAccFuncCalc(OpenBabel::OBMol*, Pharmacophore*); +double _hAccCalcAccSurf(OpenBabel::OBAtom*); +std::list _hAccGetNeighbors(OpenBabel::OBAtom*); +Coordinate _hAccCalcNormal(OpenBabel::OBAtom*); +bool _hAccDelocalized(OpenBabel::OBAtom*); + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/printHeader.h",".h","1007","42","/******************************************************************************* +printHeader.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_PRINTHEADER_H__ +#define __SILICOS_PHARAO_PRINTHEADER_H__ + + + +// General +#include + +// OpenBabel +#include + +// Pharao +#include ""pharaoConfig.h"" + + + +void printHeader(void); + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/lipoFuncCalc.h",".h","1898","83","/******************************************************************************* +lipoFuncCalc.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_LIPOFUNCCALC_H__ +#define __SILICOS_PHARAO_LIPOFUNCCALC_H__ + + + +// General +#include +#include + +// OpenBabel +#include ""openbabel/mol.h"" +#include ""openbabel/atom.h"" +#include ""openbabel/bond.h"" +#include ""openbabel/ring.h"" + +// Pharao +#include ""pharmacophore.h"" + + + + + +#ifndef ROUND +#define ROUND(x) ((int) ((x) + 0.5)) +#endif + +#ifndef H_BOND_DIST +#define H_BOND_DIST 1.8 +#endif + +#ifndef H_RADIUS +#define H_RADIUS 1.2 +#endif + +#ifndef DENSITY +#define DENSITY 1.5 +#endif + +#ifndef PI +#define PI 3.14159265 +#endif + +#ifndef PROBE_RADIUS +#define PROBE_RADIUS 1.4 +#endif + +#ifndef REF_LIPO +#define REF_LIPO 9.87 +#endif + + + + +void lipoFuncCalc(OpenBabel::OBMol*, Pharmacophore*); +void _lipoLabelAtoms(OpenBabel::OBMol*); +double _lipoCalcAccSurf(OpenBabel::OBAtom*); +void _lipoGroupAtoms(OpenBabel::OBMol*, Pharmacophore*); +std::list _lipoGetNeighbors(OpenBabel::OBAtom*); +void _lipoLabelNeighbors(OpenBabel::OBAtom*, double); + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/result.h",".h","2268","66","/******************************************************************************* +result.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_RESULT_H__ +#define __SILICOS_PHARAO_RESULT_H__ + + + +// General +#include +#include + +// OpenBabel +#include + +// Pharao +#include ""pharmacophore.h"" +#include ""solutionInfo.h"" + + + +class Result +{ + public: + + std::string refId; // id of the reference pharmacophore + double refVolume; // volume of the reference pharmacophore + std::string dbId; // id of the database pharmacophore + double dbVolume; // volume of the database pharmacophore + double overlapVolume; // volume overlap between reference and database pharmacophore + double exclVolume; // volume overlap between database pharmacophore and exclusion spheres + int resPharSize; // number of points in the resulting pharmacophore + + double tanimoto; // resulting score = info.volume/(refVolume+resVolume-info.volume) + double tversky_ref; // info.volume/refVolume + double tversky_db; // info.volume/dbVolume + double rankbyScore; // one of the three scores... + + SolutionInfo info; // information about the alignment + OpenBabel::OBMol resMol; // resulting molecule + Pharmacophore resPhar; // overlapping pharmacophore + + Result(void); +}; + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/logScores.h",".h","1010","43","/******************************************************************************* +logScores.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_LOGSCORES_H__ +#define __SILICOS_PHARAO_LOGSCORES_H__ + + + +// General +#include +#include + +// OpenBabel + +// Pharao +#include ""result.h"" +#include ""options.h"" + + + +void logScores(Result*, Options&); + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/coordinate.h",".h","1140","54","/******************************************************************************* +coordinate.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_COORDINATE_H__ +#define __SILICOS_PHARAO_COORDINATE_H__ + + + +// General +#include + +// OpenBabel + +// Pharao + + + +class Coordinate +{ + public: + + double x; + double y; + double z; + + Coordinate(void); + Coordinate(double, double, double); +}; + + + +std::ostream& operator<< (std::ostream&, const Coordinate&); + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/printUsage.h",".h","967","41","/******************************************************************************* +printUsage.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_PRINTUSAGE_H__ +#define __SILICOS_PHARAO_PRINTUSAGE_H__ + + + +// General +#include + +// OpenBabel + +// Pharao +#include ""printHeader.h"" + + + +void printUsage(void); + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/addBest.h",".h","1015","42","/******************************************************************************* +addBest.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_ADDBEST_H__ +#define __SILICOS_PHARAO_ADDBEST_H__ + + + +// General + +// OpenBabel + +// Pharao +#include +#include +#include + + + +void addBest(Result&, const Options&, std::vector&); + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/siMath.h",".h","8905","252","/******************************************************************************* +siMath.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_SIMATH_H__ +#define __SILICOS_PHARAO_SIMATH_H__ + + + +// General +#include +#include + +// OpenBabel + +// Pharao +#ifndef INF +#define INF HUGE_VAL +#endif + +#ifndef PI +#define PI 3.14159265358979323846 +#endif + +#ifndef TAU +#define TAU 1e-12 +#endif + +#ifndef min + template inline T min(T x,T y) { return (x inline T max(T x,T y) { return (x>y)?x:y; } +#endif + +#ifndef sign + template inline T sign(const T & a, const T & b ) {return (b >= 0.0) ? ( a>=0 ? a : -a) : (a>=0 ? -a : a);} +#endif sign + + + + +namespace SiMath +{ + + + + +inline double triangle(const double & a, const double & b ) +{ + double A(fabs(a)), B(fabs(b)); + if ( A > B ) + { + return A * sqrt(1.0 + (B/A)*(B/A)); + } + else if ( B == 0 ) + { + return 0; + } + return B * sqrt(1.0 + (A/B)*(A/B)); +} + + + +class Vector +{ + private: + unsigned int _n; ///< Number of data points in vector + std::vector _pVector; ///< std::vector to hold all values + + public: + Vector() : _n(0), _pVector(0) {}; ///< Empty vector + Vector(const unsigned int n) : _n(n), _pVector(n) {}; ///< vector of length n, no initial value + Vector(const unsigned int n, const double& v) : _n(n), _pVector(n, v) {}; ///< vector of length n, initial constant value v + Vector(const unsigned int n, const double*); ///< Copy of data stored in an array double[n] + Vector(const std::vector&); ///< Copy of data stored in std::vector + + Vector(const Vector&); + + ~Vector(); + + void clear(); + void reset(unsigned int); + + void resize(unsigned int); + + double getValueAt(const unsigned int); + double getValueAt(const unsigned int) const; + + double max() const; + double max(unsigned int&) const; + double min() const; + double min(unsigned int&) const; + double sum() const; + double mean() const; + double stDev() const; + double stDev(double m) const; + unsigned int size() const { return _n; }; + + Vector & operator= (const Vector&); ///< copy assignment, resets the size of the Vector if needed + Vector & operator= (const double&); ///< set all elements in Vector to constant value + Vector & operator+= (const double&); ///< add constant value to all elements in Vector + Vector & operator+= (const Vector&); ///< add full Vector element-wise + Vector & operator-= (const double&); ///< subtract constant value to all elements in Vector + Vector & operator-= (const Vector&); ///< subtract full Vector element-wise + Vector & operator*= (const double&); ///< multiply all elements with a constant value + Vector & operator*= (const Vector&); ///< multiply full Vector element-wise + Vector & operator/= (const double&); ///< divide all elements with a constant value + Vector & operator/= (const Vector&); ///< divide full Vector element-wise + Vector & operator- (); ///< change sign of all elements in Vector + Vector operator+ (const Vector&) const; ///< operator to write C = A + B + Vector operator- (const Vector&) const; ///< operator to write C = A - B + Vector operator* (const Vector&) const; ///< operator to write C = A * B + Vector operator/ (const Vector&) const; ///< operator to write C = A / B + + bool operator== (const Vector&) const; ///< check if two vectors are the same, which is only true if all elements are the same + bool operator!= (const Vector&) const; ///< check if two vectors are different + + inline double & operator[] (const unsigned int i) { return _pVector[i];}; ///< set i-th element from vector + inline double operator[] (const unsigned int i) const { return _pVector[i];}; ///< get i-th element from vector (const implementation) + + void swap(const unsigned int, const unsigned int); + + double dotProd(const Vector&); + + const double * getArrayPointer() const { return &(_pVector[0]); }; ///< direct access to the data + double * getArrayPointer() { return &(_pVector[0]); }; ///< direct access to the data +}; + + + +class Matrix +{ + private: + unsigned int _nRows; + unsigned int _nCols; + double** _pMatrix; + + public: + Matrix() : _nRows(0), _nCols(0), _pMatrix(NULL) {}; + Matrix(const unsigned int, const unsigned int); + Matrix(const unsigned int, const unsigned int, const double&); + Matrix(const Matrix&); + + Matrix(const unsigned int, const unsigned int, const Vector&); + + ~Matrix(); + + void reset (const unsigned int, const unsigned int); + void clear(); + + inline unsigned int nbrRows() const { return _nRows;}; + inline unsigned int nbrColumns() const { return _nCols;}; + + double getValueAt(const unsigned int, const unsigned int); + const double getValueAt(const unsigned int, const unsigned int) const; + Vector getRow(const unsigned int) const; + Vector getColumn(const unsigned int) const; + + void setValueAt(const unsigned int, const unsigned int, double); + void setRow(const unsigned int, Vector&); + void setColumn(const unsigned int, Vector&); + + void swapRows(unsigned int, unsigned int); + void swapColumns(unsigned int, unsigned int); + Matrix transpose(void); + + + Matrix & operator= (const Matrix&); ///< copy assignment, resets the size of the matrix if needed + Matrix & operator= (const double&); ///< set all elements in matrix to constant value + Matrix & operator+= (const double&); ///< add constant value to all elements in matrix + Matrix & operator+= (const Matrix&); ///< add full matrix element-wise + Matrix & operator-= (const double&); ///< subtract constant value from all elements in matrix + Matrix & operator-= (const Matrix&); ///< subtract full matrix element-wise + Matrix & operator*= (const double&); ///< multiply all elements with a constant value + Matrix & operator*= (const Matrix&); ///< multiply full matrix element-wise + Matrix & operator/= (const double&); ///< divide all elements with a constant value + Matrix & operator/= (const Matrix&); ///< divide full matrix element-wise + Matrix & operator- (); ///< change sign of all elements in matrix + + Matrix operator+ (const Matrix&) const; ///< add two matrices element by element and store the result in a new matrix + Matrix operator- (const Matrix&) const; ///< substract two matrices element by element and store the result in a new matrix + Matrix operator* (const Matrix&) const; ///< multiply two matrices element by element and store the result in a new matrix + Matrix operator/ (const Matrix&) const; ///< divide two matrices element by element and store the result in a new matrix + + inline double * operator[] (const unsigned int i) { return _pMatrix[i]; }; + inline const double * operator[] (const unsigned int i) const { return _pMatrix[i]; }; +}; + + + +Vector rowProduct(const Matrix & A, const Vector & U); +Vector colProduct(const Vector & U, const Matrix & A); + + + +class SVD +{ + public: + + SVD(const Matrix&, bool bU = true, bool bV = true); + + Vector getSingularValues() {return _S;}; + Matrix getSingularMatrix(); + + Matrix getU() { return _U;}; + Matrix getV() { return _V;}; + + double norm2() { return _S[0];}; + + double cond() { return _S[0]/_S[_S.size()-1]; }; + + int rank(); + + private: + + int _m; ///< number of rows + int _n; ///< number of columns + Matrix _U; ///< Left singular vectors + Matrix _V; ///< Right singular vectors + Vector _S; ///< Singular values + + bool _computeV; ///< Check if V should be computed + bool _computeU; ///< Check if U should be computed + + }; + + + +}; // end of namespace SiMath + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/aromFuncCalc.h",".h","1011","40","/******************************************************************************* +aromFuncCalc.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_AROMFUNCCALC_H__ +#define __SILICOS_PHARAO_AROMFUNCCALC_H__ + + + +// General + +// OpenBabel +#include + +// Pharao +#include ""pharmacophore.h"" + + + +void aromFuncCalc(OpenBabel::OBMol*, Pharmacophore*); + + + +#endif","Unknown" +"In Silico","baoilleach/pharao","include/hDonFuncCalc.h",".h","1527","72","/******************************************************************************* +hDonFuncCalc.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_HDONFUNCCALC_H__ +#define __SILICOS_PHARAO_HDONFUNCCALC_H__ + + + +// General +#include +#include + +// OpenBabel +#include +#include +#include + +// Pharao +#include ""pharmacophore.h"" + + + +#ifndef ROUND +#define ROUND(x) ((int) ((x) + 0.5)) +#endif + +#ifndef H_BOND_DIST +#define H_BOND_DIST 1.8 +#endif + +#ifndef H_RADIUS +#define H_RADIUS 1.2 +#endif + +#ifndef DENSITY +#define DENSITY 2.0 +#endif + +#ifndef PI +#define PI 3.14159265 +#endif + +#ifndef ACC_RADIUS +#define ACC_RADIUS 1.55 +#endif + + + +void hDonFuncCalc(OpenBabel::OBMol*, Pharmacophore*); +Coordinate _hDonCalcNormal(OpenBabel::OBAtom*); + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/getExt.h",".h","959","41","/******************************************************************************* +getExt.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_GETEXT_H__ +#define __SILICOS_PHARAO_GETEXT_H__ + + + +// General +#include + +// OpenBabel + +// Pharao +#include ""mainErr.h"" + + + +std::string getExt(std::string&); + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/alignment.h",".h","2373","78","/******************************************************************************* +alignment.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_ALIGNMENT_H__ +#define __SILICOS_PHARAO_ALIGNMENT_H__ + + + +// General +#include + +// OpenBabel + +// Pharao +#include ""siMath.h"" +#include ""solutionInfo.h"" +#include ""coordinate.h"" +#include ""pharmacophore.h"" +#include ""utilities.h"" + + + +class Alignment +{ + public: + + Alignment(PharmacophoreMap&); + ~Alignment(void); + + SolutionInfo align(bool n); + + private: + + std::vector _refMap; // holds translated points of the original reference points + std::vector _dbMap; // holds translated points of the original database points + + // coordinates of translation centers + Coordinate _refCenter; + Coordinate _dbCenter; + // initial axes of rotation + SiMath::Matrix _refRotMat; + SiMath::Matrix _dbRotMat; + + // local storage of reusable computational objects + std::vector _AkA; + SiMath::Vector _dCdq; // holds gradient update of normal computation + SiMath::Matrix _d2Cdq2; // holds hessian update of normal computation + SiMath::Vector _grad; + + unsigned int _nbrPoints; ///< counts the number of pharmacophore points + unsigned int _nbrExcl; ///< counts the number of exclusion sphere overlaps + + void _normalGradientMatrix(Coordinate& n1, Coordinate& n2, SiMath::Matrix & A); + double _quatVolumeOverlap(double alpha1, double alpha2, const SiMath::Vector& q, const SiMath::Matrix& A); + double _normalContribution(Coordinate& n1, Coordinate& n2, SiMath::Vector& q); +}; + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/hybridCalc.h",".h","1168","42","/******************************************************************************* +hybridCalc.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_HYBRIDCALC_H__ +#define __SILICOS_PHARAO_HYBRIDCALC_H__ + + + +// General + +// OpenBabel +#include + +// Pharao +#include ""coordinate.h"" +#include ""pharmacophore.h"" + + +void hybridCalc(OpenBabel::OBMol*, Pharmacophore*); +bool _hybridSameHybHPoint(const Coordinate&, const Coordinate&); +bool _hybridSameHybLPoint(const Coordinate&, const Coordinate&); + + + +#endif","Unknown" +"In Silico","baoilleach/pharao","include/parseCommandLine.h",".h","1265","55","/******************************************************************************* +parseCommandLine.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_PARSECOMMANDLINE_H__ +#define __SILICOS_PHARAO_PARSECOMMANDLINE_H__ + + + +// General +#include +#include +#include + +#ifdef WIN32 +#include ""getopt.h"" +#else +#include // For the getopt() function +#endif + +// OpenBabel + +// Pharao +#include ""options.h"" +#include ""printInfo.h"" +#include ""mainErr.h"" +#include ""stringTokenizer.h"" +#include ""pharmacophore.h"" +#include ""getExt.h"" + + + +void parseCommandLine(int argc, char* argv[], Options &o); + + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","include/fileType.h",".h","906","37","/******************************************************************************* +fileType.h - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#ifndef __SILICOS_PHARAO_FILETYPE_H__ +#define __SILICOS_PHARAO_FILETYPE_H__ + + + +enum FileType +{ + MOL, + PHAR, + GZIP, + UNKNOWN +}; + + + +#endif +","Unknown" +"In Silico","baoilleach/pharao","pymol/pharao.py",".py","9396","296","import tkFileDialog +import Pmw + +import pymol +from pymol.cgo import * +import os +import sys +import re + +#------------------------------------------------------------------------------# +# Create Pharao Menu # +#------------------------------------------------------------------------------# +def __init__(self): + self.menuBar.addmenuitem('Plugin', 'command', + 'Pharao visualization plugin', label = 'Pharao...', + command = lambda s=self: PharaoPlugin(s)) + + +class PharaoPlugin: + + #----------------------- + def __init__(self, app): + + print ""+++ SILICOS::PHARAO Pymol Plugin (2010) +++"" + self.phar = [] + #TODO store id for pharmacophore + + self.parent = app.root + self.dialog = Pmw.Dialog(self.parent, \ + buttons = ( \ + 'Create pharmacophore', + 'Read pharmacophore...', + 'Write pharmacophore...', + 'Create exclusion spheres', + 'Quit'), + title = 'Pharao Pymol plugin', + buttonboxpos = 'e', + command = self.execute) + + #---------------------- + def execute(self, opt): + if(opt=='Create pharmacophore'): + self.runPharao() + elif(opt=='Read pharmacophore...'): + self.readPharao() + elif(opt=='Write pharmacophore...'): + self.writePharao() + elif(opt=='Create exclusion spheres'): + self.createExcl() + else: + print ""+++ SILICOS::PHARAO Pymol Plugin (2010) +++"" + self.dialog.withdraw() + + #------------------ + def log(self, msg): + #TODO create label in widget + print "" * ""+msg + + #TODO method 'err' ? + +#------------------------------------------------------------------------------# +# Create Pharmacophore # +#------------------------------------------------------------------------------# + + def runPharao(self): + + #check if selection is made + if(not(""sele"" in pymol.cmd.get_names(""selections""))): + self.log(""ERROR: no selection 'sele' defined."") + sys.exit(1) + + #get object-id from selection + list = pymol.cmd.index(""sele"") + id = list[0][0] + for x in list: + if x[0]!=id: + self.log(""ERROR: multiple selection!"") + sys.exit(1) + + #add hydrogens and save in SDF format + pymol.cmd.h_add(""sele"") + pymol.cmd.save(""/tmp/_tmp_Pharao.pdb"", id) + pymol.cmd.remove(""hydrogens in ""+id) + + #run Pharao + os.system(""/usr/local/bin/pharao -d /tmp/_tmp_Pharao.pdb -p /tmp/_tmp_Pharao.phar"") + file = open(""/tmp/_tmp_Pharao.phar"") + + #display results + if file != None: + self.parseFile(file) + file.close() + else: + self.log(""ERROR: can't read Pharmacophore file."") + + # remove temporary files + os.system(""rm /tmp/_tmp_Pharao.pdb"") + os.system(""rm /tmp/_tmp_Pharao.phar"") + + self.log(""Done creating pharmacophore."") + + pymol.cmd.center() + pymol.cmd.zoom() + +#------------------------------------------------------------------------------# +# Read Pharmacophore # +#------------------------------------------------------------------------------# + + def readPharao(self): + + file = tkFileDialog.askopenfile(parent=self.parent, + mode='r', + filetypes=[('Pharmacophore', '*.phar')], + title='Open pharmacophore file') + if file != None: + self.parseFile(file) + file.close() + else: + self.log(""ERROR: can't read pharmacophore file."") + + self.log(""Done reading pharmacophore."") + + pymol.cmd.center() + pymol.cmd.zoom() + +#------------------------------------------------------------------------------# +# Create Exclusion Spheres # +#------------------------------------------------------------------------------# + + def createExcl(self): + + #check if selection is made + if(not(""sele"" in pymol.cmd.get_names(""selections""))): + self.log(""ERROR: no selection 'sele' defined."") + sys.exit(1) + + pymol.cmd.select(""_tmp_1_"", ""sele around 5 & !sele"") + + exclPoint = [ COLOR, 0.25, 0.25, 0.25 ] + + c = 0 + model = pymol.cmd.get_model(""_tmp_1_"") + for a in model.atom: + # add point to current phar + point = (""EXCL"", a.coord[0], a.coord[1], a.coord[2], 1.4, ""0"", 0.0, 0.0, 0.0) + self.phar.append(point) + + exclPoint.extend([ SPHERE, a.coord[0], a.coord[1], a.coord[2], 1.4]) + c = c + 1 + + if(len(exclPoint) != 0 ): + pymol.cmd.load_cgo(exclPoint,""excl"",1) + pymol.cmd.set('cgo_transparency',0.2,""excl"") + + pymol.cmd.delete(""_tmp_1_"") + self.log(""Done Creating ""+str(c)+"" exclusion spheres."") + + pymol.cmd.center() + pymol.cmd.zoom() + +#------------------------------------------------------------------------------# +# Write Pharmacophore # +#------------------------------------------------------------------------------# + + def writePharao(self): + + file = tkFileDialog.asksaveasfile(parent=self.parent, + filetypes=[('Pharmacophore', '*.phar')], + title='Save pharmacophore') + if file == None: + self.log(""ERROR: cannot save file."") + sys.exit(1) + + file.write('Generated_by_Pharao_Pymol_Plugin\n') + for p in self.phar: + if(p[5] != ""0""): + file.write(p[0]+'\t'+str(p[1])+'\t'+str(p[2])+'\t'+str(p[3])+'\t'+str(p[4])+'\t'+ + str(p[5])+'\t'+str(p[6])+'\t'+str(p[7])+'\t'+str(p[8])+'\n') + else: + file.write(p[0]+'\t'+str(p[1])+'\t'+str(p[2])+'\t'+str(p[3])+'\t'+str(p[4])+'\t'+ + str(p[5])+'\t'+""0.000""+'\t'+""0.000""+'\t'+""0.000""+'\n') + file.write('$$$$\n') + file.close() + + self.log(""Done writing pharmacophore."") + +#------------------------------------------------------------------------------# +# parse .phar file # +#------------------------------------------------------------------------------# + + def parseFile(self, file): + + # set colors + aromPoint = [ COLOR, 0.50, 0.85, 0.05 ] + lipoPoint = [ COLOR, 0.50, 0.10, 0.05 ] + hyblPoint = [ COLOR, 0.50, 0.50, 0.05 ] + hdonPoint = [ COLOR, 0.20, 0.65, 0.85 ] + haccPoint = [ COLOR, 0.80, 0.65, 0.85 ] + hybhPoint = [ COLOR, 0.50, 0.65, 0.85 ] + poscPoint = [ COLOR, 0.00, 0.00, 1.00 ] + negcPoint = [ COLOR, 1.00, 0.00, 0.00 ] + exclPoint = [ COLOR, 0.25, 0.25, 0.25 ] + normal = [] + + id = file.readline() + id = id.rstrip() + + #read pharmacophore points + for line in file: + if re.match(""\$"",line) == None: + strlist = line.split() + if len(strlist) >= 9: + x = float(strlist[1]) + y = float(strlist[2]) + z = float(strlist[3]) + sigma = 1.0/float(strlist[4]) + hasNormal = strlist[5] + if(re.match(""AROM"",strlist[0]) != None): + aromPoint.extend([SPHERE, x, y, z, sigma]) + + elif(re.match(""LIPO"",strlist[0]) != None ): + lipoPoint.extend([SPHERE, x, y, z, sigma]) + + elif(re.match(""HYBL"",strlist[0]) != None): + hyblPoint.extend([SPHERE, x, y, z, sigma]) + + elif(re.match(""HDON"",strlist[0]) != None): + hdonPoint.extend([SPHERE, x, y, z, sigma]) + + elif(re.match(""HACC"",strlist[0]) != None): + haccPoint.extend([SPHERE, x, y, z, sigma]) + + elif(re.match(""HYBH"",strlist[0]) != None): + hybhPoint.extend([SPHERE, x, y, z, sigma]) + + elif(re.match(""POSC"",strlist[0]) != None ): + poscPoint.extend([SPHERE, x, y, z, sigma]) + + elif(re.match(""NEGC"",strlist[0]) != None ): + negcPoint.extend([SPHERE, x, y, z, sigma]) + + elif(re.match(""EXCL"",strlist[0]) != None ): + exclPoint.extend([SPHERE, x, y, z, sigma]) + + else: + self.log(""WARNING: unknown point."") + + if(hasNormal == ""1""): + normal.extend( [ CYLINDER, + x, y, z, + float(strlist[6]), float(strlist[7]), float(strlist[8]), + 0.1, + 1.0, 1.0, 0.0, + 1.0, 1.0, 0.0 + ]) + point = (strlist[0], x, y, z, sigma, hasNormal, float(strlist[6]), float(strlist[7]), float(strlist[8])) + self.phar.append(point) + else: + point= (strlist[0], x, y, z, sigma, hasNormal, 0.0, 0.0, 0.0) + self.phar.append(point) + + else: + self.log(""pharmacophore file parsed correctly."") + + #load graphical objects into pymol + if ( len (normal) != 0 ): + pymol.cmd.load_cgo(normal,""normals_""+id,1) + pymol.cmd.set('cgo_transparency',0.0,""normals_""+id) + if ( len (aromPoint) >= 5 ): + pymol.cmd.load_cgo(aromPoint, ""arom_""+id,1) + pymol.cmd.set('cgo_transparency',0.4,""arom_""+id) + if ( len (lipoPoint) >=5 ): + pymol.cmd.load_cgo(lipoPoint, ""lipo_""+id,1) + pymol.cmd.set('cgo_transparency',0.4,""lipo_""+id) + if ( len (hyblPoint) >=5 ): + pymol.cmd.load_cgo(hyblPoint, ""hybl_""+id,1) + pymol.cmd.set('cgo_transparency',0.4,""hybl_""+id) + if ( len (hdonPoint) >= 5 ): + pymol.cmd.load_cgo(hdonPoint, ""hdon_""+id,1) + pymol.cmd.set('cgo_transparency',0.4,""hdon_""+id) + if ( len (haccPoint) >= 5 ): + pymol.cmd.load_cgo(haccPoint, ""hacc_""+id,1) + pymol.cmd.set('cgo_transparency',0.4,""hacc_""+id) + if ( len (hybhPoint) >= 5 ): + pymol.cmd.load_cgo(hybhPoint, ""hybh_""+id,1) + pymol.cmd.set('cgo_transparency',0.4,""hybh_""+id) + if ( len (poscPoint) >= 5 ): + pymol.cmd.load_cgo(poscPoint, ""posc_""+id,1) + pymol.cmd.set('cgo_transparency',0.4,""posc_""+id) + if ( len (negcPoint) >= 5 ): + pymol.cmd.load_cgo(negcPoint, ""negc_""+id,1) + pymol.cmd.set('cgo_transparency',0.4,""negc_""+id) + if ( len (exclPoint) >= 5 ): + pymol.cmd.load_cgo(exclPoint, ""excl_""+id,1) + pymol.cmd.set('cgo_transparency',0.2,""excl_""+id) +","Python" +"In Silico","baoilleach/pharao","src/solutionInfo.cpp",".cpp","1012","41","/******************************************************************************* +solutionInfo.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""solutionInfo.h"" + + + +SolutionInfo::SolutionInfo(void): + rotor(4,0.0), + volume(-999.99), + iterations(0), + center1(), + center2(), + rotation1(3,3,0.0), + rotation2(3,3,0.0) +{ +}; + + + +SolutionInfo::~SolutionInfo(void) +{ +}; +","C++" +"In Silico","baoilleach/pharao","src/coordinate.cpp",".cpp","1099","49","/******************************************************************************* +coordinate.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""coordinate.h"" + + + +Coordinate::Coordinate(void): + x(0.0), + y(0.0), + z(0.0) +{ +} + + + +Coordinate::Coordinate(double x, double y, double z): + x(x), + y(y), + z(z) +{ +}; + + + +std::ostream& +operator<< (std::ostream& os, const Coordinate& A) +{ + os << ""("" << A.x << "","" << A.y << "","" << A.z << "")""; + return os; +}; +","C++" +"In Silico","baoilleach/pharao","src/getopt.h",".h","6744","192","/* getopt.h */ +/* Declarations for getopt. + Copyright (C) 1989-1994, 1996-1999, 2001 Free Software + Foundation, Inc. This file is part of the GNU C Library. + + The GNU C Library is free software; you can redistribute + it and/or modify it under the terms of the GNU Lesser + General Public License as published by the Free Software + Foundation; either version 2.1 of the License, or + (at your option) any later version. + + The GNU C Library 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 Lesser General Public + License for more details. + + You should have received a copy of the GNU Lesser General + Public License along with the GNU C Library; if not, write + to the Free Software Foundation, Inc., 59 Temple Place, + Suite 330, Boston, MA 02111-1307 USA. */ + + + + + +#ifndef _GETOPT_H + +#ifndef __need_getopt +# define _GETOPT_H 1 +#endif + +/* If __GNU_LIBRARY__ is not already defined, either we are being used + standalone, or this is the first header included in the source file. + If we are being used with glibc, we need to include , but + that does not exist if we are standalone. So: if __GNU_LIBRARY__ is + not defined, include , which will pull in for us + if it's from glibc. (Why ctype.h? It's guaranteed to exist and it + doesn't flood the namespace with stuff the way some other headers do.) */ +#if !defined __GNU_LIBRARY__ +# include +#endif + +#ifdef __cplusplus +extern ""C"" { +#endif + +/* For communication from `getopt' to the caller. + When `getopt' finds an option that takes an argument, + the argument value is returned here. + Also, when `ordering' is RETURN_IN_ORDER, + each non-option ARGV-element is returned here. */ + +extern char *optarg; + +/* Index in ARGV of the next element to be scanned. + This is used for communication to and from the caller + and for communication between successive calls to `getopt'. + + On entry to `getopt', zero means this is the first call; initialize. + + When `getopt' returns -1, this is the index of the first of the + non-option elements that the caller should itself scan. + + Otherwise, `optind' communicates from one call to the next + how much of ARGV has been scanned so far. */ + +extern int optind; + +/* Callers store zero here to inhibit the error message `getopt' prints + for unrecognized options. */ + +extern int opterr; + +/* Set to an option character which was unrecognized. */ + +extern int optopt; + +#ifndef __need_getopt +/* Describe the long-named options requested by the application. + The LONG_OPTIONS argument to getopt_long or getopt_long_only is a vector + of `struct option' terminated by an element containing a name which is + zero. + + The field `has_arg' is: + no_argument (or 0) if the option does not take an argument, + required_argument (or 1) if the option requires an argument, + optional_argument (or 2) if the option takes an optional argument. + + If the field `flag' is not NULL, it points to a variable that is set + to the value given in the field `val' when the option is found, but + left unchanged if the option is not found. + + To have a long-named option do something other than set an `int' to + a compiled-in constant, such as set a value from `optarg', set the + option's `flag' field to zero and its `val' field to a nonzero + value (the equivalent single-letter option character, if there is + one). For long options that have a zero `flag' field, `getopt' + returns the contents of the `val' field. */ + +struct option +{ +# if (defined __STDC__ && __STDC__) || defined __cplusplus + const char *name; +# else + char *name; +# endif + /* has_arg can't be an enum because some compilers complain about + type mismatches in all the code that assumes it is an int. */ + int has_arg; + int *flag; + int val; +}; + +/* Names for the values of the `has_arg' field of `struct option'. */ + +# define no_argument 0 +# define required_argument 1 +# define optional_argument 2 +#endif /* need getopt */ + + +/* Get definitions and prototypes for functions to process the + arguments in ARGV (ARGC of them, minus the program name) for + options given in OPTS. + + Return the option character from OPTS just read. Return -1 when + there are no more options. For unrecognized options, or options + missing arguments, `optopt' is set to the option letter, and '?' is + returned. + + The OPTS string is a list of characters which are recognized option + letters, optionally followed by colons, specifying that that letter + takes an argument, to be placed in `optarg'. + + If a letter in OPTS is followed by two colons, its argument is + optional. This behavior is specific to the GNU `getopt'. + + The argument `--' causes premature termination of argument + scanning, explicitly telling `getopt' that there are no more + options. + + If OPTS begins with `--', then non-option arguments are treated as + arguments to the option '\0'. This behavior is specific to the GNU + `getopt'. */ + +#if (defined __STDC__ && __STDC__) || defined __cplusplus +# ifdef __GNU_LIBRARY__ +/* Many other libraries have conflicting prototypes for getopt, with + differences in the consts, in stdlib.h. To avoid compilation + errors, only prototype getopt for the GNU C library. */ +extern int getopt (int ___argc, char *const *___argv, const char *__shortopts); +# else /* not __GNU_LIBRARY__ */ +//extern int getopt (); +extern int getopt (int ___argc, char *const *___argv, const char *__shortopts); +# endif /* __GNU_LIBRARY__ */ + +# ifndef __need_getopt +extern int getopt_long (int ___argc, char *const *___argv, + const char *__shortopts, + const struct option *__longopts, int *__longind); +extern int getopt_long_only (int ___argc, char *const *___argv, + const char *__shortopts, + const struct option *__longopts, int *__longind); + +/* Internal only. Users should not call this directly. */ +extern int _getopt_internal (int ___argc, char *const *___argv, + const char *__shortopts, + const struct option *__longopts, int *__longind, + int __long_only); +# endif +#else /* not __STDC__ */ +extern int getopt (); +# ifndef __need_getopt +extern int getopt_long (); +extern int getopt_long_only (); + +extern int _getopt_internal (); +# endif +#endif /* __STDC__ */ + +#ifdef __cplusplus +} +#endif + +/* Make sure we later can get all the definitions and declarations. */ +#undef __need_getopt + +#endif /* getopt.h */ + + +","Unknown" +"In Silico","baoilleach/pharao","src/printProgress.cpp",".cpp","966","37","/******************************************************************************* +printProgress.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""printProgress.h"" + + + +void +printProgress(int i) +{ + if((i % 50) == 0) + { + std::cerr << "".""; + if((i % 2500) == 0) + { + std::cerr << i << std::endl; + } + } +} +","C++" +"In Silico","baoilleach/pharao","src/functionMapping.cpp",".cpp","7712","274","/******************************************************************************* +functionMapping.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + + +#include ""functionMapping.h"" + + + +FunctionMapping::FunctionMapping(Pharmacophore* ref, Pharmacophore* db, double eps) +{ + // Initial values + _hasNext = true; + _maxLevel = 0; + _epsilon = eps; + _ref = ref; + _db = db; + _refIndex.clear(); + _dbIndex.clear(); + + // Create an initial set of corresponding functional groups from reference and database + bool initCounts(false); + for (unsigned int i(0); i < _ref->size(); ++i) + { + if ((*_ref)[i].func == EXCL) + { + continue; + } + + for (unsigned int j(0); j < _db->size(); ++j) + { + if ((*_ref)[i].func == (*_db)[j].func) + { + _refIndex.push_back(i); + _dbIndex.push_back(j); + } + else if (((*_ref)[i].func == HYBH) && ((*_db)[j].func == HDON)) + { + _refIndex.push_back(i); + _dbIndex.push_back(j); + } + else if (((*_ref)[i].func == HYBH) && ((*_db)[j].func == HACC)) + { + _refIndex.push_back(i); + _dbIndex.push_back(j); + } + else if (((*_ref)[i].func == HDON) && ((*_db)[j].func == HYBH)) + { + _refIndex.push_back(i); + _dbIndex.push_back(j); + } + else if (((*_ref)[i].func == HACC) && ((*_db)[j].func == HYBH)) + { + _refIndex.push_back(i); + _dbIndex.push_back(j); + } + else if (((*_ref)[i].func == HYBL) && ((*_db)[j].func == AROM)) + { + _refIndex.push_back(i); + _dbIndex.push_back(j); + } + else if (((*_ref)[i].func == HYBL) && ((*_db)[j].func == LIPO)) + { + _refIndex.push_back(i); + _dbIndex.push_back(j); + } + else if (((*_ref)[i].func == AROM) && ((*_db)[j].func == HYBL)) + { + _refIndex.push_back(i); + _dbIndex.push_back(j); + } + else if (((*_ref)[i].func == LIPO) && ((*_db)[j].func == HYBL)) + { + _refIndex.push_back(i); + _dbIndex.push_back(j); + } + } + + // If we get here in the loop, the number of properties should be counted + initCounts = true; + } + + // check if the map is empty + if (_refIndex.empty() && _dbIndex.empty()) + { + return; + } + + // number of possible combinations + unsigned int n = _refIndex.size(); + _matchMap[0] = new std::vector >; + _matchMap[1] = new std::vector >; + for (unsigned int i(0); i < n; ++i) + { + std::vector v(1); // create a new vector to store the first pairs + v[0] = i; + _matchMap[1]->push_back(v); + } + + // _maxLevel = (_maxLevel < ref.size()) ? _maxLevel : ref.size(); + // _maxLevel = (_maxLevel < db.size()) ? _maxLevel : db.size(); + _maxLevel = (_ref->size() < _db->size()) ? _ref->size() : _db->size(); + + // create a new vector to store the first pairs + _matchMap[2] = new std::vector >; + + // now create possible pairs + for (unsigned int i(0); i < n-1; ++i) + { + double v1 = GCI * pow(PI/(*_ref)[_refIndex[i]].alpha, 1.5); + double v2 = GCI * pow(PI/(*_db)[_dbIndex[i]].alpha, 1.5); + for (unsigned int j(i+1); j < n; ++j) + { + if ((_refIndex[i] == _refIndex[j]) || (_dbIndex[i] == _dbIndex[j])) + { + // same group in one of the pairs, not possible + continue; + } + + // compute distances between functional groups within a molecule + double d1 = distance((*_ref)[_refIndex[i]].point, (*_ref)[_refIndex[j]].point); + double d2 = distance((*_db)[_dbIndex[i]].point, (*_db)[_dbIndex[j]].point); + + // check if the relative overlap between points is large enough + d1 = (d1 - d2) * (d1 - d2); + double o1 = GCI2 * pow(PI/((*_ref)[_refIndex[i]].alpha + (*_db)[_dbIndex[i]].alpha), 1.5) * exp(-((*_ref)[_refIndex[i]].alpha * (*_db)[_dbIndex[i]].alpha) * d1/((*_ref)[_refIndex[i]].alpha + (*_db)[_dbIndex[i]].alpha)); + double o2 = GCI2 * pow(PI/((*_ref)[_refIndex[j]].alpha + (*_db)[_dbIndex[j]].alpha), 1.5) * exp(-((*_ref)[_refIndex[j]].alpha * (*_db)[_dbIndex[j]].alpha) * d1/((*_ref)[_refIndex[j]].alpha + (*_db)[_dbIndex[j]].alpha)); + double v3 = GCI * pow(PI/(*_ref)[_refIndex[j]].alpha, 1.5); + double v4 = GCI * pow(PI/(*_db)[_dbIndex[j]].alpha, 1.5); + if ((o2 / (v3 + v4 - o2) > _epsilon) || (o1 / (v1 + v2 - o1) > _epsilon)) + { + std::vector v(2); + v[0] = i; + v[1] = j; + _matchMap[2]->push_back(v); + } + } + } + + for (unsigned int level(3); level <= _maxLevel; ++level) + { + _matchMap[level] = new std::vector >; + // loop over all stored combinations in the previous level + std::vector >::iterator vi, vj, vk; + for (vi = _matchMap[level-1]->begin(); vi != _matchMap[level-1]->end(); ++vi) + { + // Get index of the last pair + unsigned int lastPairIndex = (*vi)[level-2]; + + // Find in all pairs + for (vj = _matchMap[2]->begin(); vj != _matchMap[2]->end(); ++vj) + { + if ((*vj)[0] < lastPairIndex) + { + continue; + } + + if ((*vj)[0] > lastPairIndex) + { + break; + } + + // try to add it to the combination + bool possible = true; + for (unsigned int i(0); i < level-2; ++i) + { + bool found = false; + for (vk = _matchMap[2]->begin(); vk != _matchMap[2]->end(); ++vk) + { + if ((*vk)[0] < (*vi)[i]) + { + continue; + } + + if ((*vk)[0] > (*vi)[i]) + { + break; + } + + if ((*vk)[1] == (*vj)[1]) + { // found corresponding pair + found = true; + break; + } + } + possible &= found; + if (!possible) + { + break; + } + } + + // adding the pair if it is possible + if (possible) + { + std::vector v(level); + for (unsigned int i(0); i < level-1; ++i) + { + v[i] = (*vi)[i]; + } + v[level-1] = (*vj)[1]; + + _matchMap[level]->push_back(v); + } + } + + } // end of loop over combinations + } +} + + + +FunctionMapping::~FunctionMapping() +{ + std::map > *>::iterator mi; + for (mi = _matchMap.begin(); mi != _matchMap.end(); ++mi) + { + if (mi->second != NULL) + { + delete mi->second; + } + } +} + + + + +PharmacophoreMap +FunctionMapping::getNextMap() +{ + PharmacophoreMap pm; + while ((_maxLevel != 0) && _matchMap[_maxLevel]->empty()) + { + --_maxLevel; + } + + if (_maxLevel < 1) + { + pm.clear(); + return pm; + } + + std::vector >::iterator vi = _matchMap[_maxLevel]->begin(); + // loop over all combinations in the current selected vector + // and add them to the function map + for (unsigned int i(0); i < _maxLevel; ++i) + { + unsigned int i1 = _refIndex[(*vi)[i]]; + unsigned int i2 = _dbIndex[(*vi)[i]]; + + pm.insert(std::make_pair(&((*_ref)[i1]),&((*_db)[i2]))); + } + // remove the selected combination + _matchMap[_maxLevel]->erase(vi); + + return pm; +} +","C++" +"In Silico","baoilleach/pharao","src/printUsage.cpp",".cpp","2730","68","/******************************************************************************* +printUsage.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""printUsage.h"" + + + +void +printUsage() +{ + printHeader(); + std::cerr << ""TASK: "" << std::endl; + std::cerr << std::endl; + std::cerr << "" Pharao is a tool to generate and align pharmacophores."" << std::endl; + std::cerr << std::endl; + std::cerr << ""INPUT OPTIONS: "" << std::endl; + std::cerr << std::endl; + std::cerr << "" -r --reference "" << std::endl; + std::cerr << "" --refType "" << std::endl; + std::cerr << "" -d --dbase "" << std::endl; + std::cerr << "" --dbType "" << std::endl; + std::cerr << std::endl; + std::cerr << ""OUTPUT OPTIONS: "" << std::endl; + std::cerr << std::endl; + std::cerr << "" -p --pharmacophore "" << std::endl; + std::cerr << "" -o --out "" << std::endl; + std::cerr << "" -s --scores "" << std::endl; + std::cerr << std::endl; + std::cerr << "" --cutOff "" << std::endl; + std::cerr << "" --best "" << std::endl; + std::cerr << "" --rankBy "" << std::endl; + std::cerr << std::endl; + std::cerr << ""PHARAO OPTIONS: "" << std::endl; + std::cerr << std::endl; + std::cerr << "" -f --funcGroup "" << std::endl; + std::cerr << "" -e --epsilon "" << std::endl; + std::cerr << "" -m --merge"" << std::endl; + std::cerr << "" -n --noNormal"" << std::endl; + std::cerr << "" --noHybrid"" << std::endl; + std::cerr << "" --withExclusion"" << std::endl; + std::cerr << "" --scoreOnly"" << std::endl; + std::cerr << "" --singleConf"" << std::endl; + std::cerr << std::endl; + std::cerr << ""GENERAL OPTIONS: "" << std::endl; + std::cerr << std::endl; + std::cerr << "" -h --help"" << std::endl; + std::cerr << "" --info

= -1; k--) + { + if (k == -1) { + break; + } + if (fabs(e[k]) <= eps*(fabs(_S[k]) + fabs(_S[k+1]))) { + e[k] = 0.0; + break; + } + } + if ( k == p-2 ) + { + mode = 4; + } + else + { + int ks(p-1); // start from ks == p-1 + for ( ; ks >= k; ks--) { + if (ks == k) { + break; + } + double t = ( (ks != p) ? fabs(e[ks]) : 0.0) + ( (ks != k+1) ? fabs(e[ks-1]) : 0.0); + if (fabs(_S[ks]) <= eps*t) + { + _S[ks] = 0.0; + break; + } + } + if (ks == k) { + mode = 3; + } else if (ks == p-1) { + mode = 1; + } else { + mode = 2; + k = ks; + } + } + k++; + + // Perform the task indicated by the selected mode. + switch ( mode ) { + + case 1: + { // Deflate negligible _S[p] + double f = e[p-2]; + e[p-2] = 0.0; + for (j = p-2; j >= k; j--) + { + double t = SiMath::triangle(_S[j],f); + double cs = _S[j]/t; + double sn = f/t; + _S[j] = t; + if (j != k) { + f = -sn*e[j-1]; + e[j-1] = cs*e[j-1]; + } + + // update V + if ( _computeV ) + { + for (i = 0; i < _n; i++) + { + t = cs*_V[i][j] + sn*_V[i][p-1]; + _V[i][p-1] = -sn*_V[i][j] + cs*_V[i][p-1]; + _V[i][j] = t; + } + } + } + } + break; // end case 1 + + case 2: + { // Split at negligible _S[k] + double f = e[k-1]; + e[k-1] = 0.0; + for (j = k; j < p; j++) + { + double t = triangle(_S[j],f); + double cs = _S[j]/t; + double sn = f/t; + _S[j] = t; + f = -sn*e[j]; + e[j] = cs*e[j]; + + if ( _computeU ) + { + for (i = 0; i < _m; i++) { + t = cs*_U[i][j] + sn*_U[i][k-1]; + _U[i][k-1] = -sn*_U[i][j] + cs*_U[i][k-1]; + _U[i][j] = t; + } + } + } + } + break; // end case 2 + + case 3: + { // Perform one qr step. + + // Calculate the shift. + double scale = max(max(max(max(fabs(_S[p-1]),fabs(_S[p-2])),fabs(e[p-2])),fabs(_S[k])),fabs(e[k])); + double sp = _S[p-1]/scale; + double spm1 = _S[p-2]/scale; + double epm1 = e[p-2]/scale; + double sk = _S[k]/scale; + double ek = e[k]/scale; + double b = ((spm1 + sp)*(spm1 - sp) + epm1*epm1)/2.0; + double c = (sp*epm1)*(sp*epm1); + double shift = 0.0; + if ((b != 0.0) || (c != 0.0)) { + shift = sqrt(b*b + c); + if (b < 0.0) { + shift = -shift; + } + shift = c/(b + shift); + } + double f = (sk + sp)*(sk - sp) + shift; + double g = sk*ek; + + // Chase zeros. + + for (j = k; j < p-1; j++) + { + double t = SiMath::triangle(f,g); + double cs = f/t; + double sn = g/t; + if (j != k) { + e[j-1] = t; + } + f = cs*_S[j] + sn*e[j]; + e[j] = cs*e[j] - sn*_S[j]; + g = sn*_S[j+1]; + _S[j+1] = cs*_S[j+1]; + + if ( _computeV ) + { + for (i = 0; i < _n; i++) + { + t = cs*_V[i][j] + sn*_V[i][j+1]; + _V[i][j+1] = -sn*_V[i][j] + cs*_V[i][j+1]; + _V[i][j] = t; + } + } + t = SiMath::triangle(f,g); + cs = f/t; + sn = g/t; + _S[j] = t; + f = cs*e[j] + sn*_S[j+1]; + _S[j+1] = -sn*e[j] + cs*_S[j+1]; + g = sn*e[j+1]; + e[j+1] = cs*e[j+1]; + + if ( _computeU && (j < _m-1) ) + { + for (i = 0; i < _m; i++) + { + t = cs*_U[i][j] + sn*_U[i][j+1]; + _U[i][j+1] = -sn*_U[i][j] + cs*_U[i][j+1]; + _U[i][j] = t; + } + } + } + e[p-2] = f; + iter++; + } + break; // end case 3 + + // convergence step + case 4: + { + + // Make the singular values positive. + if (_S[k] <= 0.0) + { + _S[k] = (_S[k] < 0.0 ) ? -_S[k] : 0.0; + + if ( _computeV ) + { + for (i = 0; i <= pp; i++) { + _V[i][k] = -_V[i][k]; + } + } + } + + // Order the singular values. + while (k < pp) + { + if (_S[k] >= _S[k+1]) + break; + + // swap values and columns if necessary + _S.swap(k,k+1); + + if ( _computeV && (k < _n-1)) + _V.swapColumns(k,k+1); + + if ( _computeU && (k < _m-1) ) + _U.swapColumns(k,k+1); + + k++; + } + iter = 0; + p--; + } + break; // end case 4 + } + } +} + + +Matrix +SVD::getSingularMatrix() +{ + unsigned int n = _S.size(); + Matrix A(n,n,0.0); + // set diagonal elements + for (int i = 0; i < n; i++) + { + A[i][i] = _S[i]; + } + + return A; +} + + + +int +SVD::rank() +{ + double eps = pow(2.0,-52.0); + double tol = max(_m,_n) * _S[0] * eps; + int r = 0; + for (int i = 0; i < _S.size(); i++) { + if (_S[i] > tol) { + r++; + } + } + return r; +} + + + +","C++" +"In Silico","baoilleach/pharao","src/parseCommandLine.cpp",".cpp","10695","336","/******************************************************************************* +parseCommandLine.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""parseCommandLine.h"" + + + +void +parseCommandLine(int argc, char* argv[], Options &o) +{ + static struct option Arguments[] = + { + { ""reference"", required_argument, NULL, 'r' }, + { ""dbase"", required_argument, NULL, 'd' }, + { ""scores"", required_argument, NULL, 's' }, + { ""out"", required_argument, NULL, 'o' }, + { ""pharmacophore"", required_argument, NULL, 'p' }, + { ""funcGroup"", required_argument, NULL, 'f' }, + { ""epsilon"", required_argument, NULL, 'e' }, + { ""merge"", no_argument, NULL, 'm' }, + { ""noNormal"", no_argument, NULL, 'n' }, + { ""help"", no_argument, NULL, 'h' }, + { ""version"", no_argument, NULL, 'v' }, + { ""quiet"", no_argument, NULL, 'q' }, + { ""refType"", required_argument, NULL, 1 }, + { ""dbType"", required_argument, NULL, 2 }, + { ""cutOff"", required_argument, NULL, 3 }, + { ""best"", required_argument, NULL, 4 }, + { ""rankBy"", required_argument, NULL, 5 }, + { ""noHybrid"", no_argument, NULL, 7 }, + { ""info"", required_argument, NULL, 9 }, + { ""withExclusion"", no_argument, NULL, 10 }, + { ""scoreOnly"", no_argument, NULL, 11 }, + { ""singleConf"", no_argument, NULL, 12 }, + { NULL, 0, NULL, 0 } + }; + + // Set defaults + o.dbInpFile.clear(); + o.dbInpStream = NULL; + o.dbInpType = UNKNOWN; + + o.refInpFile.clear(); + o.refInpStream = NULL; + o.refInpType = UNKNOWN; + + o.molOutFile.clear(); + o.molOutStream = NULL; + o.molOutWriter = NULL; + + o.pharmOutFile.clear(); + o.pharmOutStream = NULL; + o.pharmOutWriter = NULL; + + o.scoreOutFile.clear(); + o.scoreOutStream = NULL; + + o.epsilon = 0.5; + + o.cutOff = 0.0; + o.best = 0; + o.rankby = TANIMOTO; + + o.funcGroupVec.resize(10); + o.funcGroupVec[AROM] = true; + o.funcGroupVec[HDON] = true; + o.funcGroupVec[HACC] = true; + o.funcGroupVec[LIPO] = true; + o.funcGroupVec[POSC] = true; + o.funcGroupVec[NEGC] = true; + o.funcGroupVec[HYBH] = false; + o.funcGroupVec[HYBL] = false; + + o.isQuiet = false; + o.noHybrid = false; + o.merge = false; + o.noNormal = false; + o.withExclusion = false; + o.scoreOnly = false; + o.version = false; + o.singleConf = false; + + int choice; + opterr = 0; + int optionIndex = 0; + std::string strvalue, t; + std::list l; + std::list::iterator itL; + std::string ext; + + while((choice = getopt_long(argc, argv,""vhqr:d:s:o:p:f:e:m"", Arguments, &optionIndex )) != -1) + { + switch (choice) + { + case 'v': //....................................................version + o.version = true; + break; + + case 'r': //..................................................reference + o.refInpFile = optarg; + ext = getExt(o.refInpFile); + if (ext == "".phar"") + { + o.refInpType = PHAR; + } + else + { + o.refInpType = MOL; + } + o.refInpStream = new std::ifstream(optarg); + if (!o.refInpStream->good()) + { + mainErr(""Error opening input file for reference (-r)""); + } + break; + + case 'd': //......................................................dbase + o.dbInpFile = optarg; + ext = getExt(o.dbInpFile); + if (ext == "".phar"") + { + o.dbInpType = PHAR; + } + else + { + o.dbInpType = MOL; + } + o.dbInpStream = new std::ifstream(optarg); + if (!o.dbInpStream->good()) + { + mainErr(""Error opening input file for database (-d)""); + } + break; + + case 's': //.....................................................scores + o.scoreOutFile = optarg; + o.scoreOutStream = new std::ofstream(optarg); + if (!o.scoreOutStream->good()) + { + mainErr(""Error opening output file for scores (-s)""); + } + break; + + case 'o': //........................................................out + o.molOutFile = optarg; + o.molOutStream = new std::ofstream(optarg); + if (!o.molOutStream->good()) + { + mainErr(""Error opening output file for molecules (-o)""); + } + o.molOutWriter = new OpenBabel::OBConversion(); + o.molOutWriter->SetOutFormat(o.molOutWriter->FormatFromExt(optarg)); + break; + + case 'p': //..............................................pharmacophore + o.pharmOutFile = optarg; + o.pharmOutStream = new std::ofstream(optarg); + if (!o.pharmOutStream->good()) + { + mainErr(""Error opening output file for pharmacophores (-p)""); + } + o.pharmOutWriter = new PharmacophoreWriter(); + break; + + case 'e': //....................................................epsilon + o.epsilon = strtod(optarg,NULL); + break; + + case 'm': //......................................................merge + o.merge = true; + o.noNormal = true; + break; + + case 'n': //...................................................noNormal + o.noNormal = true; + break; + + case 'f': //..................................................funcGroup + { + std::list l = stringTokenizer(optarg, "",""); + std::list::iterator itL; + std::vector vec(10, false); + for (itL = l.begin(); itL != l.end(); ++itL) + { + if (*itL == ""AROM"") + { + vec[AROM] = true; + continue; + } + if (*itL == ""HDON"") + { + vec[HDON] = true; + continue; + } + if (*itL == ""HACC"") + { + vec[HACC] = true; + continue; + } + if (*itL == ""LIPO"") + { + vec[LIPO] = true; + continue; + } + if (*itL == ""CHARGE"") + { + vec[POSC] = true; + vec[NEGC] = true; + continue; + } + mainErr(""Undefined functional Group. Only AROM, HDON, HACC, LIPO and"" + ""CHARGE are allowed as argument.""); + } + o.funcGroupVec = vec; + } + break; + + case 1: //......................................................refType + t = optarg; + if (t == ""MOL"") + { + o.refInpType = MOL; + break; + } + if (t == ""PHAR"") + { + o.refInpType = PHAR; + break; + } + mainErr(""Undefined reference type : "" + t); + break; + + case 2: //.......................................................dbType + t = optarg; + if (t == ""MOL"") + { + o.dbInpType = MOL; + break; + } + if (t == ""PHAR"") + { + o.dbInpType = PHAR; + break; + } + mainErr(""Undefined dbase type: "" + t); + break; + + case 3: //.......................................................cutOff + o.cutOff = strtod(optarg, NULL); + break; + + case 4: //.........................................................best + o.best = strtol(optarg, NULL, 10); + break; + + case 5: //.......................................................rankby + t = optarg; + if (t == ""TANIMOTO"") + { + o.rankby = TANIMOTO; + break; + } + if (t == ""TVERSKY_REF"") + { + o.rankby = TVERSKY_REF; + break; + } + if (t == ""TVERSKY_DB"") + { + o.rankby = TVERSKY_DB; + break; + } + mainErr(""Undefined rankby type : "" + t); + break; + + case 7: //.....................................................noHybrid + o.noHybrid = true; + break; + + case 'h': //.......................................................help + o.help = true; + break; + + case 9: //.........................................................info + printInfo(std::string(optarg)); + break; + + case 10: //...............................................withExclusion + o.withExclusion = true; + break; + + case 11: //...................................................scoreOnly + o.scoreOnly = true; + break; + + case 12: //...................................................singleConf + o.singleConf = true; + break; + + case 'q': //......................................................quiet + o.isQuiet = true; + break; + + default: + mainErr(""unknown command line option""); + } + } + + // If no options are given print the help + if (optind == 1) + { + o.help = true; + } + + argc -= optind; + argv += optind; + return; +} +","C++" +"In Silico","baoilleach/pharao","src/hDonFuncCalc.cpp",".cpp","2381","86","/******************************************************************************* +hDonFuncCalc.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""hDonFuncCalc.h"" + + + +void +hDonFuncCalc(OpenBabel::OBMol* mol, Pharmacophore* pharmacophore) +{ + // Create for every hydrogen donor a pharmacophore point + std::vector::iterator ai; + for (OpenBabel::OBAtom* a = mol->BeginAtom(ai); a; a = mol->NextAtom(ai)) + { + if (a->GetAtomicNum() == 7 || a->GetAtomicNum() == 8) + { + if (a->GetFormalCharge() >= 0 && ((a->GetImplicitValence() - a->GetHvyValence()) !=0)) + { + PharmacophorePoint p; + p.func = HDON; + p.point.x = a->x(); + p.point.y = a->y(); + p.point.z = a->z(); + p.hasNormal = true; + p.alpha = funcSigma[HDON]; + p.normal = _hDonCalcNormal(a); + pharmacophore->push_back(p); + } + } + } +} + + + +Coordinate +_hDonCalcNormal(OpenBabel::OBAtom* a) +{ + int nbrBonds(0); + Coordinate normal; + + std::vector::iterator bi; + for (OpenBabel::OBBond* b = a->BeginBond(bi); b; b = a->NextBond(bi)) + { + OpenBabel::OBAtom* aa = b->GetNbrAtom(a); + if (aa->GetAtomicNum() == 1) + { + continue; + } + ++nbrBonds; + normal.x += (aa->x() - a->x()); + normal.y += (aa->y() - a->y()); + normal.z += (aa->z() - a->z()); + } + double length(sqrt(normal.x*normal.x + normal.y*normal.y + normal.z*normal.z)); + normal.x /= length; + normal.y /= length; + normal.z /= length; + + normal.x = -normal.x; + normal.y = -normal.y; + normal.z = -normal.z; + + normal.x += a->x(); + normal.y += a->y(); + normal.z += a->z(); + + return normal; +} +","C++" +"In Silico","baoilleach/pharao","src/printInfo.cpp",".cpp","18492","364","/******************************************************************************* +printInfo.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""printInfo.h"" + + + +void +printInfo(const std::string& option) +{ + // Information taken from Pharao Manual (section IV) + bool valid(false); + printHeader(); + if (option == ""r"" || option == ""reference"") + { + std::cerr << "" -r --reference"" << std::endl; + std::cerr << std::endl; + std::cerr << "" Defines the reference structure that will be used to screen and/or"" << std::endl; + std::cerr << "" align the database. This option is not required, so when not given,"" << std::endl; + std::cerr << "" only the database will be converted into pharmacophores without alignment."" << std::endl; + std::cerr << std::endl; + std::cerr << "" By default the format is deduced from the extension of the file"" << std::endl; + std::cerr << "" but can be defined explicitly with the --refType option."" << std::endl; + std::cerr << std::endl; + valid = true; + } + + if (option == ""refType"") + { + std::cerr << "" --refType"" << std::endl; + std::cerr << std::endl; + std::cerr << "" With this option the format of the reference input file can be"" << std::endl; + std::cerr << "" specified. At the moment only two formats are supported:"" << std::endl; + std::cerr << std::endl; + std::cerr << "" 'MOL' : The default format. Molecule should contain coordinate"" << std::endl; + std::cerr << "" information."" << std::endl; + std::cerr << "" 'PHAR' : The molecule is already transformed in pharmacophore"" << std::endl; + std::cerr << "" format."" << std::endl; + std::cerr << std::endl; + std::cerr << "" If the pharmacophore format is used, the program will generate a"" << std::endl; + std::cerr << "" pharmacophore for the reference molecule. The time needed for this"" << std::endl; + std::cerr << "" generation is however negligible compared with the time needed for"" << std::endl; + std::cerr << "" a proper alignment."" << std::endl; + std::cerr << std::endl; + valid = true; + } + + if (option == ""d"" || option==""dbase"") + { + std::cerr << "" -d --dbase"" << std::endl; + std::cerr << std::endl; + std::cerr << "" Defines the database, or a collection of structures, that will be"" << std::endl; + std::cerr << "" used to screen. This option is required but it is allowed to"" << std::endl; + std::cerr << "" select a database containing only a single molecule."" << std::endl; + std::cerr << std::endl; + std::cerr << "" The database can consist of precalculated pharmacophores or of"" << std::endl; + std::cerr << "" molecules in a format readable by the computer."" << std::endl; + std::cerr << std::endl; + std::cerr << "" By default the format is deduced from the extension of the file"" << std::endl; + std::cerr << "" but can be defined explicitly with the --dbType option."" << std::endl; + std::cerr << std::endl; + valid = true; + } + + if (option == ""dbType"") + { + std::cerr << "" --dbType"" << std::endl; + std::cerr << std::endl; + std::cerr << "" With this option the format of the database input file(s) can be"" << std::endl; + std::cerr << "" specified. At the moment only four formats are supported: "" << std::endl; + std::cerr << std::endl; + std::cerr << "" 'MOL' : The default format. Molecules should contain coordinate"" << std::endl; + std::cerr << "" information. The actual fileformat is deduced automatically"" << std::endl; + std::cerr << "" from the file extension."" << std::endl; + std::cerr << "" 'PHAR' : The molecules are already transformed in pharmacophore"" << std::endl; + std::cerr << "" format."" << std::endl; + std::cerr << std::endl; + std::cerr << "" If the pharmacophore format is not used, the program will generate"" << std::endl; + std::cerr << "" a pharmacophore for each molecule on-the-fly. The time needed for"" << std::endl; + std::cerr << "" this generation is however negligible compared with the time"" << std::endl; + std::cerr << "" needed for a proper alignement."" << std::endl; + std::cerr << std::endl; + valid = true; + } + + if (option == ""p"" || option == ""pharmacophore"") + { + std::cerr << "" -p --pharmacophore"" << std::endl; + std::cerr << std::endl; + std::cerr << "" In this file the processed pharmacophores of the structures in"" << std::endl; + std::cerr << "" the input database are stored. These pharmacophores will not"" << std::endl; + std::cerr << "" correspond to the original structures because they are aligned"" << std::endl; + std::cerr << "" with respect to the reference input molecule and therefore can"" << std::endl; + std::cerr << "" have a different orientation. Moreover, only points used in the"" << std::endl; + std::cerr << "" alignment are reported."" << std::endl; + std::cerr << std::endl; + std::cerr << "" For more information about the format in which the pharmacophores"" << std::endl; + std::cerr << "" are written, consult the Pharao manual."" << std::endl; + std::cerr << std::endl; + valid = true; + } + + if (option == ""o"" || option == ""out"") + { + std::cerr << "" -o --out"" << std::endl; + std::cerr << std::endl; + std::cerr << "" In this file the transformed database structures after aligning"" << std::endl; + std::cerr << "" them to the reference structure can be written down. These"" << std::endl; + std::cerr << "" structures correspond to the processed pharmacophores. "" << std::endl; + std::cerr << std::endl; + std::cerr << "" This file is written in the sdf-format."" << std::endl; + std::cerr << "" If the extension .gz is used, the file will be automatically zipped."" << std::endl; + std::cerr << std::endl; + valid = true; + } + + if (option == ""s"" || option == ""scores"") + { + std::cerr << "" -s --scores"" << std::endl; + std::cerr << std::endl; + std::cerr << "" With this option a tab-delimited text file can be generated"" << std::endl; + std::cerr << "" containing the following information:"" << std::endl; + std::cerr << std::endl; + std::cerr << "" 'column 1' : Id of the reference structure."" << std::endl; + std::cerr << "" 'column 2' : Maximum volume of the reference structure."" << std::endl; + std::cerr << "" 'column 3' : Id of the database structure."" << std::endl; + std::cerr << "" 'column 4' : Maximum volume of the database structure."" << std::endl; + std::cerr << "" 'column 5' : Maximum pharmacophore overlap of the two structures."" << std::endl; + std::cerr << "" 'column 6' : Overlap between pharmacophore and exclusion spheres"" << std::endl; + std::cerr << "" in the reference."" << std::endl; + std::cerr << "" 'column 7' : Corrected volume overlap between database"" << std::endl; + std::cerr << "" pharmacophore and reference."" << std::endl; + std::cerr << "" 'column 8' : Number of pharmacophore points in the processed"" << std::endl; + std::cerr << "" pharmacophore."" << std::endl; + std::cerr << "" 'column 9' : TANIMOTO score. This value is between 0 and 1."" << std::endl; + std::cerr << "" 'column 10' : TVERSKY_REF score. This value is between 0 and 1."" << std::endl; + std::cerr << "" 'column 11' : TVERSKY_DB score. This value is between 0 and 1."" << std::endl; + std::cerr << std::endl; + std::cerr << "" More information about the three different scoring schemes can be"" << std::endl; + std::cerr << "" obtained by ty typing: Pharao --info rankby "" << std::endl; + std::cerr << std::endl; + valid = true; + } + + if (option == ""cutOff"") + { + std::cerr << "" --cutOff"" << std::endl; + std::cerr << std::endl; + std::cerr << "" This value should be between 0 and 1 and only structures with a"" << std::endl; + std::cerr << "" score, as defined by the --rankBy option, higher than this value"" << std::endl; + std::cerr << "" are reported in the three possible output files."" << std::endl; + std::cerr << std::endl; + valid = true; + } + + if (option == ""best"") + { + std::cerr << "" --best"" << std::endl; + std::cerr << std::endl; + std::cerr << "" With this option only a limited number of best scoring structures,"" << std::endl; + std::cerr << "" as defined by the --rankBy option, are reported in the three"" << std::endl; + std::cerr << "" possible output files. If the --cutOff option was used, all best "" << std::endl; + std::cerr << "" scoring structures must first pass this filter. The user can "" << std::endl; + std::cerr << "" specify the number of best scoring structures that should be "" << std::endl; + std::cerr << "" reported."" << std::endl; + std::cerr << std::endl; + valid = true; + } + + if (option == ""rankBy"") + { + std::cerr << "" --rankBy"" << std::endl; + std::cerr << std::endl; + std::cerr << "" This option defines the scoring used by the --cutOff and --best"" << std::endl; + std::cerr << "" options. Currently two measures are implemented:"" << std::endl; + std::cerr << std::endl; + std::cerr << "" 'TANIMOTO' : Final overlap score. This value is between 0 and"" << std::endl; + std::cerr << "" 1, and the closer this value to 1, the better the"" << std::endl; + std::cerr << "" alignment."" << std::endl; + std::cerr << "" 'TVERSKY_REF' : Overlap ref volume ratio. This value is between 0"" << std::endl; + std::cerr << "" and 1, and the closer this value to 1, the better"" << std::endl; + std::cerr << "" the reference pharmacophore is 'included' in the"" << std::endl; + std::cerr << "" database pharmacophore, regardless the unmatched"" << std::endl; + std::cerr << "" part of the database pharmacophore."" << std::endl; + std::cerr << "" 'TVERSKY_DB' : Overlap db volume ratio. This value is between 0"" << std::endl; + std::cerr << "" and 1, and the closer this value to 1, the better"" << std::endl; + std::cerr << "" the database pharmacophore is 'included' in the"" << std::endl; + std::cerr << "" reference pharmacophore, regardless the unmatched"" << std::endl; + std::cerr << "" part of the reference pharmacophore."" << std::endl; + std::cerr << std::endl; + std::cerr << "" By default the TANIMOTO score is used. For more information"" << std::endl; + std::cerr << "" consult the Pharao manual."" << std::endl; + std::cerr << std::endl; + valid = true; + } + + if (option == ""f"" || option == ""funcGroup"") + { + std::cerr << "" -f --funcGroup"" << std::endl; + std::cerr << std::endl; + std::cerr << "" By default all generated pharmacophores contain all functional"" << std::endl; + std::cerr << "" groups and thus include all information that might be useful. With"" << std::endl; + std::cerr << "" this option only a subset of the available functional groups can"" << std::endl; + std::cerr << "" be used in the alignment. The user can define this subset by using"" << std::endl; + std::cerr << "" the tags listed below with the ',' symbol as separator."" << std::endl; + std::cerr << std::endl; + std::cerr << "" 'AROM' : Aromatic rings"" << std::endl; + std::cerr << "" 'HDON' : Hydrogen donors"" << std::endl; + std::cerr << "" 'HACC' : Hydrogen acceptor"" << std::endl; + std::cerr << "" 'LIPO' : Lipophilic spots"" << std::endl; + std::cerr << "" 'CHARGE' : Charge centers (both positive and negative)"" << std::endl; + std::cerr << std::endl; + std::cerr << "" If both reference and database structures are defined in the"" << std::endl; + std::cerr << "" pharmacophore format this option is discarded and has no influence"" << std::endl; + std::cerr << std::endl; + valid = true; + } + + if (option == ""e"" || option == ""epsilon"") + { + std::cerr << "" -e --epsilon"" << std::endl; + std::cerr << std::endl; + std::cerr << "" This option can be used to change the level of relative overlap between"" << std::endl; + std::cerr << "" points to be considered as feasible combinations. As such, it is an important"" << std::endl; + std::cerr << "" parameter in the 'feature mapping'."" << std::endl; + std::cerr << std::endl; + std::cerr << "" The value should be set between 0.0 and 1.0 and indicates how much overlap"" << std::endl; + std::cerr << "" is required for two points to be considered as a feasible combination. The relative overlap"" << std::endl; + std::cerr << "" is computed by mapping one database point on top of one reference point and measuring the "" << std::endl; + std::cerr << "" overlap between the two other points. Smaller values are less stringent, but require"" << std::endl; + std::cerr << "" more computing time."" << std::endl; + std::cerr << "" The default value is 0.5"" << std::endl; + std::cerr << std::endl; + valid = true; + } + + if (option == ""m"" || option == ""merge"") + { + std::cerr << "" -m --merge"" << std::endl; + std::cerr << std::endl; + std::cerr << "" This option can be used to merge pharmacophore points that are"" << std::endl; + std::cerr << "" close enough to each other together into a single pharmacophore"" << std::endl; + std::cerr << "" point with the same functional group, but with an increased sigma."" << std::endl; + std::cerr << std::endl; + std::cerr << "" This flag also activates the -n or --noNormal flag because merged"" << std::endl; + std::cerr << "" pharmacophore points can't have a 'direction'."" << std::endl; + std::cerr << std::endl; + valid = true; + } + + if (option == ""n"" || option == ""noNormal"") + { + std::cerr << "" -n --noNormal"" << std::endl; + std::cerr << std::endl; + std::cerr << "" Flag to indicate that no normal information is used during alignment."" << std::endl; + std::cerr << std::endl; + std::cerr << "" By default, several pharmacophore features contain normal"" << std::endl; + std::cerr << "" information to add the notion of 'direction' in addition to"" << std::endl; + std::cerr << "" 'position'. AROM, HYBL, HDON, HACC and HYBH points all have such an"" << std::endl; + std::cerr << "" additional constraint. Using this information makes the"" << std::endl; + std::cerr << "" pharmacophore model more specific."" << std::endl; + std::cerr << std::endl; + std::cerr << "" When the -m or --merge flag is used this flag is automatically"" << std::endl; + std::cerr << "" activated."" << std::endl; + std::cerr << std::endl; + valid = true; + } + + if (option == ""noHybrid"") + { + std::cerr << "" --noHybrid"" << std::endl; + std::cerr << std::endl; + std::cerr << "" Flag to indicate that no hybrid points should be included in the"" << std::endl; + std::cerr << "" final pharmacophores. The possible hybrid pharmacophore points are:"" << std::endl; + std::cerr << std::endl; + std::cerr << "" 'HYBL' : AROM + LIPO"" << std::endl; + std::cerr << "" 'HYBH' : HDON + HACC"" << std::endl; + std::cerr << std::endl; + std::cerr << "" Hybrid pharmacophore points are generated by default to reduce the"" << std::endl; + std::cerr << "" number of pharmacophore points."" << std::endl; + std::cerr << std::endl; + valid = true; + } + + if (option == ""scoreOnly"") + { + std::cerr << "" --scoreOnly"" << std::endl; + std::cerr << std::endl; + std::cerr << "" Flag to indicate when the volume overlap should only be computed from "" << std::endl; + std::cerr << "" the given poses and do not perform any translation or rotation of the "" << std::endl; + std::cerr << "" pharmacophore points to optimize the overlap."" << std::endl; + std::cerr << std::endl; + valid = true; + } + + if (option == ""withExclusion"") + { + std::cerr << "" --withExclusion"" << std::endl; + std::cerr << std::endl; + std::cerr << "" Flag to indicate if the exclusion spheres should be part of"" << std::endl; + std::cerr << "" the optimization procedure. By default the overlap between "" << std::endl; + std::cerr << "" pharmacophore and exclusion spheres is only taken into account"" << std::endl; + std::cerr << "" at the end of the alignment procedure. When this flag is set,"" << std::endl; + std::cerr << "" the exclusion spheres have an imapct on the optimization procedure."" << std::endl; + std::cerr << std::endl; + valid = true; + } + + if (option == ""h"" || option == ""help"") + { + std::cerr << "" -h --help"" << std::endl; + std::cerr << std::endl; + std::cerr << "" With this option a general help on the usage of Pharao is provided."" << std::endl; + std::cerr << std::endl; + valid = true; + } + + if (option == ""info"") + { + std::cerr << "" --info"" << std::endl; + std::cerr << std::endl; + std::cerr << "" With this option the user can get detailed information for each"" << std::endl; + std::cerr << "" option."" << std::endl; + std::cerr << std::endl; + valid = true; + } + + if (option == ""q"" || option == ""quiet"") + { + std::cerr << "" -q --quiet"" << std::endl; + std::cerr << std::endl; + std::cerr << "" If no output is needed during the execution of the program this "" << std::endl; + std::cerr << "" option can be used and no output, progress or warnings are shown "" << std::endl; + std::cerr << "" to the user."" << std::endl; + std::cerr << std::endl; + valid = true; + } + + if (!valid) + { + std::cerr << "" Unknown option: "" << option << std::endl; + std::cerr << std::endl; + } + + exit(0); +} +","C++" +"In Silico","baoilleach/pharao","src/stringTokenizer.cpp",".cpp","1700","61","/******************************************************************************* +stringTokenizer.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""stringTokenizer.h"" + + + +std::list +stringTokenizer(const std::string& s, const std::string& spacer) +{ + const std::string::size_type len = s.length(); + std::string::size_type i = 0; + std::list container; + container.clear(); + + while (i < len) + { + // eat leading whitespace + i = s.find_first_not_of(spacer, i); + if (i == std::string::npos) + { + return container; // nothing left but white space + } + + // find the end of the token + std::string::size_type j = s.find_first_of(spacer, i); + + // push token onto container + if (j == std::string::npos) // end of string + { + container.push_back(s.substr(i)); + return container; + } + else // + { + container.push_back(s.substr(i, j-i)); + } + // move positions to next substring + i = j + 1; + } + + return container; +}; +","C++" +"In Silico","baoilleach/pharao","src/getExt.cpp",".cpp","979","35","/******************************************************************************* +getExt.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""getExt.h"" + + + +std::string +getExt(std::string& s) +{ + int pos(s.find_last_of(""."")); + if (pos < 1) + { + mainErr(""File \'"" + s + ""\' has no extension.""); + } + return s.substr(pos, s.size()-pos); +} +","C++" +"In Silico","baoilleach/pharao","src/pharmacophore.cpp",".cpp","5296","223","/******************************************************************************* +pharmacophore.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""pharmacophore.h"" + + + +PharmacophorePoint::PharmacophorePoint() +{ + func = UNDEF; + alpha = 1.0; + normal.x = 0.0; + + normal.y = 0.0; + normal.z = 0.0; + + point.x = 0.0; + point.y = 0.0; + point.z = 0.0; + + hasNormal = false; +} + + + +PharmacophorePoint::PharmacophorePoint(const PharmacophorePoint & p) +{ + point = p.point; + func = p.func; + alpha = p.alpha; + normal = p.normal; + hasNormal = p.hasNormal; +} + + + +PharmacophorePoint::PharmacophorePoint(const PharmacophorePoint * p) +{ + point = p->point; + func = p->func; + alpha = p->alpha; + normal = p->normal; + hasNormal = p->hasNormal; +} + + + +PharmacophoreReader::PharmacophoreReader(void) +{ +} + + + +PharmacophoreReader::~PharmacophoreReader(void) +{ +} + + + +Pharmacophore +PharmacophoreReader::read(std::ifstream* _input, std::string& name) +{ + Pharmacophore pharmacophore; + pharmacophore.clear(); + + if (!*_input) + { + mainWar(""Unable to read Pharmacophore. Input stream not accessible.""); + return pharmacophore; + } + + std::string line; + getline(*_input, line); + name = line; + getline(*_input, line); + while (line != ""$$$$"") + { + if (line[0]=='#') continue; + + PharmacophorePoint p; + + std::list lineList = stringTokenizer(line, ""\t""); + std::vector lineVec; + lineVec.clear(); + std::list::iterator li; + for (li = lineList.begin(); li != lineList.end(); ++li) + { + lineVec.push_back(*li); + } + + if (lineVec.size() < 8) + { + _skipPharmacophore(_input); + if (!_input->eof()) + { + mainWar(""incorrect line: "" + line); + pharmacophore.clear(); + return pharmacophore; + } + else + { + return pharmacophore; + } + } + + bool isOk(false); + if (lineVec[0] == ""AROM"") {isOk = true; p.func = AROM;} + if (lineVec[0] == ""HDON"") {isOk = true; p.func = HDON;} + if (lineVec[0] == ""HACC"") {isOk = true; p.func = HACC;} + if (lineVec[0] == ""LIPO"") {isOk = true; p.func = LIPO;} + if (lineVec[0] == ""POSC"") {isOk = true; p.func = POSC;} + if (lineVec[0] == ""NEGC"") {isOk = true; p.func = NEGC;} + if (lineVec[0] == ""HYBH"") {isOk = true; p.func = HYBH;} + if (lineVec[0] == ""HYBL"") {isOk = true; p.func = HYBL;} + if (lineVec[0] == ""EXCL"") {isOk = true; p.func = EXCL;} + if (!isOk) + { + _skipPharmacophore(_input); + mainWar(""incorrect functional group:: "" + line); + pharmacophore.clear(); + return pharmacophore; + } + + p.point.x = strtod(lineVec[1].c_str(), NULL); + p.point.y = strtod(lineVec[2].c_str(), NULL); + p.point.z = strtod(lineVec[3].c_str(), NULL); + + p.alpha = strtod(lineVec[4].c_str(), NULL); + + if (lineVec[5] == ""1"") {p.hasNormal = true;} + if (lineVec[5] == ""0"") {p.hasNormal = false;} + + p.normal.x = strtod(lineVec[6].c_str(), NULL); + p.normal.y = strtod(lineVec[7].c_str(), NULL); + p.normal.z = strtod(lineVec[8].c_str(), NULL); + + pharmacophore.push_back(p); + getline(*_input, line); + } + + return pharmacophore; +} + + + +void +PharmacophoreReader::_skipPharmacophore(std::ifstream* _input) +{ + std::string line; + getline(*_input, line); + while (line!=""$$$$"") + { + if(_input->eof()) return; + getline(*_input, line); + } +} + + + +PharmacophoreWriter::PharmacophoreWriter(void) +{ +} + + + +PharmacophoreWriter::~PharmacophoreWriter(void) +{ +} + + + +void +PharmacophoreWriter::write(Pharmacophore& p, std::ofstream* os, const std::string& name) +{ + *os << name << std::endl; + + Pharmacophore::iterator itP; + for (itP = p.begin(); itP != p.end(); ++itP) + { + switch (itP->func) + { + case AROM: *os << ""AROM\t""; break; + case HDON: *os << ""HDON\t""; break; + case HACC: *os << ""HACC\t""; break; + case LIPO: *os << ""LIPO\t""; break; + case POSC: *os << ""POSC\t""; break; + case NEGC: *os << ""NEGC\t""; break; + case HYBH: *os << ""HYBH\t""; break; + case HYBL: *os << ""HYBL\t""; break; + case EXCL: *os << ""EXCL\t""; break; + } + + Coordinate c(itP->point); + *os << c.x << '\t' << c.y << '\t' << c.z << '\t'; + + *os << itP->alpha << '\t'; + + itP->hasNormal ? (*os << ""1\t"") : (*os << ""0\t""); + + Coordinate n(itP->normal); + *os << n.x << '\t' << n.y << '\t' << n.z << std::endl; + } + *os << ""$$$$"" << std::endl; +} + +","C++" +"In Silico","baoilleach/pharao","src/utilities.cpp",".cpp","10586","439","/******************************************************************************* +utilities.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""utilities.h"" + + + +Coordinate +translate(Coordinate& p, Coordinate& t) +{ + Coordinate n; + n.x = p.x + t.x; + n.y = p.y + t.y; + n.z = p.z + t.z; + return n; +} + + + +Coordinate +rotate(Coordinate& p, SiMath::Matrix& U) +{ + Coordinate n; + n.x = p.x * U[0][0] + p.y * U[0][1] + p.z * U[0][2]; + n.y = p.x * U[1][0] + p.y * U[1][1] + p.z * U[1][2]; + n.z = p.x * U[2][0] + p.y * U[2][1] + p.z * U[2][2]; + return n; +} + + + +void +normalise(Coordinate& p) +{ + double d = p.x*p.x + p.y*p.y + p.z*p.z; + d = sqrt(d); + p.x /= d; + p.y /= d; + p.z /= d; + return; +} + + + +double +norm(Coordinate& p) +{ + return sqrt(p.x*p.x + p.y*p.y + p.z*p.z); +} + + + +double +dotProduct(Coordinate& p1, Coordinate& p2) +{ + return p1.x*p2.x + p1.y*p2.y + p1.z*p2.z; +} + + + +Coordinate +crossProduct(Coordinate& p1, Coordinate& p2) +{ + Coordinate p; + p.x = (p1.y * p2.z) - (p1.z * p2.y); + p.y = (p1.z * p2.x) - (p1.x * p2.z); + p.z = (p1.x * p2.y) - (p1.y * p2.x); + return p; +} + + +double +cosine(Coordinate& p1, Coordinate& p2) +{ + double c(p1.x*p2.x + p1.y*p2.y + p1.z*p2.z); + c /= norm(p1); + c /= norm(p2); + return c; +} + + +double +distance(Coordinate& p1, Coordinate& p2) +{ + double d(0.0); + d += (p1.x - p2.x)*(p1.x - p2.x); + d += (p1.y - p2.y)*(p1.y - p2.y); + d += (p1.z - p2.z)*(p1.z - p2.z); + return sqrt(d); +} + + + +void +normalise(SiMath::Vector& v) +{ + double d(0.0); + for (unsigned int i = 0; i < 4; i++) d += v[i] * v[i]; + v /= sqrt(d); + return; +} + + + +SiMath::Matrix +quat2Rotation(SiMath::Vector& Q) +{ + double d1sq(Q[1]*Q[1]); + double d2sq(Q[2]*Q[2]); + double d3sq(Q[3]*Q[3]); + + SiMath::Matrix U(3,3); + U[0][0] = 1.0 - 2.0 * d2sq - 2.0 * d3sq; + U[1][0] = 2.0 * (Q[1] * Q[2] + Q[0] * Q[3]); + U[2][0] = 2.0 * (Q[1] * Q[3] - Q[0] * Q[2]); + + U[0][1] = 2.0 * (Q[2] * Q[1] - Q[0] * Q[3]); + U[1][1] = 1.0 - 2.0 * d1sq - 2.0 * d3sq; + U[2][1] = 2.0 * (Q[2] * Q[3] + Q[0] * Q[1]); + + U[0][2] = 2.0 * (Q[3] * Q[1] + Q[0] * Q[2]); + U[1][2] = 2.0 * (Q[3] * Q[2] - Q[0] * Q[1]); + U[2][2] = 1.0 - 2.0 * d1sq - 2.0 * d2sq; + + return U; +} + + + +void +inverseHessian(SiMath::Matrix& H) +{ + // define H = [H00 H01 | H10 H11] + // R0 = inv(H00) + SiMath::Matrix R0(2,2); + double d = (H[0][0] * H[1][1] - H[0][1] * H[1][0]); + if ( d > 1e-6 || d < -1e-6) d = 1.0 / d; + + R0[0][0] = d * H[1][1]; + R0[1][1] = d * H[0][0]; + R0[0][1] = -d * H[0][1]; + R0[1][0] = -d * H[1][0]; + + // R1 = H10 * R0 + SiMath::Matrix R1(2,2); + R1[0][0] = H[2][0]*R0[0][0] + H[2][1] * R0[1][0]; + R1[0][1] = H[2][0]*R0[0][1] + H[2][1] * R0[1][1]; + R1[1][0] = H[3][0]*R0[0][0] + H[3][1] * R0[1][0]; + R1[1][1] = H[3][0]*R0[0][1] + H[3][1] * R0[1][1]; + + // R2 = R0 * H01 + SiMath::Matrix R2(2,2); + R2[0][0] = R0[0][0]*H[0][2] + R0[0][1] * H[1][2]; + R2[0][1] = R0[0][0]*H[0][3] + R0[0][1] * H[1][3]; + R2[1][0] = R0[1][0]*H[0][2] + R0[1][1] * H[1][2]; + R2[1][1] = R0[1][0]*H[0][3] + R0[1][1] * H[1][3]; + + // R3 = H10 * R1 + SiMath::Matrix R3(2,2); + R3[0][0] = H[2][0]*R2[0][0] + H[2][1] * R2[1][0]; + R3[0][1] = H[2][0]*R2[0][1] + H[2][1] * R2[1][1]; + R3[1][0] = H[3][0]*R2[0][0] + H[3][1] * R2[1][0]; + R3[1][1] = H[3][0]*R2[0][1] + H[3][1] * R2[1][1]; + + // R3 = R3 - A11 + R3[0][0] -= H[2][2]; + R3[0][1] -= H[2][3]; + R3[1][0] -= H[3][2]; + R3[1][1] -= H[3][3]; + + // R3 = inv(R3) + d = (R3[0][0] * R3[1][1] - R3[0][1] * R3[1][0]); + if ( d > 1e-6 || d < -1e-6 ) R3 /= d; + + // swap [0][0] with [1][1] + d = R3[1][1]; + R3[1][1] = R3[0][0]; + R3[0][0] = d; + + // negate [0][1] and [1][0] + R3[1][0] = -R3[1][0]; + R3[0][1] = -R3[0][1]; + + // H01 = R2 * R3 + H[0][2] = R2[0][0] * R3[0][0] + R2[0][1] * R3[1][0]; + H[0][3] = R2[0][0] * R3[0][1] + R2[0][1] * R3[1][1]; + H[1][2] = R2[1][0] * R3[0][0] + R2[1][1] * R3[1][0]; + H[1][3] = R2[1][0] * R3[0][1] + R2[1][1] * R3[1][1]; + + // H10 = R3 * R1 + H[2][0] = R3[0][0] * R1[0][0] + R3[0][1] * R1[1][0]; + H[2][1] = R3[0][0] * R1[0][1] + R3[0][1] * R1[1][1]; + H[3][0] = R3[1][0] * R1[0][0] + R3[1][1] * R1[1][0]; + H[3][1] = R3[1][0] * R1[0][1] + R3[1][1] * R1[1][1]; + + // R4 = R2 * H10 + SiMath::Matrix R4(2,2); + R4[0][0] = R2[0][0] * H[2][0] + R2[0][1] * H[3][0]; + R4[0][1] = R2[0][0] * H[2][1] + R2[0][1] * H[3][1]; + R4[1][0] = R2[1][0] * H[2][0] + R2[1][1] * H[3][0]; + R4[1][1] = R2[1][0] * H[2][1] + R2[1][1] * H[3][1]; + + // H00 = R0 - R4 + H[0][0] = R0[0][0] - R4[0][0]; + H[0][1] = R0[0][1] - R4[0][1]; + H[1][0] = R0[1][0] - R4[1][0]; + H[1][1] = R0[1][1] - R4[1][1]; + + // H11 = -R3 + H[2][2] = -R3[0][0]; + H[2][3] = -R3[0][1]; + H[3][2] = -R3[1][0]; + H[3][3] = -R3[1][1]; + + return; +} + + + +double +VolumeOverlap(PharmacophorePoint& p1, PharmacophorePoint& p2, bool n) +{ + double r2 = (p1.point.x - p2.point.x) * (p1.point.x - p2.point.x); + r2 += (p1.point.y - p2.point.y) * (p1.point.y - p2.point.y); + r2 += (p1.point.z - p2.point.z) * (p1.point.z - p2.point.z); + double vol(1.0); + if (n) + { + if(((p1.func == AROM) || (p1.func == HYBL)) + && ((p2.func == AROM) || (p2.func == HYBL)) + && ( p1.hasNormal ) + && ( p2.hasNormal )) + { + vol = fabs(cosine(p1.normal, p2.normal)); + } + else if(((p1.func == HACC) || (p1.func == HDON) || (p1.func == HYBH)) + && ((p2.func == HACC) || (p2.func == HDON) || (p2.func == HYBH)) + && ( p1.hasNormal ) + && ( p2.hasNormal )) + { + vol = cosine(p1.normal, p2.normal); + } + } + + vol *= GCI2 * pow(PI/(p1.alpha + p2.alpha), 1.5); + vol *= exp(-(p1.alpha * p2.alpha) * r2/(p1.alpha + p2.alpha)); + + return vol; +} + + + +double +VolumeOverlap(PharmacophorePoint* p1, PharmacophorePoint* p2, bool n) +{ + double r2 = (p1->point.x - p2->point.x) * (p1->point.x - p2->point.x); + r2 += (p1->point.y - p2->point.y) * (p1->point.y - p2->point.y); + r2 += (p1->point.z - p2->point.z) * (p1->point.z - p2->point.z); + double vol(1.0); + if (n) + { + if(((p1->func == AROM) || (p1->func == HYBL)) + && ((p2->func == AROM) || (p2->func == HYBL)) + && ( p1->hasNormal ) + && ( p2->hasNormal )) + { + vol = fabs(cosine(p1->normal, p2->normal)); + } + else if(((p1->func == HACC) || (p1->func == HDON) || (p1->func == HYBH)) + && ((p2->func == HACC) || (p2->func == HDON) || (p2->func == HYBH)) + && ( p1->hasNormal ) + && ( p2->hasNormal )) + { + vol = cosine(p1->normal, p2->normal); + } + } + vol *= GCI2 * pow(PI/(p1->alpha + p2->alpha), 1.5); + vol *= exp(-(p1->alpha * p2->alpha) * r2/(p1->alpha + p2->alpha)); + + return vol; +} + + + +void +positionPharmacophore(Pharmacophore& pharm, SiMath::Matrix& U, SolutionInfo& s) +{ + // transpose of rotation matrix + SiMath::Matrix rt = s.rotation2.transpose(); + + for (int i(0); i < pharm.size(); ++i) + { + // translate normal origin + pharm[i].normal.x -= pharm[i].point.x; + pharm[i].normal.y -= pharm[i].point.y; + pharm[i].normal.z -= pharm[i].point.z; + + // translate pharmacophore to center of db pharm + pharm[i].point.x -= s.center2.x; + pharm[i].point.y -= s.center2.y; + pharm[i].point.z -= s.center2.z; + + // align with main axes + pharm[i].point = rotate(pharm[i].point, rt); + pharm[i].normal = rotate(pharm[i].normal, rt); + + // rotate according to best rotor + pharm[i].point = rotate(pharm[i].point, U); + pharm[i].normal = rotate(pharm[i].normal, U); + + // rotate back to main axes of the reference + pharm[i].point = rotate(pharm[i].point, s.rotation1); + pharm[i].normal = rotate(pharm[i].normal, s.rotation1); + + // move to center of reference + pharm[i].point.x += s.center1.x; + pharm[i].point.y += s.center1.y; + pharm[i].point.z += s.center1.z; + + // translate normal back from origin + pharm[i].normal.x += pharm[i].point.x; + pharm[i].normal.y += pharm[i].point.y; + pharm[i].normal.z += pharm[i].point.z; + + } + return; +} + + + +void +positionMolecule(OpenBabel::OBMol* m, SiMath::Matrix& U, SolutionInfo& s) +{ + // transpose of rotation matrix + SiMath::Matrix rt = s.rotation2.transpose(); + + Coordinate point; + std::vector::iterator ai; + for (OpenBabel::OBAtom* a = m->BeginAtom(ai); a; a = m->NextAtom(ai)) + { + point.x = a->x(); + point.y = a->y(); + point.z = a->z(); + + point.x -= s.center2.x; + point.y -= s.center2.y; + point.z -= s.center2.z; + + point = rotate(point, rt); + point = rotate(point, U); + point = rotate(point, s.rotation1); + + point.x += s.center1.x; + point.y += s.center1.y; + point.z += s.center1.z; + + a->SetVector(point.x, point.y, point.z); + } + + return; +} + + + +void +TransformPharmacophore(Pharmacophore& pharm, SiMath::Matrix& U, Coordinate& center1, Coordinate& center2) +{ + for (int i(0); i < pharm.size(); ++i) + { + PharmacophorePoint pp(pharm[i]); + + // translate and rotate normal[0] + pharm[i].normal.x -= pharm[i].point.x; + pharm[i].normal.y -= pharm[i].point.y; + pharm[i].normal.z -= pharm[i].point.z; + + // translate and rotate pharmacophore center + pharm[i].point.x -= center2.x; + pharm[i].point.y -= center2.y; + pharm[i].point.z -= center2.z; + pharm[i].point = rotate(pharm[i].point, U); + pharm[i].point.x += center1.x; + pharm[i].point.y += center1.y; + pharm[i].point.z += center1.z; + + pharm[i].normal = rotate(pharm[i].normal, U); + pharm[i].normal.x += pharm[i].point.x; + pharm[i].normal.y += pharm[i].point.y; + pharm[i].normal.z += pharm[i].point.z; + } + return; +} + + + +void +TransformMolecule(OpenBabel::OBMol* m, SiMath::Matrix& U, Coordinate& center1, Coordinate& center2) +{ + Coordinate point; + std::vector::iterator ai; + for (OpenBabel::OBAtom* a = m->BeginAtom(ai); a; a = m->NextAtom(ai)) + { + point.x = a->x(); + point.y = a->y(); + point.z = a->z(); + + point.x -= center2.x; + point.y -= center2.y; + point.z -= center2.z; + + point = rotate(point, U); + + point.x += center1.x; + point.y += center1.y; + point.z += center1.z; + + a->SetVector(point.x, point.y, point.z); + } + return; +} + +","C++" +"In Silico","baoilleach/pharao","src/getopt.c",".c","40694","1275","/* Getopt for GNU. + NOTE: getopt is now part of the C library, so if you don't know what + ""Keep this file name-space clean"" means, talk to drepper@gnu.org + before changing it! + Copyright (C) 1987,88,89,90,91,92,93,94,95,96,98,99,2000,2001 + Free Software Foundation, Inc. + This file is part of the GNU C Library. + + The GNU C Library is free software; you can redistribute it and/or + modify it under the terms of the GNU Lesser General Public + License as published by the Free Software Foundation; either + version 2.1 of the License, or (at your option) any later version. + + The GNU C Library 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 + Lesser General Public License for more details. + + You should have received a copy of the GNU Lesser General Public + License along with the GNU C Library; if not, write to the Free + Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA + 02111-1307 USA. */ + +// Avoid warnings under MinGW about strlen +#include + +/* This tells Alpha OSF/1 not to define a getopt prototype in . + Ditto for AIX 3.2 and . */ +#ifndef _NO_PROTO +# define _NO_PROTO +#endif + +#ifdef HAVE_CONFIG_H +# include +#endif + +#if !defined __STDC__ || !__STDC__ +/* This is a separate conditional since some stdc systems + reject `defined (const)'. */ +# ifndef const +# define const +# endif +#endif + +#include + +/* Comment out all this code if we are using the GNU C Library, and are not + actually compiling the library itself. This code is part of the GNU C + Library, but also included in many other GNU distributions. Compiling + and linking in this code is a waste when using the GNU C library + (especially if it is a shared library). Rather than having every GNU + program understand `configure --with-gnu-libc' and omit the object files, + it is simpler to just do this in the source for each such file. */ + +#define GETOPT_INTERFACE_VERSION 2 +#if !defined _LIBC && defined __GLIBC__ && __GLIBC__ >= 2 +# include +# if _GNU_GETOPT_INTERFACE_VERSION == GETOPT_INTERFACE_VERSION +# define ELIDE_CODE +# endif +#endif + +#ifndef ELIDE_CODE + + +/* This needs to come after some library #include + to get __GNU_LIBRARY__ defined. */ +#ifdef __GNU_LIBRARY__ +/* Don't include stdlib.h for non-GNU C libraries because some of them + contain conflicting prototypes for getopt. */ +# include +# include +#endif /* GNU C library. */ + +#ifdef VMS +# include +# if HAVE_STRING_H - 0 +# include +# endif +#endif + +#ifndef _ +/* This is for other GNU distributions with internationalized messages. */ +# if (HAVE_LIBINTL_H && ENABLE_NLS) || defined _LIBC +# include +# ifndef _ +# define _(msgid) gettext (msgid) +# endif +# else +# define _(msgid) (msgid) +# endif +# if defined _LIBC && defined USE_IN_LIBIO +# include +# endif +#endif + +/* This version of `getopt' appears to the caller like standard Unix `getopt' + but it behaves differently for the user, since it allows the user + to intersperse the options with the other arguments. + + As `getopt' works, it permutes the elements of ARGV so that, + when it is done, all the options precede everything else. Thus + all application programs are extended to handle flexible argument order. + + Setting the environment variable POSIXLY_CORRECT disables permutation. + Then the behavior is completely standard. + + GNU application programs can use a third alternative mode in which + they can distinguish the relative order of options and other arguments. */ + +#include ""getopt.h"" + +/* For communication from `getopt' to the caller. + When `getopt' finds an option that takes an argument, + the argument value is returned here. + Also, when `ordering' is RETURN_IN_ORDER, + each non-option ARGV-element is returned here. */ + +char *optarg; + +/* Index in ARGV of the next element to be scanned. + This is used for communication to and from the caller + and for communication between successive calls to `getopt'. + + On entry to `getopt', zero means this is the first call; initialize. + + When `getopt' returns -1, this is the index of the first of the + non-option elements that the caller should itself scan. + + Otherwise, `optind' communicates from one call to the next + how much of ARGV has been scanned so far. */ + +/* 1003.2 says this must be 1 before any call. */ +int optind = 1; + +/* Formerly, initialization of getopt depended on optind==0, which + causes problems with re-calling getopt as programs generally don't + know that. */ + +int __getopt_initialized; + +/* The next char to be scanned in the option-element + in which the last option character we returned was found. + This allows us to pick up the scan where we left off. + + If this is zero, or a null string, it means resume the scan + by advancing to the next ARGV-element. */ + +static char *nextchar; + +/* Callers store zero here to inhibit the error message + for unrecognized options. */ + +int opterr = 1; + +/* Set to an option character which was unrecognized. + This must be initialized on some systems to avoid linking in the + system's own getopt implementation. */ + +int optopt = '?'; + +/* Describe how to deal with options that follow non-option ARGV-elements. + + If the caller did not specify anything, + the default is REQUIRE_ORDER if the environment variable + POSIXLY_CORRECT is defined, PERMUTE otherwise. + + REQUIRE_ORDER means don't recognize them as options; + stop option processing when the first non-option is seen. + This is what Unix does. + This mode of operation is selected by either setting the environment + variable POSIXLY_CORRECT, or using `+' as the first character + of the list of option characters. + + PERMUTE is the default. We permute the contents of ARGV as we scan, + so that eventually all the non-options are at the end. This allows options + to be given in any order, even with programs that were not written to + expect this. + + RETURN_IN_ORDER is an option available to programs that were written + to expect options and other ARGV-elements in any order and that care about + the ordering of the two. We describe each non-option ARGV-element + as if it were the argument of an option with character code 1. + Using `-' as the first character of the list of option characters + selects this mode of operation. + + The special argument `--' forces an end of option-scanning regardless + of the value of `ordering'. In the case of RETURN_IN_ORDER, only + `--' can cause `getopt' to return -1 with `optind' != ARGC. */ + +static enum +{ + REQUIRE_ORDER, PERMUTE, RETURN_IN_ORDER +} ordering; + +/* Value of POSIXLY_CORRECT environment variable. */ +static char *posixly_correct; + +#ifdef __GNU_LIBRARY__ +/* We want to avoid inclusion of string.h with non-GNU libraries + because there are many ways it can cause trouble. + On some systems, it contains special magic macros that don't work + in GCC. */ +# include +# define my_index strchr +#else +/* +# if HAVE_STRING_H || WIN32 // Pete Wilson mod 7/28/02 +# include +# else +# include +# endif +*/ +/* Avoid depending on library functions or files + whose names are inconsistent. */ + +#ifndef getenv +extern char *getenv (); +#endif + +static char * +my_index (str, chr) + const char *str; + int chr; +{ + while (*str) + { + if (*str == chr) + return (char *) str; + str++; + } + return 0; +} + +/* If using GCC, we can safely declare strlen this way. + If not using GCC, it is ok not to declare it. */ +#ifdef __GNUC__ +/* Note that Motorola Delta 68k R3V7 comes with GCC but not stddef.h. + That was relevant to code that was here before. */ +# if (!defined __STDC__ || !__STDC__) && !defined strlen +/* gcc with -traditional declares the built-in strlen to return int, + and has done so at least since version 2.4.5. -- rms. */ +extern int strlen (const char *); +# endif /* not __STDC__ */ +#endif /* __GNUC__ */ + +#endif /* not __GNU_LIBRARY__ */ + +/* Handle permutation of arguments. */ + +/* Describe the part of ARGV that contains non-options that have + been skipped. `first_nonopt' is the index in ARGV of the first of them; + `last_nonopt' is the index after the last of them. */ + +static int first_nonopt; +static int last_nonopt; + +#ifdef _LIBC +/* Stored original parameters. + XXX This is no good solution. We should rather copy the args so + that we can compare them later. But we must not use malloc(3). */ +extern int __libc_argc; +extern char **__libc_argv; + +/* Bash 2.0 gives us an environment variable containing flags + indicating ARGV elements that should not be considered arguments. */ + +# ifdef USE_NONOPTION_FLAGS +/* Defined in getopt_init.c */ +extern char *__getopt_nonoption_flags; + +static int nonoption_flags_max_len; +static int nonoption_flags_len; +# endif + +# ifdef USE_NONOPTION_FLAGS +# define SWAP_FLAGS(ch1, ch2) \ + if (nonoption_flags_len > 0) \ + { \ + char __tmp = __getopt_nonoption_flags[ch1]; \ + __getopt_nonoption_flags[ch1] = __getopt_nonoption_flags[ch2]; \ + __getopt_nonoption_flags[ch2] = __tmp; \ + } +# else +# define SWAP_FLAGS(ch1, ch2) +# endif +#else /* !_LIBC */ +# define SWAP_FLAGS(ch1, ch2) +#endif /* _LIBC */ + +/* Exchange two adjacent subsequences of ARGV. + One subsequence is elements [first_nonopt,last_nonopt) + which contains all the non-options that have been skipped so far. + The other is elements [last_nonopt,optind), which contains all + the options processed since those non-options were skipped. + + `first_nonopt' and `last_nonopt' are relocated so that they describe + the new indices of the non-options in ARGV after they are moved. */ + +#if defined __STDC__ && __STDC__ +static void exchange (char **); +#endif + +static void +exchange (argv) + char **argv; +{ + int bottom = first_nonopt; + int middle = last_nonopt; + int top = optind; + char *tem; + + /* Exchange the shorter segment with the far end of the longer segment. + That puts the shorter segment into the right place. + It leaves the longer segment in the right place overall, + but it consists of two parts that need to be swapped next. */ + +#if defined _LIBC && defined USE_NONOPTION_FLAGS + /* First make sure the handling of the `__getopt_nonoption_flags' + string can work normally. Our top argument must be in the range + of the string. */ + if (nonoption_flags_len > 0 && top >= nonoption_flags_max_len) + { + /* We must extend the array. The user plays games with us and + presents new arguments. */ + char *new_str = malloc (top + 1); + if (new_str == NULL) + nonoption_flags_len = nonoption_flags_max_len = 0; + else + { + memset (__mempcpy (new_str, __getopt_nonoption_flags, + nonoption_flags_max_len), + '\0', top + 1 - nonoption_flags_max_len); + nonoption_flags_max_len = top + 1; + __getopt_nonoption_flags = new_str; + } + } +#endif + + while (top > middle && middle > bottom) + { + if (top - middle > middle - bottom) + { + /* Bottom segment is the short one. */ + int len = middle - bottom; + register int i; + + /* Swap it with the top part of the top segment. */ + for (i = 0; i < len; i++) + { + tem = argv[bottom + i]; + argv[bottom + i] = argv[top - (middle - bottom) + i]; + argv[top - (middle - bottom) + i] = tem; + SWAP_FLAGS (bottom + i, top - (middle - bottom) + i); + } + /* Exclude the moved bottom segment from further swapping. */ + top -= len; + } + else + { + /* Top segment is the short one. */ + int len = top - middle; + register int i; + + /* Swap it with the bottom part of the bottom segment. */ + for (i = 0; i < len; i++) + { + tem = argv[bottom + i]; + argv[bottom + i] = argv[middle + i]; + argv[middle + i] = tem; + SWAP_FLAGS (bottom + i, middle + i); + } + /* Exclude the moved top segment from further swapping. */ + bottom += len; + } + } + + /* Update records for the slots the non-options now occupy. */ + + first_nonopt += (optind - last_nonopt); + last_nonopt = optind; +} + +/* Initialize the internal data when the first call is made. */ + +#if defined __STDC__ && __STDC__ +static const char *_getopt_initialize (int, char *const *, const char *); +#endif +static const char * +_getopt_initialize (argc, argv, optstring) + int argc; + char *const *argv; + const char *optstring; +{ + /* Start processing options with ARGV-element 1 (since ARGV-element 0 + is the program name); the sequence of previously skipped + non-option ARGV-elements is empty. */ + + first_nonopt = last_nonopt = optind; + + nextchar = NULL; + + posixly_correct = getenv (""POSIXLY_CORRECT""); + + /* Determine how to handle the ordering of options and nonoptions. */ + + if (optstring[0] == '-') + { + ordering = RETURN_IN_ORDER; + ++optstring; + } + else if (optstring[0] == '+') + { + ordering = REQUIRE_ORDER; + ++optstring; + } + else if (posixly_correct != NULL) + ordering = REQUIRE_ORDER; + else + ordering = PERMUTE; + +#if defined _LIBC && defined USE_NONOPTION_FLAGS + if (posixly_correct == NULL + && argc == __libc_argc && argv == __libc_argv) + { + if (nonoption_flags_max_len == 0) + { + if (__getopt_nonoption_flags == NULL + || __getopt_nonoption_flags[0] == '\0') + nonoption_flags_max_len = -1; + else + { + const char *orig_str = __getopt_nonoption_flags; + int len = nonoption_flags_max_len = strlen (orig_str); + if (nonoption_flags_max_len < argc) + nonoption_flags_max_len = argc; + __getopt_nonoption_flags = + (char *) malloc (nonoption_flags_max_len); + if (__getopt_nonoption_flags == NULL) + nonoption_flags_max_len = -1; + else + memset (__mempcpy (__getopt_nonoption_flags, orig_str, len), + '\0', nonoption_flags_max_len - len); + } + } + nonoption_flags_len = nonoption_flags_max_len; + } + else + nonoption_flags_len = 0; +#endif + + return optstring; +} + +/* Scan elements of ARGV (whose length is ARGC) for option characters + given in OPTSTRING. + + If an element of ARGV starts with '-', and is not exactly ""-"" or ""--"", + then it is an option element. The characters of this element + (aside from the initial '-') are option characters. If `getopt' + is called repeatedly, it returns successively each of the option characters + from each of the option elements. + + If `getopt' finds another option character, it returns that character, + updating `optind' and `nextchar' so that the next call to `getopt' can + resume the scan with the following option character or ARGV-element. + + If there are no more option characters, `getopt' returns -1. + Then `optind' is the index in ARGV of the first ARGV-element + that is not an option. (The ARGV-elements have been permuted + so that those that are not options now come last.) + + OPTSTRING is a string containing the legitimate option characters. + If an option character is seen that is not listed in OPTSTRING, + return '?' after printing an error message. If you set `opterr' to + zero, the error message is suppressed but we still return '?'. + + If a char in OPTSTRING is followed by a colon, that means it wants an arg, + so the following text in the same ARGV-element, or the text of the following + ARGV-element, is returned in `optarg'. Two colons mean an option that + wants an optional arg; if there is text in the current ARGV-element, + it is returned in `optarg', otherwise `optarg' is set to zero. + + If OPTSTRING starts with `-' or `+', it requests different methods of + handling the non-option ARGV-elements. + See the comments about RETURN_IN_ORDER and REQUIRE_ORDER, above. + + Long-named options begin with `--' instead of `-'. + Their names may be abbreviated as long as the abbreviation is unique + or is an exact match for some defined option. If they have an + argument, it follows the option name in the same ARGV-element, separated + from the option name by a `=', or else the in next ARGV-element. + When `getopt' finds a long-named option, it returns 0 if that option's + `flag' field is nonzero, the value of the option's `val' field + if the `flag' field is zero. + + The elements of ARGV aren't really const, because we permute them. + But we pretend they're const in the prototype to be compatible + with other systems. + + LONGOPTS is a vector of `struct option' terminated by an + element containing a name which is zero. + + LONGIND returns the index in LONGOPT of the long-named option found. + It is only valid when a long-named option has been found by the most + recent call. + + If LONG_ONLY is nonzero, '-' as well as '--' can introduce + long-named options. */ + +int +_getopt_internal (argc, argv, optstring, longopts, longind, long_only) + int argc; + char *const *argv; + const char *optstring; + const struct option *longopts; + int *longind; + int long_only; +{ + int print_errors = opterr; + if (optstring[0] == ':') + print_errors = 0; + + if (argc < 1) + return -1; + + optarg = NULL; + + if (optind == 0 || !__getopt_initialized) + { + if (optind == 0) + optind = 1; /* Don't scan ARGV[0], the program name. */ + optstring = _getopt_initialize (argc, argv, optstring); + __getopt_initialized = 1; + } + + /* Test whether ARGV[optind] points to a non-option argument. + Either it does not have option syntax, or there is an environment flag + from the shell indicating it is not an option. The later information + is only used when the used in the GNU libc. */ +#if defined _LIBC && defined USE_NONOPTION_FLAGS +# define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0' \ + || (optind < nonoption_flags_len \ + && __getopt_nonoption_flags[optind] == '1')) +#else +# define NONOPTION_P (argv[optind][0] != '-' || argv[optind][1] == '\0') +#endif + + if (nextchar == NULL || *nextchar == '\0') + { + /* Advance to the next ARGV-element. */ + + /* Give FIRST_NONOPT and LAST_NONOPT rational values if OPTIND has been + moved back by the user (who may also have changed the arguments). */ + if (last_nonopt > optind) + last_nonopt = optind; + if (first_nonopt > optind) + first_nonopt = optind; + + if (ordering == PERMUTE) + { + /* If we have just processed some options following some non-options, + exchange them so that the options come first. */ + + if (first_nonopt != last_nonopt && last_nonopt != optind) + exchange ((char **) argv); + else if (last_nonopt != optind) + first_nonopt = optind; + + /* Skip any additional non-options + and extend the range of non-options previously skipped. */ + + while (optind < argc && NONOPTION_P) + optind++; + last_nonopt = optind; + } + + /* The special ARGV-element `--' means premature end of options. + Skip it like a null option, + then exchange with previous non-options as if it were an option, + then skip everything else like a non-option. */ + + if (optind != argc && !strcmp (argv[optind], ""--"")) + { + optind++; + + if (first_nonopt != last_nonopt && last_nonopt != optind) + exchange ((char **) argv); + else if (first_nonopt == last_nonopt) + first_nonopt = optind; + last_nonopt = argc; + + optind = argc; + } + + /* If we have done all the ARGV-elements, stop the scan + and back over any non-options that we skipped and permuted. */ + + if (optind == argc) + { + /* Set the next-arg-index to point at the non-options + that we previously skipped, so the caller will digest them. */ + if (first_nonopt != last_nonopt) + optind = first_nonopt; + return -1; + } + + /* If we have come to a non-option and did not permute it, + either stop the scan or describe it to the caller and pass it by. */ + + if (NONOPTION_P) + { + if (ordering == REQUIRE_ORDER) + return -1; + optarg = argv[optind++]; + return 1; + } + + /* We have found another option-ARGV-element. + Skip the initial punctuation. */ + + nextchar = (argv[optind] + 1 + + (longopts != NULL && argv[optind][1] == '-')); + } + + /* Decode the current option-ARGV-element. */ + + /* Check whether the ARGV-element is a long option. + + If long_only and the ARGV-element has the form ""-f"", where f is + a valid short option, don't consider it an abbreviated form of + a long option that starts with f. Otherwise there would be no + way to give the -f short option. + + On the other hand, if there's a long option ""fubar"" and + the ARGV-element is ""-fu"", do consider that an abbreviation of + the long option, just like ""--fu"", and not ""-f"" with arg ""u"". + + This distinction seems to be the most useful approach. */ + + if (longopts != NULL + && (argv[optind][1] == '-' + || (long_only && (argv[optind][2] || !my_index (optstring, argv[optind][1]))))) + { + char *nameend; + const struct option *p; + const struct option *pfound = NULL; + int exact = 0; + int ambig = 0; + int indfound = -1; + int option_index; + + for (nameend = nextchar; *nameend && *nameend != '='; nameend++) + /* Do nothing. */ ; + + /* Test all long options for either exact match + or abbreviated matches. */ + for (p = longopts, option_index = 0; p->name; p++, option_index++) + if (!strncmp (p->name, nextchar, nameend - nextchar)) + { + if ((unsigned int) (nameend - nextchar) + == (unsigned int) strlen (p->name)) + { + /* Exact match found. */ + pfound = p; + indfound = option_index; + exact = 1; + break; + } + else if (pfound == NULL) + { + /* First nonexact match found. */ + pfound = p; + indfound = option_index; + } + else if (long_only + || pfound->has_arg != p->has_arg + || pfound->flag != p->flag + || pfound->val != p->val) + /* Second or later nonexact match found. */ + ambig = 1; + } + + if (ambig && !exact) + { + if (print_errors) + { +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; + + __asprintf (&buf, _(""%s: option `%s' is ambiguous\n""), + argv[0], argv[optind]); + + if (_IO_fwide (stderr, 0) > 0) + __fwprintf (stderr, L""%s"", buf); + else + fputs (buf, stderr); + + free (buf); +#else + fprintf (stderr, _(""%s: option `%s' is ambiguous\n""), + argv[0], argv[optind]); +#endif + } + nextchar += strlen (nextchar); + optind++; + optopt = 0; + return '?'; + } + + if (pfound != NULL) + { + option_index = indfound; + optind++; + if (*nameend) + { + /* Don't test has_arg with >, because some C compilers don't + allow it to be used on enums. */ + if (pfound->has_arg) + optarg = nameend + 1; + else + { + if (print_errors) + { +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; +#endif + + if (argv[optind - 1][1] == '-') + { + /* --option */ +#if defined _LIBC && defined USE_IN_LIBIO + __asprintf (&buf, _(""\ +%s: option `--%s' doesn't allow an argument\n""), + argv[0], pfound->name); +#else + fprintf (stderr, _(""\ +%s: option `--%s' doesn't allow an argument\n""), + argv[0], pfound->name); +#endif + } + else + { + /* +option or -option */ +#if defined _LIBC && defined USE_IN_LIBIO + __asprintf (&buf, _(""\ +%s: option `%c%s' doesn't allow an argument\n""), + argv[0], argv[optind - 1][0], + pfound->name); +#else + fprintf (stderr, _(""\ +%s: option `%c%s' doesn't allow an argument\n""), + argv[0], argv[optind - 1][0], pfound->name); +#endif + } + +#if defined _LIBC && defined USE_IN_LIBIO + if (_IO_fwide (stderr, 0) > 0) + __fwprintf (stderr, L""%s"", buf); + else + fputs (buf, stderr); + + free (buf); +#endif + } + + nextchar += strlen (nextchar); + + optopt = pfound->val; + return '?'; + } + } + else if (pfound->has_arg == 1) + { + if (optind < argc) + optarg = argv[optind++]; + else + { + if (print_errors) + { +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; + + __asprintf (&buf, + _(""%s: option `%s' requires an argument\n""), + argv[0], argv[optind - 1]); + + if (_IO_fwide (stderr, 0) > 0) + __fwprintf (stderr, L""%s"", buf); + else + fputs (buf, stderr); + + free (buf); +#else + fprintf (stderr, + _(""%s: option `%s' requires an argument\n""), + argv[0], argv[optind - 1]); +#endif + } + nextchar += strlen (nextchar); + optopt = pfound->val; + return optstring[0] == ':' ? ':' : '?'; + } + } + nextchar += strlen (nextchar); + if (longind != NULL) + *longind = option_index; + if (pfound->flag) + { + *(pfound->flag) = pfound->val; + return 0; + } + return pfound->val; + } + + /* Can't find it as a long option. If this is not getopt_long_only, + or the option starts with '--' or is not a valid short + option, then it's an error. + Otherwise interpret it as a short option. */ + if (!long_only || argv[optind][1] == '-' + || my_index (optstring, *nextchar) == NULL) + { + if (print_errors) + { +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; +#endif + + if (argv[optind][1] == '-') + { + /* --option */ +#if defined _LIBC && defined USE_IN_LIBIO + __asprintf (&buf, _(""%s: unrecognized option `--%s'\n""), + argv[0], nextchar); +#else + fprintf (stderr, _(""%s: unrecognized option `--%s'\n""), + argv[0], nextchar); +#endif + } + else + { + /* +option or -option */ +#if defined _LIBC && defined USE_IN_LIBIO + __asprintf (&buf, _(""%s: unrecognized option `%c%s'\n""), + argv[0], argv[optind][0], nextchar); +#else + fprintf (stderr, _(""%s: unrecognized option `%c%s'\n""), + argv[0], argv[optind][0], nextchar); +#endif + } + +#if defined _LIBC && defined USE_IN_LIBIO + if (_IO_fwide (stderr, 0) > 0) + __fwprintf (stderr, L""%s"", buf); + else + fputs (buf, stderr); + + free (buf); +#endif + } + nextchar = (char *) """"; + optind++; + optopt = 0; + return '?'; + } + } + + /* Look at and handle the next short option-character. */ + + { + char c = *nextchar++; + char *temp = my_index (optstring, c); + + /* Increment `optind' when we start to process its last character. */ + if (*nextchar == '\0') + ++optind; + + if (temp == NULL || c == ':') + { + if (print_errors) + { +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; +#endif + + if (posixly_correct) + { + /* 1003.2 specifies the format of this message. */ +#if defined _LIBC && defined USE_IN_LIBIO + __asprintf (&buf, _(""%s: illegal option -- %c\n""), + argv[0], c); +#else + fprintf (stderr, _(""%s: illegal option -- %c\n""), argv[0], c); +#endif + } + else + { +#if defined _LIBC && defined USE_IN_LIBIO + __asprintf (&buf, _(""%s: invalid option -- %c\n""), + argv[0], c); +#else + fprintf (stderr, _(""%s: invalid option -- %c\n""), argv[0], c); +#endif + } + +#if defined _LIBC && defined USE_IN_LIBIO + if (_IO_fwide (stderr, 0) > 0) + __fwprintf (stderr, L""%s"", buf); + else + fputs (buf, stderr); + + free (buf); +#endif + } + optopt = c; + return '?'; + } + /* Convenience. Treat POSIX -W foo same as long option --foo */ + if (temp[0] == 'W' && temp[1] == ';') + { + char *nameend; + const struct option *p; + const struct option *pfound = NULL; + int exact = 0; + int ambig = 0; + int indfound = 0; + int option_index; + + /* This is an option that requires an argument. */ + if (*nextchar != '\0') + { + optarg = nextchar; + /* If we end this ARGV-element by taking the rest as an arg, + we must advance to the next element now. */ + optind++; + } + else if (optind == argc) + { + if (print_errors) + { + /* 1003.2 specifies the format of this message. */ +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; + + __asprintf (&buf, _(""%s: option requires an argument -- %c\n""), + argv[0], c); + + if (_IO_fwide (stderr, 0) > 0) + __fwprintf (stderr, L""%s"", buf); + else + fputs (buf, stderr); + + free (buf); +#else + fprintf (stderr, _(""%s: option requires an argument -- %c\n""), + argv[0], c); +#endif + } + optopt = c; + if (optstring[0] == ':') + c = ':'; + else + c = '?'; + return c; + } + else + /* We already incremented `optind' once; + increment it again when taking next ARGV-elt as argument. */ + optarg = argv[optind++]; + + /* optarg is now the argument, see if it's in the + table of longopts. */ + + for (nextchar = nameend = optarg; *nameend && *nameend != '='; nameend++) + /* Do nothing. */ ; + + /* Test all long options for either exact match + or abbreviated matches. */ + for (p = longopts, option_index = 0; p->name; p++, option_index++) + if (!strncmp (p->name, nextchar, nameend - nextchar)) + { + if ((unsigned int) (nameend - nextchar) == strlen (p->name)) + { + /* Exact match found. */ + pfound = p; + indfound = option_index; + exact = 1; + break; + } + else if (pfound == NULL) + { + /* First nonexact match found. */ + pfound = p; + indfound = option_index; + } + else + /* Second or later nonexact match found. */ + ambig = 1; + } + if (ambig && !exact) + { + if (print_errors) + { +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; + + __asprintf (&buf, _(""%s: option `-W %s' is ambiguous\n""), + argv[0], argv[optind]); + + if (_IO_fwide (stderr, 0) > 0) + __fwprintf (stderr, L""%s"", buf); + else + fputs (buf, stderr); + + free (buf); +#else + fprintf (stderr, _(""%s: option `-W %s' is ambiguous\n""), + argv[0], argv[optind]); +#endif + } + nextchar += strlen (nextchar); + optind++; + return '?'; + } + if (pfound != NULL) + { + option_index = indfound; + if (*nameend) + { + /* Don't test has_arg with >, because some C compilers don't + allow it to be used on enums. */ + if (pfound->has_arg) + optarg = nameend + 1; + else + { + if (print_errors) + { +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; + + __asprintf (&buf, _(""\ +%s: option `-W %s' doesn't allow an argument\n""), + argv[0], pfound->name); + + if (_IO_fwide (stderr, 0) > 0) + __fwprintf (stderr, L""%s"", buf); + else + fputs (buf, stderr); + + free (buf); +#else + fprintf (stderr, _(""\ +%s: option `-W %s' doesn't allow an argument\n""), + argv[0], pfound->name); +#endif + } + + nextchar += strlen (nextchar); + return '?'; + } + } + else if (pfound->has_arg == 1) + { + if (optind < argc) + optarg = argv[optind++]; + else + { + if (print_errors) + { +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; + + __asprintf (&buf, _(""\ +%s: option `%s' requires an argument\n""), + argv[0], argv[optind - 1]); + + if (_IO_fwide (stderr, 0) > 0) + __fwprintf (stderr, L""%s"", buf); + else + fputs (buf, stderr); + + free (buf); +#else + fprintf (stderr, + _(""%s: option `%s' requires an argument\n""), + argv[0], argv[optind - 1]); +#endif + } + nextchar += strlen (nextchar); + return optstring[0] == ':' ? ':' : '?'; + } + } + nextchar += strlen (nextchar); + if (longind != NULL) + *longind = option_index; + if (pfound->flag) + { + *(pfound->flag) = pfound->val; + return 0; + } + return pfound->val; + } + nextchar = NULL; + return 'W'; /* Let the application handle it. */ + } + if (temp[1] == ':') + { + if (temp[2] == ':') + { + /* This is an option that accepts an argument optionally. */ + if (*nextchar != '\0') + { + optarg = nextchar; + optind++; + } + else + optarg = NULL; + nextchar = NULL; + } + else + { + /* This is an option that requires an argument. */ + if (*nextchar != '\0') + { + optarg = nextchar; + /* If we end this ARGV-element by taking the rest as an arg, + we must advance to the next element now. */ + optind++; + } + else if (optind == argc) + { + if (print_errors) + { + /* 1003.2 specifies the format of this message. */ +#if defined _LIBC && defined USE_IN_LIBIO + char *buf; + + __asprintf (&buf, + _(""%s: option requires an argument -- %c\n""), + argv[0], c); + + if (_IO_fwide (stderr, 0) > 0) + __fwprintf (stderr, L""%s"", buf); + else + fputs (buf, stderr); + + free (buf); +#else + fprintf (stderr, + _(""%s: option requires an argument -- %c\n""), + argv[0], c); +#endif + } + optopt = c; + if (optstring[0] == ':') + c = ':'; + else + c = '?'; + } + else + /* We already incremented `optind' once; + increment it again when taking next ARGV-elt as argument. */ + optarg = argv[optind++]; + nextchar = NULL; + } + } + return c; + } +} + +int +getopt (argc, argv, optstring) + int argc; + char *const *argv; + const char *optstring; +{ + return _getopt_internal (argc, argv, optstring, + (const struct option *) 0, + (int *) 0, + 0); +} + +int +getopt_long (int ___argc, char *const *___argv, + const char *__shortopts, + const struct option *__longopts, int *__longind) +{ + return _getopt_internal (___argc, ___argv, + __shortopts, + __longopts, __longind, + 0); +} + +#endif /* Not ELIDE_CODE. */ + + +/* Compile with -DTEST to make an executable for use in testing + the above definition of `getopt'. */ + +/* #define TEST */ /* Pete Wilson mod 7/28/02 */ +#ifdef TEST + +#ifndef exit /* Pete Wilson mod 7/28/02 */ + int exit(int); /* Pete Wilson mod 7/28/02 */ +#endif /* Pete Wilson mod 7/28/02 */ + +int +main (argc, argv) + int argc; + char **argv; +{ + int c; + int digit_optind = 0; + + while (1) + { + int this_option_optind = optind ? optind : 1; + + c = getopt (argc, argv, ""abc:d:0123456789""); + if (c == -1) + break; + + switch (c) + { + case '0': + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + case '8': + case '9': + if (digit_optind != 0 && digit_optind != this_option_optind) + printf (""digits occur in two different argv-elements.\n""); + digit_optind = this_option_optind; + printf (""option %c\n"", c); + break; + + case 'a': + printf (""option a\n""); + break; + + case 'b': + printf (""option b\n""); + break; + + case 'c': + printf (""option c with value `%s'\n"", optarg); + break; + + case '?': + break; + + default: + printf (""?? getopt returned character code 0%o ??\n"", c); + } + } + + if (optind < argc) + { + printf (""non-option ARGV-elements: ""); + while (optind < argc) + printf (""%s "", argv[optind++]); + printf (""\n""); + } + + exit (0); +} + +#endif /* TEST */ + + +","C" +"In Silico","baoilleach/pharao","src/lipoFuncCalc.cpp",".cpp","16690","528","/******************************************************************************* +lipoFuncCalc.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""lipoFuncCalc.h"" +using OpenBabel::OBAtomAtomIter; + + +void +lipoFuncCalc(OpenBabel::OBMol* m, Pharmacophore* pharmacophore) +{ + // Make a copy of the partial charge of each atom, since here we store the values + std::vector pcharge; + pcharge.clear(); + std::vector::iterator ai; + for (OpenBabel::OBAtom* a = m->BeginAtom(ai); a; a = m->NextAtom(ai)) + { + pcharge.push_back(a->GetPartialCharge()); + } + + // Find for each atom the 'topology-dependent term': t + _lipoLabelAtoms(m); + + // Multiply 't' with the accessible surface 's' + for (OpenBabel::OBAtom* a = m->BeginAtom(ai); a; a = m->NextAtom(ai)) + { + if (a->GetAtomicNum() == 1) + { + continue; + } + double t = a->GetPartialCharge(); +// std::cout << a->GetIdx() << "" "" << t << "" "" << _lipoCalcAccSurf(a) << "" "" << _lipoCalcAccSurf(a) * t << ""\n""; + if (t != 0.0) + { + a->SetPartialCharge(_lipoCalcAccSurf(a) * t); + } + } + + // Finally calculate the lipophilic points + _lipoGroupAtoms(m, pharmacophore); + + // Reset partial charges + unsigned int i(0); + for (OpenBabel::OBAtom* atom = m->BeginAtom(ai); atom; atom = m->NextAtom(ai)) + { + atom->SetPartialCharge(pcharge[i]); + ++i; + } +} + + + +void +_lipoLabelAtoms(OpenBabel::OBMol* m) +{ + // Give all atoms default score of 1 + std::vector::iterator ai; + for (OpenBabel::OBAtom* atom = m->BeginAtom(ai); atom; atom = m->NextAtom(ai)) + { + atom->SetPartialCharge(1.0); + } + + // Decrease scores based on O,N,S and charged atoms + std::vector::iterator bi; + std::vector::iterator bi2; + for (OpenBabel::OBAtom* a = m->BeginAtom(ai); a; a = m->NextAtom(ai)) + { + switch (a->GetAtomicNum()) + { + //......................................................... + case 1: //................................................. + a->SetPartialCharge(0.0); // category 1 + break; + + //......................................................... + case 7: //................................................. + a->SetPartialCharge(0.0); // category 1 + if (a->IsAromatic()) + { + break; + } + _lipoLabelNeighbors(a, 0.25); // category 13 + if ((a->GetImplicitValence() - a->GetHvyValence()) !=0 ) + { + std::vector::iterator bi; + for (OpenBabel::OBBond* b = a->BeginBond(bi); b; b = a->NextBond(bi)) + { + OpenBabel::OBAtom* aa = b->GetNbrAtom(a); + aa->SetPartialCharge(0.0); // category 4 + _lipoLabelNeighbors(aa, 0.0); // category 4 + } + } + break; + + //......................................................... + case 8: //................................................. + a->SetPartialCharge(0.0); // category 1 + if (a->IsAromatic()) + { + break; + } + _lipoLabelNeighbors(a, 0.25); // category 13 + + for (OpenBabel::OBBond* b = a->BeginBond(bi); b; b = a->NextBond(bi)) + { + if (b->GetNbrAtom(a)->GetAtomicNum() == 1) + { + std::vector::iterator bi2; + for (OpenBabel::OBBond* b2 = a->BeginBond(bi2); b2; b2 = a->NextBond(bi2)) + { + OpenBabel::OBAtom* aa = b2->GetNbrAtom(a); + aa->SetPartialCharge(0.0); // category 4 + _lipoLabelNeighbors(aa, 0.0); // category 4 + } + } + if (b->GetBO() == 2) + { + OpenBabel::OBAtom* aa = b->GetNbrAtom(a); + aa->SetPartialCharge(0.0); // category 6 + for (OpenBabel::OBBond* b2 = aa->BeginBond(bi2); b2; b2 = aa->NextBond(bi2)) + { + OpenBabel::OBAtom* aaa = b2->GetNbrAtom(aa); + if (aaa == a) + { + continue; + } + aaa->SetPartialCharge(0.0); // category 6 + _lipoLabelNeighbors(aaa, 0.6); // category 9 + } + } + } + break; + + //......................................................... + case 16: //................................................ + for (OpenBabel::OBBond* b = a->BeginBond(bi); b; b = a->NextBond(bi)) + { + if (b->GetNbrAtom(a)->GetAtomicNum() == 1) + { + a->SetPartialCharge(0.0); // category 2 + _lipoLabelNeighbors(a, 0.0); // category 5 + } + + if (b->GetBO() == 2) + { + a->SetPartialCharge(0.0); // category 8 + _lipoLabelNeighbors(a, 0.6); // category 11 + } + } + + // we make the assumption that every S with valence > 2 can be found + // by counting the number of bonds. + if ((a->GetImplicitValence() - a->GetHvyValence()) > 2) + { + a->SetPartialCharge(0.0); // category 7 + for (OpenBabel::OBBond* b = a->BeginBond(bi); b; b = a->NextBond(bi)) + { + OpenBabel::OBAtom* aa = b->GetNbrAtom(a); + aa->SetPartialCharge(0.0); // category 7 + _lipoLabelNeighbors(aa, 0.6); // category 10 + } + } + break; + } + + if (a->GetFormalCharge() != 0) + { + for (OpenBabel::OBBond* b = a->BeginBond(bi); b; b = a->NextBond(bi)) + { + OpenBabel::OBAtom* aa = b->GetNbrAtom(a); + aa->SetPartialCharge(0.0); + _lipoLabelNeighbors(aa, 0.0); + } + } + } + + // Adjust combinations of scores (category 12 and 14) + for (OpenBabel::OBAtom* a = m->BeginAtom(ai); a; a = m->NextAtom(ai)) + { + double value = a->GetPartialCharge(); + if ((value == 0.36 || value < 0.25) && value != 0.15) + { + a->SetPartialCharge(0.0); // category 12 and 14 + } + } +} + + + +double +_lipoCalcAccSurf(OpenBabel::OBAtom* a) +{ + OpenBabel::OBElementTable et; + double radius = et.GetVdwRad(a->GetAtomicNum()); + + // Create sphere with uniformly distributed points + std::vector sphere; + std::vector::iterator itS; + + const double arclength(1.0 / sqrt(sqrt(3.0) * DENSITY)); + double dphi(arclength/radius); + int nlayer(ROUND(PI/dphi) + 1); + + double phi(0.0); + for (int i = 0; i < nlayer; ++i) + { + double rsinphi(radius*sin(phi)); + double z(radius*cos(phi)); + double dtheta((rsinphi==0) ? PI*2 : arclength/rsinphi); + int tmpNbrPoints(ROUND(PI*2/dtheta)); + if (tmpNbrPoints <= 0) + { + tmpNbrPoints = 1; + } + dtheta = PI*2 / tmpNbrPoints; + double theta((i%2) ? 0 : PI); + for (int j = 0; j < tmpNbrPoints ; ++j) + { + Coordinate coord; + coord.x = rsinphi*cos(theta) + a->x(); + coord.y = rsinphi*sin(theta) + a->y(); + coord.z = z + a->z(); + sphere.push_back(coord); + theta += dtheta; + if (theta > PI*2) + { + theta -= PI*2; + } + } + phi += dphi; + } + + // Define neighbors of atom + std::list aList(_lipoGetNeighbors(a)); + std::list::iterator itA; + + // Check for every sphere-point if it is accessible + int nbrAccSurfPoints(0); + double delta(PROBE_RADIUS/radius); + for (itS = sphere.begin(); itS != sphere.end(); ++itS) + { + Coordinate p; + p.x = ((itS->x - a->x()) * delta) + itS->x; + p.y = ((itS->y - a->y()) * delta) + itS->y; + p.z = ((itS->z - a->z()) * delta) + itS->z; + + bool isAccessible(true); + for (itA = aList.begin(); itA != aList.end(); ++itA) + { + OpenBabel::OBAtom* n(*itA); + double distSq(((p.x - n->x()) * (p.x - n->x())) + + ((p.y - n->y()) * (p.y - n->y())) + + ((p.z - n->z()) * (p.z - n->z()))); + double sumSq((PROBE_RADIUS + et.GetVdwRad(n->GetAtomicNum())) * + (PROBE_RADIUS + et.GetVdwRad(n->GetAtomicNum()))); + + if (distSq <= sumSq) + { + isAccessible = false; + break; + } + } + + if (isAccessible) ++nbrAccSurfPoints; + } + + double f(nbrAccSurfPoints/(double)sphere.size()); + return f * 4 * PI * radius*radius; +} + +bool HasZeroLipo(OpenBabel::OBAtom* atom) { + return (atom->GetPartialCharge() == 0.0); +} + +void +_lipoGroupAtoms(OpenBabel::OBMol* m, Pharmacophore* pharmacophore) +{ + std::set atomSet; // keeps remaining atoms for step (3) + std::set::iterator itS; + + std::vector::iterator ai; + for (OpenBabel::OBAtom* a = m->BeginAtom(ai); a; a = m->NextAtom(ai)) + { + atomSet.insert(a); + } + + // Group rings smaller than 7 + std::vector allrings = m->GetSSSR(); + std::vector::iterator ri; + OpenBabel::OBRing* ring; + for (ri = allrings.begin(); ri != allrings.end(); ++ri) + { + ring = *ri; + if (ring->Size() > 7) + { + continue; + } + + double lipoSum(0.0); + Coordinate center; + for (OpenBabel::OBAtom* atom = m->BeginAtom(ai); atom; atom = m->NextAtom(ai)) + { + if (ring->IsMember(atom)) + { + atomSet.erase(atom); + double lipo(atom->GetPartialCharge()); + lipoSum += lipo; + center.x += lipo * atom->x(); + center.y += lipo * atom->y(); + center.z += lipo * atom->z(); + } + else + { + continue; + } + } + + if (lipoSum > REF_LIPO) + { + PharmacophorePoint p; + p.func = LIPO; + p.hasNormal = false; + p.normal.x = 0.0; + p.normal.y = 0.0; + p.normal.z = 0.0; + p.alpha = funcSigma[LIPO]; + center.x /= lipoSum; + center.y /= lipoSum; + center.z /= lipoSum; + p.point = center; + pharmacophore->push_back(p); + } + } + + // Group atoms with three or more bonds + std::vector removeAtoms; + for (itS = atomSet.begin(); itS != atomSet.end(); ++itS) + { + if ((*itS)->GetHvyValence() > 2) + { + removeAtoms.push_back(*itS); + double lipoSum((*itS)->GetPartialCharge()); + Coordinate center; + center.x += lipoSum * (*itS)->x(); + center.y += lipoSum * (*itS)->y(); + center.z += lipoSum * (*itS)->z(); + + std::vector::iterator bi; + for (OpenBabel::OBBond* b = (*itS)->BeginBond(bi); b; b = (*itS)->NextBond(bi)) + { + OpenBabel::OBAtom* a = b->GetNbrAtom(*itS); + if (a->GetHvyValence() == 1 && a->GetAtomicNum() != 1) + { + double lipo(a->GetPartialCharge()); + lipoSum += lipo; + removeAtoms.push_back(a); + center.x += (lipo * a->x()); + center.y += (lipo * a->y()); + center.z += (lipo * a->z()); + } + } + + if (lipoSum > REF_LIPO) + { + PharmacophorePoint p; + p.func = LIPO; + p.hasNormal = false; + p.normal.x = 0.0; + p.normal.y = 0.0; + p.normal.z = 0.0; + p.alpha = funcSigma[LIPO]; + center.x /= lipoSum; + center.y /= lipoSum; + center.z /= lipoSum; + p.point = center; + pharmacophore->push_back(p); + } + } + } + + for (std::vector::const_iterator itV = removeAtoms.begin(); itV != removeAtoms.end(); ++itV) + atomSet.erase(*itV); + + // ********************************** + // Divide remaining atoms into chains + // ********************************** + + std::set natomSet; + std::remove_copy_if(atomSet.begin(), atomSet.end(), std::inserter(natomSet, natomSet.begin()), HasZeroLipo); + + OpenBabel::OBBitVec seen(m->NumAtoms() + 1); + for (itS = natomSet.begin(); itS != natomSet.end(); ++itS) + { + if (seen.BitIsSet((*itS)->GetIdx())) continue; // already seen + + // Only continue if this is a chain terminus + char chain_nbrs = 0; + FOR_NBORS_OF_ATOM(nbr, *itS) + if (natomSet.find(&*nbr) != natomSet.end()) chain_nbrs++; + if (chain_nbrs > 1) + continue; + + // Initialisation + OpenBabel::OBAtom* atom = *itS; + double lipoSum = 0.0; + Coordinate center; + std::vector oneBond; + bool first_pass = true; + + while(true) + { + if (atom == NULL || ((!first_pass) && (lipoSum + atom->GetPartialCharge()) > 2*REF_LIPO)) + { // Store this pharmacophore + PharmacophorePoint p; + p.func = LIPO; + p.hasNormal = false; + p.normal.x = 0.0; + p.normal.y = 0.0; + p.normal.z = 0.0; + p.alpha = funcSigma[LIPO]; + if (oneBond.size() == 1) + { + center.x = oneBond.at(0)->x(); + center.y = oneBond.at(0)->y(); + center.z = oneBond.at(0)->z(); + } + else + { + center.x /= lipoSum; + center.y /= lipoSum; + center.z /= lipoSum; + } + p.point = center; + pharmacophore->push_back(p); + if (atom == NULL) break; + + // Reset initialisation + lipoSum = 0.0; + center.x = center.y = center.z = 0; + oneBond.clear(); + } + + first_pass = false; + double lipo = atom->GetPartialCharge(); + lipoSum += lipo; + seen.SetBitOn(atom->GetIdx()); + center.x += (lipo * atom->x()); + center.y += (lipo * atom->y()); + center.z += (lipo * atom->z()); + if (atom->GetHvyValence() == 1) + oneBond.push_back(atom); + + // Move to the next atom along the chain or NULL + OpenBabel::OBAtom* next_atom = NULL; + FOR_NBORS_OF_ATOM(nbr, atom) + if (natomSet.find(&*nbr) != natomSet.end() && !seen.BitIsSet(nbr->GetIdx())) + { + next_atom = &*nbr; + break; + } + atom = next_atom; + } + } + +} + + + +std::list +_lipoGetNeighbors(OpenBabel::OBAtom* a) +{ + OpenBabel::OBElementTable et; + double radius = et.GetVdwRad(a->GetAtomicNum()); + std::list aList; + + OpenBabel::OBMol* parent(a->GetParent()); + std::vector::iterator ai; + for (OpenBabel::OBAtom* aa = parent->BeginAtom(ai); aa; aa = parent->NextAtom(ai)) + { + if ((aa->GetAtomicNum() == 1) || (aa == a)) + { + continue; + } + + double delta(radius + et.GetVdwRad(aa->GetAtomicNum()) + 2 * PROBE_RADIUS); + double maxDistSq(delta*delta); + double distSq((a->x() - aa->x()) * (a->x() - aa->x()) + + (a->y() - aa->y()) * (a->y() - aa->y()) + + (a->z() - aa->z()) * (a->z() - aa->z())); + + if (distSq <= maxDistSq) + { + aList.push_back(aa); + } + } + + return aList; +} + + + +void +_lipoLabelNeighbors(OpenBabel::OBAtom* a, double value) +{ + std::vector::iterator bi; + for (OpenBabel::OBBond* b = a->BeginBond(bi); b; b = a->NextBond(bi)) + { + OpenBabel::OBAtom* aa = b->GetNbrAtom(a); + aa->SetPartialCharge(value * aa->GetPartialCharge()); + } +} +","C++" +"In Silico","baoilleach/pharao","src/hybridCalc.cpp",".cpp","8621","236","/******************************************************************************* +hDonFuncCalc.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""hybridCalc.h"" + + + +void +hybridCalc(OpenBabel::OBMol* m, Pharmacophore* pharmacophore) +{ + + Pharmacophore::iterator itP; + Pharmacophore::iterator itP2; + for (itP = pharmacophore->begin(); itP != pharmacophore->end(); ++itP) + { + switch (itP->func) + { + //................................................................ + case AROM: + itP2 = itP; + ++itP2; + for( ; itP2 != pharmacophore->end(); ++itP2) + { + if (itP2->func == LIPO) + { + if (_hybridSameHybLPoint(itP2->point, itP->point)) + { + // modify first point + itP->func = HYBL; + itP->alpha = funcSigma[HYBL]; + itP->point.x = (itP->point.x + itP2->point.x) / 2.0; + itP->point.y = (itP->point.y + itP2->point.y) / 2.0; + itP->point.z = (itP->point.z + itP2->point.z) / 2.0; + itP->hasNormal = false; + itP->normal.x = 0.0; + itP->normal.y = 0.0; + itP->normal.z = 0.0; + + // remove second point + itP2 = pharmacophore->erase(itP2); + --itP2; + } + } + } + break; + + //................................................................ + case HACC: + itP2 = itP; + ++itP2; + for( ; itP2 != pharmacophore->end(); ++itP2) + { + if ((itP2->func == HDON) && (_hybridSameHybHPoint(itP2->point, itP->point))) + { + //modify first point + itP->func = HYBH; + itP->alpha = funcSigma[HYBH]; + + // Update normal + itP->normal.x = itP->normal.x - itP->point.x; + itP->normal.y = itP->normal.y - itP->point.y; + itP->normal.z = itP->normal.z - itP->point.z; + + itP2->normal.x = itP2->normal.x - itP2->point.x; + itP2->normal.y = itP2->normal.y - itP2->point.y; + itP2->normal.z = itP2->normal.z - itP2->point.z; + + itP->normal.x = (itP->normal.x + itP2->normal.x) / 2.0; + itP->normal.y = (itP->normal.y + itP2->normal.y) / 2.0; + itP->normal.z = (itP->normal.z + itP2->normal.z) / 2.0; + + double length(sqrt(itP->normal.x*itP->normal.x + + itP->normal.y*itP->normal.y + + itP->normal.z*itP->normal.z)); + + itP->normal.x /= length; + itP->normal.y /= length; + itP->normal.z /= length; + + itP->normal.x += itP->point.x; + itP->normal.y += itP->point.y; + itP->normal.z += itP->point.z; + + //remove second point + itP2 = pharmacophore->erase(itP2); + --itP2; + } + } + break; + + //................................................................ + case HDON: + itP2 = itP; + ++itP2; + for( ; itP2 != pharmacophore->end(); ++itP2) + { + if (itP2->func == HACC) + { + if (_hybridSameHybHPoint(itP2->point, itP->point)) + { + // modify first point + itP->func = HYBH; + itP->alpha = funcSigma[HYBH]; + + // Update normal + itP->normal.x = itP->normal.x - itP->point.x; + itP->normal.y = itP->normal.y - itP->point.y; + itP->normal.z = itP->normal.z - itP->point.z; + + itP2->normal.x = itP2->normal.x - itP2->point.x; + itP2->normal.y = itP2->normal.y - itP2->point.y; + itP2->normal.z = itP2->normal.z - itP2->point.z; + + itP->normal.x = (itP->normal.x + itP2->normal.x) / 2.0; + itP->normal.y = (itP->normal.y + itP2->normal.y) / 2.0; + itP->normal.z = (itP->normal.z + itP2->normal.z) / 2.0; + + double length(sqrt(itP->normal.x*itP->normal.x + + itP->normal.y*itP->normal.y + + itP->normal.z*itP->normal.z)); + + itP->normal.x /= length; + itP->normal.y /= length; + itP->normal.z /= length; + + itP->normal.x += itP->point.x; + itP->normal.y += itP->point.y; + itP->normal.z += itP->point.z; + + //remove second point + itP2 = pharmacophore->erase(itP2); + --itP2; + } + } + } + break; + + //................................................................ + case LIPO: + itP2 = itP; + ++itP2; + for( ; itP2 != pharmacophore->end(); ++itP2) + { + if (itP2->func == AROM) + { + if (_hybridSameHybLPoint(itP2->point, itP->point)) + { + // Modify first point + itP->func = HYBL; + itP->alpha = funcSigma[HYBL]; + itP->point.x = (itP->point.x + itP2->point.x) / 2.0; + itP->point.y = (itP->point.y + itP2->point.y) / 2.0; + itP->point.z = (itP->point.z + itP2->point.z) / 2.0; + itP->hasNormal = false; + itP->normal.x = 0.0; + itP->normal.y = 0.0; + itP->normal.z = 0.0; + + // Remove second point + pharmacophore->erase(itP2); + --itP2; + } + } + } + break; + } + } + + // For the lipophilic pharmacophores: rename both AROM and LIPO into HYBL + for (itP = pharmacophore->begin(); itP != pharmacophore->end(); ++itP) + { + switch (itP->func) + { + //................................................................ + case AROM: + itP->func = HYBL; + itP->alpha = funcSigma[HYBL]; + itP->hasNormal = false; + itP->normal.x = 0.0; + itP->normal.y = 0.0; + itP->normal.z = 0.0; + break; + + //................................................................ + case LIPO: + itP->func = HYBL; + itP->alpha = funcSigma[HYBL]; + itP->hasNormal = false; + itP->normal.x = 0.0; + itP->normal.y = 0.0; + itP->normal.z = 0.0; + break; + } + } +} + + + +bool +_hybridSameHybHPoint(const Coordinate& c1, const Coordinate& c2) +{ + double distSqr((c1.x - c2.x) * (c1.x - c2.x) + + (c1.y - c2.y) * (c1.y - c2.y) + + (c1.z - c2.z) * (c1.z - c2.z)); + return distSqr < 0.0001; +} + + + +bool +_hybridSameHybLPoint(const Coordinate& c1, const Coordinate& c2) +{ + double distSqr((c1.x - c2.x) * (c1.x - c2.x) + + (c1.y - c2.y) * (c1.y - c2.y) + + (c1.z - c2.z) * (c1.z - c2.z)); + return distSqr < 1.0; +} + +","C++" +"In Silico","baoilleach/pharao","src/logScores.cpp",".cpp","1373","40","/******************************************************************************* +logScores.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""logScores.h"" + + + +void +logScores(Result* res, Options& uo) +{ + *uo.scoreOutStream << res->refId << ""\t"" + << std::setprecision(6) << res->refVolume << ""\t"" + << res->dbId << ""\t"" + << std::setprecision(6) << res->dbVolume << ""\t"" + << std::setprecision(6) << res->overlapVolume << ""\t"" + << std::setprecision(6) << res->exclVolume << ""\t"" + << std::setprecision(6) << (res->info).volume << ""\t"" + << res->resPharSize << ""\t"" + << std::setprecision(4) << res->tanimoto << ""\t"" + << std::setprecision(4) << res->tversky_ref << ""\t"" + << std::setprecision(4) << res->tversky_db << std::endl; +} +","C++" +"In Silico","baoilleach/pharao","src/logPharmacophores.cpp",".cpp","932","30","/******************************************************************************* +logPharmacophores.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""logPharmacophores.h"" + + + +void +logPharmacophores(Result* res, Options& uo) +{ + uo.pharmOutWriter->write(res->resPhar, uo.pharmOutStream, ""NAME""); +} +","C++" +"In Silico","baoilleach/pharao","src/hAccFuncCalc.cpp",".cpp","7053","267","/******************************************************************************* +hAccFuncCalc.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""hAccFuncCalc.h"" + + + +void +hAccFuncCalc(OpenBabel::OBMol* mol, Pharmacophore* pharmacophore) +{ + // Create for every hydrogen acceptor a pharmacophore point + std::vector::iterator ai; + for (OpenBabel::OBAtom* atom = mol->BeginAtom(ai); atom; atom = mol->NextAtom(ai)) + { + if (atom->GetAtomicNum() == 7 || atom->GetAtomicNum() == 8) + { + if (atom->GetFormalCharge() <= 0) + { + if(_hAccDelocalized(atom) || (_hAccCalcAccSurf(atom) < 0.02)) + { + continue; + } + PharmacophorePoint p; + p.func = HACC; + p.point.x = atom->x(); + p.point.y = atom->y(); + p.point.z = atom->z(); + p.hasNormal = true; + p.alpha = funcSigma[HACC]; + p.normal = _hAccCalcNormal(atom); + pharmacophore->push_back(p); + } + } + } +} + + + +double +_hAccCalcAccSurf(OpenBabel::OBAtom* atom) +{ + double radius(H_BOND_DIST); + + //---(1)-- create sphere with uniformly distributed points + std::vector sphere; + std::vector::iterator itS; + + const double arclength(1.0 / sqrt(sqrt(3.0) * DENSITY)); + double dphi(arclength/radius); + int nlayer(ROUND(PI/dphi) + 1); + + double phi(0.0); + for (int i(0); i < nlayer; ++i) + { + double rsinphi(radius*sin(phi)); + double z(radius*cos(phi)); + double dtheta((rsinphi==0) ? PI*2 : arclength/rsinphi); + int tmpNbrPoints(ROUND(PI*2/dtheta)); + if(tmpNbrPoints <= 0) + { + tmpNbrPoints = 1; + } + dtheta = PI * 2.0 / tmpNbrPoints; + double theta((i % 2) ? 0 : PI); + for (int j(0) ; j < tmpNbrPoints ; ++j) + { + Coordinate coord; + coord.x = rsinphi*cos(theta) + atom->x(); + coord.y = rsinphi*sin(theta) + atom->y(); + coord.z = z + atom->z(); + sphere.push_back(coord); + theta += dtheta; + if(theta > PI*2) + { + theta -= PI*2; + } + } + phi += dphi; + } + + //---(2)-- define neighbors of atom + std::list aList(_hAccGetNeighbors(atom)); + std::list::iterator itA; + + //---(3) -- check for every sphere-point if it is accessible + int nbrAccSurfPoints(0); + double r; + OpenBabel::OBElementTable et; + for (itS = sphere.begin(); itS != sphere.end(); ++itS) + { + bool isAccessible(true); + for (itA = aList.begin(); itA != aList.end(); ++itA) + { + OpenBabel::OBAtom* n(*itA); + double distSq(((itS->x - n->x()) * (itS->x - n->x())) + + ((itS->y - n->y()) * (itS->y - n->y())) + + ((itS->z - n->z()) * (itS->z - n->z()))); + r = et.GetVdwRad(n->GetAtomicNum()); + double sumSq(r*r); + + if (distSq <= sumSq) + { + isAccessible = false; + break; + } + } + + if (isAccessible) + { + ++nbrAccSurfPoints; + + } + } + + return (nbrAccSurfPoints/(double)sphere.size()); +} + + + + +std::list +_hAccGetNeighbors(OpenBabel::OBAtom* a) +{ + std::list aList; + OpenBabel::OBMol* parent(a->GetParent()); + + double r; + OpenBabel::OBElementTable et; + std::vector::iterator ai; + for (OpenBabel::OBAtom* aa = parent->BeginAtom(ai); aa; aa = parent->NextAtom(ai)) + { + if (*aa == a) + { + continue; + } + + r = et.GetVdwRad(aa->GetAtomicNum()); + double delta(H_BOND_DIST + H_RADIUS + r); + double maxDistSq(delta*delta); + double distSq((a->x() - aa->x()) * (a->x() - aa->x()) + + (a->y() - aa->y()) * (a->y() - aa->y()) + + (a->z() - aa->z()) * (a->z() - aa->z())); + + if (distSq <= maxDistSq) + { + aList.push_back(aa); + } + } + return aList; +} + + + +bool +_hAccDelocalized(OpenBabel::OBAtom* a) +{ + if (a->GetAtomicNum() != 7) + { + return false; + } + if (a->IsAromatic() && a->GetImplicitValence() == 3) + { + return true; + } + + std::vector::iterator bi1; + for (OpenBabel::OBBond* b1 = a->BeginBond(bi1); b1; b1 = a->NextBond(bi1)) + { + OpenBabel::OBAtom* aa = b1->GetNbrAtom(a); + + if (aa->IsAromatic() && a->GetImplicitValence() == 3) + { + return true; + } + + if (aa->GetAtomicNum() == 6) + { + std::vector::iterator bi2; + for (OpenBabel::OBBond* b2 = aa->BeginBond(bi2); b2; b2 = aa->NextBond(bi2)) + { + OpenBabel::OBAtom* aaa = b2->GetNbrAtom(aa); + + if (aaa == a) + { + continue; + } + if (b2->GetBO() == 2) + { + if (aaa->GetAtomicNum() == 8) return true; + if (aaa->GetAtomicNum() == 7) return true; + if (aaa->GetAtomicNum() == 16) return true; + } + } + } + else if (aa->GetAtomicNum() == 16) + { + std::vector::iterator bi2; + for (OpenBabel::OBBond* b2 = aa->BeginBond(bi2); b2; b2 = aa->NextBond(bi2)) + { + OpenBabel::OBAtom* aaa = b2->GetNbrAtom(aa); + + if (aaa == a) + { + continue; + } + if ((b2->GetBO() == 2) && (aaa->GetAtomicNum() == 8)) + { + return true; + } + } + } + } + return false; +} + + + + +Coordinate +_hAccCalcNormal(OpenBabel::OBAtom* a) +{ + Coordinate normal; + std::vector::iterator bi; + for (OpenBabel::OBBond* b = a->BeginBond(bi); b; b = a->NextBond(bi)) + { + OpenBabel::OBAtom* aa = b->GetNbrAtom(a); + if (aa->GetAtomicNum() == 1) + { + continue; + } + normal.x += (aa->x() - a->x()); + normal.y += (aa->y() - a->y()); + normal.z += (aa->z() - a->z()); + } + double length(sqrt(normal.x*normal.x + normal.y*normal.y + normal.z*normal.z)); + normal.x /= length; + normal.y /= length; + normal.z /= length; + + normal.x = -normal.x; + normal.y = -normal.y; + normal.z = -normal.z; + + normal.x += a->x(); + normal.y += a->y(); + normal.z += a->z(); + + return normal; +} +","C++" +"In Silico","baoilleach/pharao","src/main.cpp",".cpp","18609","673","/******************************************************************************* +main.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +// General +#include +#include +#include +#include +#include + +// OpenBabel +#include +#include + +// Pharao +#include ""options.h"" +#include ""logOut.h"" +#include ""logScores.h"" +#include ""logPharmacophores.h"" +#include ""addBest.h"" +#include ""parseCommandLine.h"" +#include ""pharmacophore.h"" +#include ""pharMerger.h"" +#include ""printHeader.h"" +#include ""printUsage.h"" +#include ""printProgress.h"" +#include ""getExt.h"" +#include ""calcPharm.h"" +#include ""result.h"" +#include ""alignment.h"" +#include ""functionMapping.h"" + +//*--------------------------------------------------------------------------*// +PharMerger pharMerger; + +void writeResult(Result &res, Options &uo) { + if (!uo.molOutFile.empty()) + { + logOut(&res, uo); + } + if (!uo.pharmOutFile.empty()) + { + logPharmacophores(&res, uo); + } + if (!uo.scoreOutFile.empty()) + { + logScores(&res, uo); + } +} + + +//*--------------------------------------------------------------------------*// +//* MAIN MAIN *// +//*--------------------------------------------------------------------------*// +int main(int argc, char* argv[]) +{ + // Initialise random number generator +#ifdef _MSC_VER + srand(static_cast (time(NULL))); +#else + srandom(time(NULL)); +#endif + clock_t t0 = clock(); + + // Print header + printHeader(); + + // Read options + Options uo; + parseCommandLine(argc,argv,uo); + if(!uo.noHybrid) + { + if(uo.funcGroupVec[AROM] && uo.funcGroupVec[LIPO]) + { + uo.funcGroupVec[HYBL] = true; + } + if(uo.funcGroupVec[HDON] && uo.funcGroupVec[HACC]) + { + uo.funcGroupVec[HYBH] = true; + } + } + std::cerr << uo.print() << std::endl; + + if (uo.version) + { + printHeader(); + exit(0); + } + + if (uo.help) + { + printUsage(); + exit(0); + } + + // Db file and pharmacophore out are mandatory elements + if (uo.dbInpFile.empty()) + { + mainErr(""Missing database file. This is a required option (-d).""); + } + + if (uo.pharmOutFile.empty() && uo.molOutFile.empty() && uo.scoreOutFile.empty()) + { + mainErr(""No output file defined. So there is actually no use to compute anything at all.""); + } + + if ((uo.pharmOutFile.empty() && uo.scoreOutFile.empty()) && !uo.molOutFile.empty()) + { + mainErr(""No file defined to write pharmacophore information.""); + } + + if (uo.refInpFile.empty() && uo.pharmOutFile.empty() && uo.molOutFile.empty() && !uo.scoreOutFile.empty()) + { + mainErr(""Only score file requested when no reference is given. Unable to generate this output.""); + } + + // Reference variables + Pharmacophore refPharm; + refPharm.clear(); + std::string refId; + double refVolume(0.0); + int refSize(0); + int exclSize(0); + + // Database variables + std::vector resList; + Pharmacophore dbPharm; + std::string dbId; + double dbVolume(0.0); + int dbSize(0); + + //---------------------------------------------------------------------------- + //...(A).. Process the reference + //---------------------------------------------------------------------------- + + if (!uo.refInpFile.empty()) + { + //------------------------------------------------------- + //...(1).. get reference pharmacophore + //------------------------------------------------------- + + if (uo.refInpType == UNKNOWN) + { + std::string ext(getExt(uo.refInpFile)); + if (ext == "".phar"") + { + uo.refInpType = PHAR; + } + else + { + uo.refInpType = MOL; + } + } + + if (uo.refInpType == MOL) + { + OpenBabel::OBMol m; + OpenBabel::OBConversion* reader = new OpenBabel::OBConversion(); + reader->SetInFormat(reader->FormatFromExt(uo.refInpFile.c_str())); + if (!reader->Read(&m, uo.refInpStream)) + { + mainErr(""Unable to read reference molecule""); + } + calcPharm(&m, &refPharm, uo); + refId = m.GetTitle(); + delete reader; + reader = NULL; + } + else if (uo.refInpType == PHAR) + { + PharmacophoreReader* reader = new PharmacophoreReader(); + refPharm = reader->read(uo.refInpStream, refId); + if (refPharm.empty()) + { + mainErr(""Error reading reference pharmacophore""); + } + delete reader; + reader = NULL; + } + else + { + mainErr(""Unknown format of reference molecule.""); + } + + //------------------------------------------------------- + //...(2).. process reference pharmacophore + //------------------------------------------------------- + + if (uo.merge) + { + pharMerger.merge(refPharm); + } + + refSize = refPharm.size(); + for (unsigned int i(0); i < refSize; ++i) + { + if (refPharm[i].func == EXCL) + { + // extract overlap with exclusion spheres + for (unsigned int j(0); j < refPharm.size(); ++j) + { + if (refPharm[j].func != EXCL) + { + refVolume -= VolumeOverlap(refPharm[i], refPharm[j], !uo.noNormal); + } + } + exclSize++; + } + else + { + // add point self-overlap + refVolume += VolumeOverlap(refPharm[i], refPharm[i], !uo.noNormal); + } + } + + if(!uo.isQuiet) + { + std::cerr << ""Reference pharmacophore "" << refId << std::endl; + std::cerr << "" number of points: "" << refSize - exclSize << std::endl; + std::cerr << "" number of exclusion spheres: "" << exclSize << std::endl; + std::cerr << "" totalvolume: "" << refVolume << std::endl; + } + } + + //---------------------------------------------------------------------------- + //...(B).. Process the database file + //---------------------------------------------------------------------------- + + // DB files + if (uo.dbInpType == UNKNOWN) + { + std::string ext(getExt(uo.dbInpFile)); + if (ext=="".phar"") + { + uo.dbInpType = PHAR; + } + else + { + uo.dbInpType = MOL; + } + } + + // local storage of the rotation matrix + SiMath::Matrix rotMat(3,3,0.0); + + unsigned int molCount(0); + + OpenBabel::OBConversion* molReader = NULL; + PharmacophoreReader* pharmReader = NULL; + + if (uo.dbInpType == PHAR) + { + pharmReader = new PharmacophoreReader(); + } + else if (uo.dbInpType == MOL) + { + molReader = new OpenBabel::OBConversion(); + molReader->SetInFormat(molReader->FormatFromExt(uo.dbInpFile.c_str())); + molReader->SetInStream(uo.dbInpStream); + } + else + { + mainErr(""Unknown format of db file.""); + } + + bool done(false); + OpenBabel::OBMol m; + std::string oldTitle = """"; + Result bestConf; + bestConf.rankbyScore = -9999; + while (!done) + { + dbPharm.clear(); + m.Clear(); + + if (uo.dbInpType == MOL) + { + if (!molReader->Read(&m)) + { + done = true; + break; + } + else + { + calcPharm(&m, &dbPharm, uo); + dbId = m.GetTitle(); + } + } + else + { + if (uo.dbInpStream->eof()) + { + done = true; + break; + } + else + { + dbPharm = pharmReader->read(uo.dbInpStream, dbId); + } + } + if (dbPharm.empty()) + { + continue; + } + + ++molCount; + if (!uo.isQuiet ) + { + if ((molCount % 10) == 0) + { + std::cerr << ""."" << std::flush; + } + if ((molCount % 500) == 0) + { + std::cerr << molCount << std::endl << std::flush; + } + } + + + if (uo.merge) + { + pharMerger.merge(dbPharm); + } + + if (uo.refInpFile.empty()) + { + if (!(uo.isQuiet)) + { + printProgress(molCount); + } + if( !uo.pharmOutFile.empty()) + { + uo.pharmOutWriter->write(dbPharm, uo.pharmOutStream, dbId); + } + continue; + } + + //------------------------------------------------------- + //...(1).. Alignment + //------------------------------------------------------- + + dbSize = dbPharm.size(); + dbVolume = 0.0; + for (unsigned int i(0); i < dbSize; ++i) + { + if (dbPharm[i].func == EXCL) + { + continue; + } + dbVolume += VolumeOverlap(dbPharm[i], dbPharm[i], !uo.noNormal); + } + + // Create a result structure + Result res; + res.refId = refId; + res.refVolume = refVolume; + res.dbId = dbId; + res.dbVolume = dbVolume; + res.overlapVolume = 0.0; + res.exclVolume = 0.0; + res.resMol = m; + res.resPharSize = 0; + + if (uo.scoreOnly) + { + FunctionMapping funcMap(&refPharm, &dbPharm, uo.epsilon); + PharmacophoreMap fMap = funcMap.getNextMap(); + double volBest(-9999.999); + + // loop over all reference points + while (!fMap.empty()) + { + double newVol(0.0); + double exclVol(0.0); + for (PharmacophoreMap::iterator itP = fMap.begin(); itP != fMap.end(); ++itP) + { + if ((itP->first)->func == EXCL) + { + exclVol += VolumeOverlap((itP->first), (itP->second), !uo.noNormal); + } + else if (((itP->first)->func == (itP->second)->func ) || + (((itP->first)->func == HYBH || + (itP->first)->func == HDON || + (itP->first)->func == HACC) + && ((itP->second)->func == HDON || + (itP->second)->func == HACC || + (itP->second)->func == HYBH)) + || (((itP->first)->func == HYBL || + (itP->first)->func == AROM || + (itP->first)->func == LIPO) + && ((itP->second)->func == AROM || + (itP->second)->func == LIPO || + (itP->second)->func == HYBL))) + { + newVol += VolumeOverlap((itP->first),(itP->second), !uo.noNormal); + } + } + + if ((newVol - exclVol) > volBest) + { + res.resPhar.clear(); + res.resPharSize = 0; + for (PharmacophoreMap::iterator itP = fMap.begin(); itP != fMap.end(); ++itP) + { + // add point to resulting pharmacophore + PharmacophorePoint p(itP->second); + (res.resPhar).push_back(p); + ++res.resPharSize; + } + res.overlapVolume = newVol; + res.exclVolume = exclVol; + volBest = newVol - exclVol; + } + // get the next map + fMap.clear(); + fMap = funcMap.getNextMap(); + } + } + else + { + FunctionMapping funcMap(&refPharm, &dbPharm, uo.epsilon); + PharmacophoreMap fMap = funcMap.getNextMap(); + PharmacophoreMap bestMap; + + // default solution + SolutionInfo best; + best.volume = -999.9; + + // rotor is set to no rotation + best.rotor.resize(4); + best.rotor = 0.0; + best.rotor[0] = 1.0; + + double bestScore = -1000; + int mapSize(fMap.size()); + int maxSize = mapSize - 3; + + while (!fMap.empty()) + { + int msize = fMap.size(); + + // add the exclusion spheres to the alignment procedure + if (uo.withExclusion) + { + for (unsigned int i(0); i < refSize ; ++i) + { + if (refPharm[i].func != EXCL) + { + continue; + } + for (unsigned int j(0); j < dbSize; ++j) + { + if (dbPharm[j].func == EXCL) + { + continue; + } + fMap.insert(std::make_pair(&(refPharm[i]), &(dbPharm[j]))); + } + } + } + + // Only align if the expected score has any chance of being larger + // than best score so far + if ((msize > maxSize) + && (((double) msize / (refSize - exclSize + dbSize - msize)) > bestScore)) + { + Alignment align(fMap); + SolutionInfo r = align.align(!uo.noNormal); + + if (best.volume < r.volume) + { + best = r; + bestScore = best.volume / (refVolume + dbVolume - best.volume); + bestMap = fMap; + mapSize = msize; + } + } + else + { + // Level of mapping site to low + break; + } + + if (bestScore > 0.98) + { + break; + } + + // Get the next map + fMap.clear(); + fMap = funcMap.getNextMap(); + } + + // Transform the complete pharmacophore and the molecule towards the + // best alignment + rotMat = quat2Rotation(best.rotor); + positionPharmacophore(dbPharm, rotMat, best); + positionMolecule(&res.resMol, rotMat, best); + + // Update result + res.info = best; + + // Compute overlap volume between exlusion spheres and pharmacophore + // points + for (int i(0); i < refSize; ++i) + { + if (refPharm[i].func != EXCL) + { + continue; + } + for (int j(0); j < dbSize; ++j) + { + res.exclVolume += VolumeOverlap(refPharm[i], dbPharm[j], !uo.noNormal); + } + } + + // make copy of the best map and compute the volume overlap + for (PharmacophoreMap::iterator itP = bestMap.begin(); itP != bestMap.end(); ++itP) + { + if(((itP->first)->func == EXCL) || ((itP->second)->func == EXCL)) + { + continue; + } + + // compute overlap + res.overlapVolume += VolumeOverlap(itP->first, itP->second, !uo.noNormal); + + // add point to resulting pharmacophore + PharmacophorePoint p(itP->second); + (res.resPhar).push_back(p); + ++res.resPharSize; + } + } + + // update scores + res.info.volume = res.overlapVolume - res.exclVolume; + if (res.info.volume > 0.0) + { + res.tanimoto = res.info.volume / (res.refVolume + res.dbVolume - res.info.volume); + res.tversky_ref = res.info.volume / res.refVolume; + res.tversky_db = res.info.volume / res.dbVolume; + } + + switch (uo.rankby) + { + case TANIMOTO: + res.rankbyScore = res.tanimoto; + break; + case TVERSKY_REF: + res.rankbyScore = res.tversky_ref; + break; + case TVERSKY_DB: + res.rankbyScore = res.tversky_db; + break; + } + + //------------------------------------------------------- + //...(5).. Generate output + //------------------------------------------------------- + if (uo.cutOff != 0.0) + { + if (res.rankbyScore < uo.cutOff) + { + continue; + } + } + + if (uo.singleConf) + { + if (res.resMol.GetTitle() == oldTitle) + { + if (res.rankbyScore > bestConf.rankbyScore) + bestConf = res; + } + else + { + if (bestConf.rankbyScore != -9999) // On the first iteration + { + if (uo.best != 0) + addBest(bestConf, uo, resList); + else + writeResult(bestConf, uo); + } + oldTitle = res.resMol.GetTitle(); + bestConf = res; + } + } + else + { + if (uo.best != 0) + addBest(res, uo, resList); + else + writeResult(res, uo); + } + } + + // Tidy up + if (uo.singleConf) + { + if (uo.best != 0) + addBest(bestConf, uo, resList); + else + writeResult(bestConf, uo); + } + + if (molReader) + { + delete molReader; + molReader = NULL; + } + if (pharmReader) + { + delete pharmReader; + pharmReader = NULL; + } + + //---------------------------------------------------------------------------- + //...(C).. Process best list (if defined) + //---------------------------------------------------------------------------- + + if (uo.best != 0) + { + std::vector::iterator itR; + for (itR = resList.begin(); itR != resList.end(); ++itR) + { + writeResult(**itR, uo); + delete *itR; + } + } + + // done processing database + if (!uo.isQuiet) + { + if (uo.refInpFile.empty()) + { + std::cerr << std::endl; + std::cerr << ""Processed "" << molCount << "" molecules""; + double tt = (double)(clock() - t0 )/CLOCKS_PER_SEC; + std::cerr << "" in "" << tt << "" seconds (""; + std::cerr << molCount/tt << "" molecules per second)."" << std::endl; + } + else + { + std::cerr << std::endl; + std::cerr << ""Processed "" << molCount << "" molecules"" << std::endl; + double tt = (double)(clock() - t0 )/CLOCKS_PER_SEC; + std::cerr << molCount << "" alignments in "" << tt << "" seconds (""; + std::cerr << molCount/tt << "" alignments per second)."" << std::endl; + } + } + + exit(0); + +} + +","C++" +"In Silico","baoilleach/pharao","src/logOut.cpp",".cpp","1837","64","/******************************************************************************* +logOut.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""logOut.h"" + + + +void +logOut(Result* res, Options& uo) +{ + if((res->resMol).Empty()) + { + return; + } + + std::ostringstream ss; + + // Add properties to the molecule + OpenBabel::OBPairData* label1 = new OpenBabel::OBPairData(); + label1->SetAttribute(""PHARAO_TANIMOTO""); + ss << res->tanimoto; + label1->SetValue(ss.str()); + (res->resMol).SetData(label1); + + OpenBabel::OBPairData* label2 = new OpenBabel::OBPairData(); + label2->SetAttribute(""PHARAO_TVERSKY_REF""); + ss.str(""""); + ss << res->tversky_ref; + label2->SetValue(ss.str()); + (res->resMol).SetData(label2); + + OpenBabel::OBPairData* label3 = new OpenBabel::OBPairData(); + label3->SetAttribute(""PHARAO_TVERSKY_DB""); + ss.str(""""); + ss << res->tversky_db; + label3->SetValue(ss.str()); + (res->resMol).SetData(label3); + + // Write molecule + uo.molOutWriter->Write(&(res->resMol), uo.molOutStream); + + // Clean up + (res->resMol).DeleteData(""PHARAO_TANIMOTO""); + (res->resMol).DeleteData(""PHARAO_TVERSKY_REF""); + (res->resMol).DeleteData(""PHARAO_TVERSKY_DB""); +} +","C++" +"In Silico","baoilleach/pharao","src/mainWar.cpp",".cpp","886","30","/******************************************************************************* +mainWar.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""mainWar.h"" + + + +void +mainWar(const std::string& msg) +{ + std::cerr << ""**MainWarning** "" << msg << std::endl; +} +","C++" +"In Silico","baoilleach/pharao","src/alignment.cpp",".cpp","15693","502","/******************************************************************************* +alignment.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""alignment.h"" + +Alignment::Alignment(PharmacophoreMap& fMap) : + _refMap(), + _dbMap(), + _refCenter(), + _dbCenter(), + _refRotMat(3,3,0.0), + _dbRotMat(3,3,0.0), + _dCdq(4,0.0), + _d2Cdq2(4,4,0.0), + _grad(4,0.0), + _AkA(fMap.size()), + _nbrPoints(0), + _nbrExcl(0) +{ + // compute centers of the two pharmacophore sets + PharmacophoreMap::iterator mi; + + unsigned int nbrMatch(0); + + // compute the centroid of the pharmacophores + double V1(0.0), v1(0.0), V2(0.0), v2(0.0); + for (mi = fMap.begin(); mi != fMap.end(); ++mi) + { + if (mi->first->func == EXCL) + { + _nbrExcl++; + continue; // do not use exclusion spheres when computing the center + } + + _nbrPoints++; + + v1 = GCI * pow(PI/mi->first->alpha,1.5); + V1 += v1; + _refCenter.x += v1 * mi->first->point.x; + _refCenter.y += v1 * mi->first->point.y; + _refCenter.z += v1 * mi->first->point.z; + + v2 = GCI * pow(PI/mi->second->alpha,1.5); + V2 += v2; + _dbCenter.x += v2 * mi->second->point.x; + _dbCenter.y += v2 * mi->second->point.y; + _dbCenter.z += v2 * mi->second->point.z; + ++nbrMatch; + } + _refCenter.x /= V1; + _refCenter.y /= V1; + _refCenter.z /= V1; + + _dbCenter.x /= V2; + _dbCenter.y /= V2; + _dbCenter.z /= V2; + + // translate the pharmacophores to the centers + // and compute center of mass matrix + SiMath::Matrix mass1(3,3,0.0); + SiMath::Matrix mass2(3,3,0.0); + for (mi = fMap.begin(); mi != fMap.end(); ++mi) + { + PharmacophorePoint p1, p2; + + p1.point.x = mi->first->point.x - _refCenter.x; + p1.point.y = mi->first->point.y - _refCenter.y; + p1.point.z = mi->first->point.z - _refCenter.z; + p1.func = mi->first->func; + p1.alpha = mi->first->alpha; + p1.normal.x = mi->first->normal.x - mi->first->point.x; + p1.normal.y = mi->first->normal.y - mi->first->point.y; + p1.normal.z = mi->first->normal.z - mi->first->point.z; + + p2.point.x = mi->second->point.x - _dbCenter.x; + p2.point.y = mi->second->point.y - _dbCenter.y; + p2.point.z = mi->second->point.z - _dbCenter.z; + p2.func = mi->second->func; + p2.alpha = mi->second->alpha; + p2.normal.x = mi->second->normal.x - mi->second->point.x; + p2.normal.y = mi->second->normal.y - mi->second->point.y; + p2.normal.z = mi->second->normal.z - mi->second->point.z; + + if (mi->first->func != EXCL) + { + v1 = GCI * pow(PI/mi->first->alpha,1.5); + mass1[0][0] += v1 * p1.point.x * p1.point.x; + mass1[0][1] += v1 * p1.point.x * p1.point.y; + mass1[0][2] += v1 * p1.point.x * p1.point.z; + mass1[1][1] += v1 * p1.point.y * p1.point.y; + mass1[1][2] += v1 * p1.point.y * p1.point.z; + mass1[2][2] += v1 * p1.point.z * p1.point.z; + + v2 = GCI * pow(PI/mi->second->alpha,1.5); + + mass2[0][0] += v2 * p2.point.x * p2.point.x; + mass2[0][1] += v2 * p2.point.x * p2.point.y; + mass2[0][2] += v2 * p2.point.x * p2.point.z; + mass2[1][1] += v2 * p2.point.y * p2.point.y; + mass2[1][2] += v2 * p2.point.y * p2.point.z; + mass2[2][2] += v2 * p2.point.z * p2.point.z; + } + // add new points to local maps + _refMap.push_back(p1); + _dbMap.push_back(p2); + } + + // use SVD to compute best rotations + // set lower triangle + mass1[1][0] = mass1[0][1]; + mass1[2][0] = mass1[0][2]; + mass1[2][1] = mass1[1][2]; + + // normalize mass matrix + mass1 /= V1; + + // compute SVD of the mass matrix + SiMath::SVD svd(mass1, true, true); + _refRotMat = svd.getU(); + + // check if determinant is 1, otherwise it is a mirroring instead of rotation + double det = _refRotMat[0][0]*_refRotMat[1][1]*_refRotMat[2][2] + + _refRotMat[2][1]*_refRotMat[1][0]*_refRotMat[0][2] + + _refRotMat[0][1]*_refRotMat[1][2]*_refRotMat[2][0] + - _refRotMat[0][0]*_refRotMat[1][2]*_refRotMat[2][1] + - _refRotMat[1][1]*_refRotMat[2][0]*_refRotMat[0][2] + - _refRotMat[2][2]*_refRotMat[0][1]*_refRotMat[1][0]; + + // check if it is a rotation matrix and not a mirroring + if (det < 0) + { + // switch sign of third column + _refRotMat[0][2] = -_refRotMat[0][2]; + _refRotMat[1][2] = -_refRotMat[1][2]; + _refRotMat[2][2] = -_refRotMat[2][2]; + } + + // set lower triangle + mass2[1][0] = mass2[0][1]; + mass2[2][0] = mass2[0][2]; + mass2[2][1] = mass2[1][2]; + + // normalize mass matrix + mass2 /= V2; + + // compute SVD of the mass matrix + SiMath::SVD svd2(mass2, true, true); + _dbRotMat = svd2.getU(); + + // check if determinant is 1, otherwise it is a mirroring instead of rotation + det = _dbRotMat[0][0]*_dbRotMat[1][1]*_dbRotMat[2][2] + + _dbRotMat[2][1]*_dbRotMat[1][0]*_dbRotMat[0][2] + + _dbRotMat[0][1]*_dbRotMat[1][2]*_dbRotMat[2][0] + - _dbRotMat[0][0]*_dbRotMat[1][2]*_dbRotMat[2][1] + - _dbRotMat[1][1]*_dbRotMat[2][0]*_dbRotMat[0][2] + - _dbRotMat[2][2]*_dbRotMat[0][1]*_dbRotMat[1][0]; + + // checif if it is a rotation matrix and not a mirroring + if (det < 0) + { + // switch sign of third column + _dbRotMat[0][2] = -_dbRotMat[0][2]; + _dbRotMat[1][2] = -_dbRotMat[1][2]; + _dbRotMat[2][2] = -_dbRotMat[2][2]; + } + + // rotate points towards main axes + for (unsigned int i(0); i < _refMap.size(); ++i) + { + // Rotate points + double x = _refMap[i].point.x; + double y = _refMap[i].point.y; + double z = _refMap[i].point.z; + _refMap[i].point.x = _refRotMat[0][0]*x + _refRotMat[1][0]*y + _refRotMat[2][0]*z; + _refMap[i].point.y = _refRotMat[0][1]*x + _refRotMat[1][1]*y + _refRotMat[2][1]*z; + _refMap[i].point.z = _refRotMat[0][2]*x + _refRotMat[1][2]*y + _refRotMat[2][2]*z; + + x = _dbMap[i].point.x; + y = _dbMap[i].point.y; + z = _dbMap[i].point.z; + _dbMap[i].point.x = _dbRotMat[0][0]*x + _dbRotMat[1][0]*y + _dbRotMat[2][0]*z; + _dbMap[i].point.y = _dbRotMat[0][1]*x + _dbRotMat[1][1]*y + _dbRotMat[2][1]*z; + _dbMap[i].point.z = _dbRotMat[0][2]*x + _dbRotMat[1][2]*y + _dbRotMat[2][2]*z; + + double dx = _refMap[i].point.x - _dbMap[i].point.x; + double dx2 = dx * dx; + double dy = _refMap[i].point.y - _dbMap[i].point.y; + double dy2 = dy * dy; + double dz = _refMap[i].point.z - _dbMap[i].point.z; + double dz2 = dz * dz; + double sx = _refMap[i].point.x + _dbMap[i].point.x; + double sx2 = sx * sx; + double sy = _refMap[i].point.y + _dbMap[i].point.y; + double sy2 = sy * sy; + double sz = _refMap[i].point.z + _dbMap[i].point.z; + double sz2 = sz * sz; + + _AkA[i] = new SiMath::Matrix(4,4,0.0); + (*_AkA[i])[0][0] = dx2 + dy2 + dz2; + (*_AkA[i])[0][1] = dy*sz - sy*dz; + (*_AkA[i])[0][2] = sx*dz - dx*sz; + (*_AkA[i])[0][3] = dx*sy - sx*dy; + (*_AkA[i])[1][0] = (*_AkA[i])[0][1]; + (*_AkA[i])[1][1] = dx2 + sy2 + sz2; + (*_AkA[i])[1][2] = dx*dy - sx*sy; + (*_AkA[i])[1][3] = dx*dz - sx*sz; + (*_AkA[i])[2][0] = (*_AkA[i])[0][2]; + (*_AkA[i])[2][1] = (*_AkA[i])[1][2]; + (*_AkA[i])[2][2] = sx2 + dy2 + sz2; + (*_AkA[i])[2][3] = dy*dz - sy*sz; + (*_AkA[i])[3][0] = (*_AkA[i])[0][3]; + (*_AkA[i])[3][1] = (*_AkA[i])[1][3]; + (*_AkA[i])[3][2] = (*_AkA[i])[2][3]; + (*_AkA[i])[3][3] = sx2 + sy2 + dz2; + + // Rotate normals + x = _refMap[i].normal.x; + y = _refMap[i].normal.y; + z = _refMap[i].normal.z; + _refMap[i].normal.x = _refRotMat[0][0]*x + _refRotMat[1][0]*y + _refRotMat[2][0]*z; + _refMap[i].normal.y = _refRotMat[0][1]*x + _refRotMat[1][1]*y + _refRotMat[2][1]*z; + _refMap[i].normal.z = _refRotMat[0][2]*x + _refRotMat[1][2]*y + _refRotMat[2][2]*z; + x = _dbMap[i].normal.x; + y = _dbMap[i].normal.y; + z = _dbMap[i].normal.z; + _dbMap[i].normal.x = _dbRotMat[0][0]*x + _dbRotMat[1][0]*y + _dbRotMat[2][0]*z; + _dbMap[i].normal.y = _dbRotMat[0][1]*x + _dbRotMat[1][1]*y + _dbRotMat[2][1]*z; + _dbMap[i].normal.z = _dbRotMat[0][2]*x + _dbRotMat[1][2]*y + _dbRotMat[2][2]*z; + } + + return; +} + + + +Alignment::~Alignment(void) +{ + for (unsigned int i(0); i < _AkA.size(); ++i) + { + if (_AkA[i] != NULL) + { + delete _AkA[i]; + } + } +} + + + +SolutionInfo +Alignment::align(bool n) +{ + // create initial solution + SolutionInfo si; + si.volume = -1000.0; + si.iterations = 0; + si.center1 = _refCenter; + si.center2 = _dbCenter; + si.rotation1 = _refRotMat; + si.rotation2 = _dbRotMat; + + // scaling of the exclusion spheres + double scale(1.0); + if (_nbrExcl != 0) + { + scale /= _nbrExcl; + } + + // try 4 different start orientations + for (unsigned int _call(0); _call < 4; ++_call ) + { + // create initial rotation quaternion + SiMath::Vector rotor(4,0.0); + rotor[_call] = 1.0; + + double volume(0.0), oldVolume(-999.99), v(0.0); + SiMath::Vector dG(4,0.0); // gradient update + SiMath::Matrix hessian(4,4,0.0), dH(4,4,0.0); // hessian and hessian update + unsigned int ii(0); + for ( ; ii < 100; ++ii) + { + // compute gradient of volume + _grad = 0.0; + volume = 0.0; + hessian = 0.0; + for (unsigned int i(0); i < _refMap.size(); ++i) + { + // compute the volume overlap of the two pharmacophore points + SiMath::Vector Aq(4,0.0); + SiMath::Matrix * AkA = _AkA[i]; + Aq[0] = (*AkA)[0][0] * rotor[0] + (*AkA)[0][1] * rotor[1] + (*AkA)[0][2] * rotor[2] + (*AkA)[0][3] * rotor[3]; + Aq[1] = (*AkA)[1][0] * rotor[0] + (*AkA)[1][1] * rotor[1] + (*AkA)[1][2] * rotor[2] + (*AkA)[1][3] * rotor[3]; + Aq[2] = (*AkA)[2][0] * rotor[0] + (*AkA)[2][1] * rotor[1] + (*AkA)[2][2] * rotor[2] + (*AkA)[2][3] * rotor[3]; + Aq[3] = (*AkA)[3][0] * rotor[0] + (*AkA)[3][1] * rotor[1] + (*AkA)[3][2] * rotor[2] + (*AkA)[3][3] * rotor[3]; + + double qAq = Aq[0] * rotor[0] + Aq[1] * rotor[1] + Aq[2] * rotor[2] +Aq[3] * rotor[3]; + + v = GCI2 * pow(PI/(_refMap[i].alpha+_dbMap[i].alpha),1.5) * exp(-qAq); + + double c(1.0); + + // add normal if AROM-AROM + // in this case the absolute value of the angle is needed + if (n + && (_refMap[i].func == AROM) && (_dbMap[i].func == AROM) + && (_refMap[i].hasNormal) && (_dbMap[i].hasNormal)) + { + // for aromatic rings only the planar directions count + // therefore the absolute value of the cosine is taken + c = _normalContribution(_refMap[i].normal, _dbMap[i].normal, rotor); + + // update based on the sign of the cosine + if (c < 0) + { + c *= -1.0; + _dCdq *= -1.0; + _d2Cdq2 *= -1.0; + } + + for (unsigned int hi(0); hi < 4; hi++) + { + _grad[hi] += v * ( _dCdq[hi] - 2.0 * c * Aq[hi] ); + for (unsigned int hj(0); hj < 4; hj++) + { + hessian[hi][hj] += v * (_d2Cdq2[hi][hj] - 2.0 * _dCdq[hi]*Aq[hj] + 2.0 * c * (2.0*Aq[hi]*Aq[hj] - (*AkA)[hi][hj])); + } + } + v *= c; + } + else if (n + && ((_refMap[i].func == HACC) || (_refMap[i].func == HDON) || (_refMap[i].func == HYBH)) + && ((_dbMap[i].func == HYBH) || (_dbMap[i].func == HACC) || (_dbMap[i].func == HDON)) + && (_refMap[i].hasNormal) + && (_dbMap[i].hasNormal)) + { + // hydrogen donors and acceptor also have a direction + // in this case opposite directions have negative impact + + c = _normalContribution(_refMap[i].normal, _dbMap[i].normal, rotor); + + for (unsigned int hi(0); hi < 4; hi++) + { + _grad[hi] += v * ( _dCdq[hi] - 2.0 * c * Aq[hi] ); + for (unsigned int hj(0); hj < 4; hj++) + { + hessian[hi][hj] += v * (_d2Cdq2[hi][hj] - 2.0 * _dCdq[hi]*Aq[hj] + 2.0 * c * (2.0*Aq[hi]*Aq[hj] - (*AkA)[hi][hj])); + } + } + + v *= c; + } + else if (_refMap[i].func == EXCL) + { + // scale volume overlap of exclusion sphere with a negative scaling factor + // => exclusion spheres have a negative impact + v *= -scale; + // update gradient and hessian directions + for (unsigned int hi=0; hi < 4; hi++) + { + _grad[hi] -= 2.0 * v * Aq[hi]; + for (unsigned int hj(0); hj < 4; hj++) + { + hessian[hi][hj] += 2.0 * v * (2.0*Aq[hi]*Aq[hj] - (*AkA)[hi][hj]); + } + } + } + else + { + // update gradient and hessian directions + for (unsigned int hi(0); hi < 4; hi++) + { + _grad[hi] -= 2.0 * v * Aq[hi]; + for (unsigned int hj(0); hj < 4; hj++) + { + hessian[hi][hj] += 2.0 * v * (2.0*Aq[hi]*Aq[hj] - (*AkA)[hi][hj]); + } + } + } + + volume += v; + } + + // stop iterations if the increase in volume overlap is too small (gradient ascent) + // or if the volume is not defined +#ifdef _MSC_VER + if (_isnan(volume) || (volume - oldVolume < 1e-5)) break; +#else + if (std::isnan(volume) || (volume - oldVolume < 1e-5)) break; +#endif + + // reset old volume + oldVolume = volume; + + inverseHessian(hessian); + // update gradient based on inverse hessian + _grad = rowProduct(hessian,_grad); + // small scaling of the gradient + _grad *= 0.9; + + // update rotor based on gradient information + rotor += _grad; + + // normalise rotor such that it has unit norm + normalise(rotor); + } + + // save result in info structure + if (oldVolume > si.volume) + { + si.rotor = rotor; + si.volume = oldVolume; + si.iterations = ii; + } + } + + return si; +} + + + +double +Alignment::_normalContribution(Coordinate& n1, Coordinate& n2, SiMath::Vector& q) +{ + double x = n2.x; + double y = n2.y; + double z = n2.z; + + double d1sq(q[1]*q[1]); + double d2sq(q[2]*q[2]); + double d3sq(q[3]*q[3]); + + + double Ux = x * (1.0 - 2.0 * d2sq - 2.0 * d3sq ) + + y * (2.0 * (q[2] * q[1] - q[0] * q[3])) + + z * (2.0 * (q[3] * q[1] + q[0] * q[2])); + + double Uy = x * (2.0 * (q[1] * q[2] + q[0] * q[3])) + + y * (1.0 - 2.0 * d1sq - 2.0 * d3sq) + + z * (2.0 * (q[3] * q[2] - q[0] * q[1])); + + double Uz = x * (2.0 * (q[1] * q[3] - q[0] * q[2])) + + y * (2.0 * (q[2] * q[3] + q[0] * q[1])) + + z * (1.0 - 2.0 * d1sq - 2.0 * d2sq); + + // hessian update matrix + _d2Cdq2[0][0] = 0.0; + _d2Cdq2[1][1] = 2.0 * (n1.y * Uy + n1.z * Uz); + _d2Cdq2[2][2] = 2.0 * (n1.x * Ux + n1.z * Uz); + _d2Cdq2[3][3] = 2.0 * (n1.x * Ux + n1.y * Uy); + _d2Cdq2[0][1] = _d2Cdq2[1][0] = -2.0 * (n1.y * Uz - n1.z * Uy); + _d2Cdq2[0][2] = _d2Cdq2[2][0] = 2.0 * (n1.x * Uz - n1.z * Ux); + _d2Cdq2[0][3] = _d2Cdq2[3][0] = -2.0 * (n1.x * Uy - n1.y * Ux); + _d2Cdq2[1][2] = _d2Cdq2[2][1] = 2.0 * (n1.x * Uy + n1.y * Ux); + _d2Cdq2[1][3] = _d2Cdq2[3][1] = 2.0 * (n1.x * Uz + n1.z * Ux); + _d2Cdq2[2][3] = _d2Cdq2[3][2] = 2.0 * (n1.y * Uz + n1.z * Uy); + + // gradient update + _dCdq[0] = _d2Cdq2[0][0] * q[0] + _d2Cdq2[0][1] * q[1] + _d2Cdq2[0][2] * q[2] + _d2Cdq2[0][3] * q[3]; + _dCdq[1] = _d2Cdq2[1][0] * q[0] + _d2Cdq2[1][1] * q[1] + _d2Cdq2[1][2] * q[2] + _d2Cdq2[1][3] * q[3]; + _dCdq[2] = _d2Cdq2[2][0] * q[0] + _d2Cdq2[2][1] * q[1] + _d2Cdq2[2][2] * q[2] + _d2Cdq2[2][3] * q[3]; + _dCdq[3] = _d2Cdq2[3][0] * q[0] + _d2Cdq2[3][1] * q[1] + _d2Cdq2[3][2] * q[2] + _d2Cdq2[3][3] * q[3]; + + // return cosine + return n1.x * Ux + n1.y * Uy + n1.z * Uz; + +} + + + +double +Alignment::_quatVolumeOverlap(double alpha1, double alpha2, const SiMath::Vector& q, const SiMath::Matrix& A) +{ + // compute qTAq + // first t = Aq + SiMath::Vector temp = SiMath::colProduct(q,A); + + // next qT*t + double r2 = temp.dotProd(q); + double vol = GCI2 * pow( (PI)/(alpha1 + alpha2),1.5); + vol *= exp(-r2); + + return vol; +} + + +","C++" +"In Silico","baoilleach/pharao","src/printHeader.cpp",".cpp","2484","55","/******************************************************************************* +printHeader.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""printHeader.h"" + + + +void +printHeader() +{ + std::cerr << ""+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"" << std::endl; + std::cerr << "" PHARAO v"" << PHARAO_VERSION << ""."" << PHARAO_RELEASE << ""."" << PHARAO_SUBRELEASE << "" | ""; + std::cerr << __DATE__ "" "" << __TIME__ << std::endl; + std::cerr << std::endl; +#ifdef _MSC_VER + std::cerr << "" -> MSVC: "" << _MSC_VER << std::endl; +#else + std::cerr << "" -> GCC: "" << __VERSION__ << std::endl; +#endif + std::cerr << "" -> Open Babel: "" << BABEL_VERSION << std::endl; + std::cerr << std::endl; + std::cerr << "" Copyright (C) 2005-2010 by Silicos NV (http://www.silicos.com)"" << std::endl; + std::cerr << std::endl; + std::cerr << "" This program is part of the Open Babel project."" << std::endl; + std::cerr << "" For more information, see http://openbabel.sourceforge.net"" << std::endl; + std::cerr << std::endl; + std::cerr << "" This program is free software; you can redistribute it and/or modify"" << std::endl; + std::cerr << "" it under the terms of the GNU General Public License as published by"" << std::endl; + std::cerr << "" the Free Software Foundation version 2 of the License."" << std::endl; + std::cerr << std::endl; + std::cerr << "" This program is distributed in the hope that it will be useful,"" << std::endl; + std::cerr << "" but WITHOUT ANY WARRANTY; without even the implied warranty of"" << std::endl; + std::cerr << "" MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the"" << std::endl; + std::cerr << "" GNU General Public License for more details."" << std::endl; + std::cerr << ""+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++"" << std::endl; + std::cerr << std::endl; +} +","C++" +"In Silico","baoilleach/pharao","src/addBest.cpp",".cpp","1515","51","/******************************************************************************* +addBest.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""addBest.h"" + + + +void +addBest(Result& res, const Options& uo, std::vector& resList) +{ + // 1) if 'resList' is not full -> add it. + // 2) if 'resList' is full but we have a result that is better than the worst + // one -> replace it. + // 3) else -> do nothing + + if (resList.size() < uo.best) + { + Result* newRes = new Result(res); + resList.push_back(newRes); + sort(resList.begin(), resList.end(), CompScore()); + return; + } + + Result* worst = *(resList.rbegin()); + if (worst->rankbyScore < res.rankbyScore) + { + delete worst; + resList.pop_back(); + Result* newRes = new Result(res); + resList.push_back(newRes); + sort(resList.begin(), resList.end(), CompScore()); + } +} +","C++" +"In Silico","baoilleach/pharao","src/compScore.cpp",".cpp","913","30","/******************************************************************************* +compScore.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""compScore.h"" + + + +bool +CompScore::operator()(const Result* res1, const Result* res2) +{ + return res1->rankbyScore > res2->rankbyScore; +} +","C++" +"In Silico","baoilleach/pharao","src/mainErr.cpp",".cpp","896","31","/******************************************************************************* +mainErr.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""mainErr.h"" + + + +void +mainErr(const std::string& msg) +{ + std::cerr << ""**MainError** "" << msg << std::endl; + exit(1); +} +","C++" +"In Silico","baoilleach/pharao","src/aromFuncCalc.cpp",".cpp","2071","68","/******************************************************************************* +aromFuncCalc.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""aromFuncCalc.h"" + + + +void +aromFuncCalc(OpenBabel::OBMol* mol, Pharmacophore* pharmacophore) +{ + // Create for every aromatic ring a pharmacophore point + bool rings(false); + OpenBabel::OBAtom* atom; + std::vector::iterator i; + for (atom = mol->BeginAtom(i); atom; atom = mol->NextAtom(i)) + { + if (atom->IsInRing() && atom->IsAromatic()) + { + rings = true; + break; + } + } + + if (rings) + { + OpenBabel::vector3 center; + OpenBabel::vector3 norm1; + OpenBabel::vector3 norm2; + std::vector nrings = mol->GetSSSR(); + std::vector::iterator ri; + for (ri = nrings.begin(); ri != nrings.end(); ++ri) + { + if ((*ri)->IsAromatic() && (*ri)->findCenterAndNormal(center, norm1, norm2)) + { + PharmacophorePoint p; + p.func = AROM; + p.point.x = center.x(); + p.point.y = center.y(); + p.point.z = center.z(); + p.hasNormal = true; + + p.normal.x = norm1.x() + center.x(); + p.normal.y = norm1.y() + center.y(); + p.normal.z = norm1.z() + center.z(); + p.alpha = funcSigma[AROM]; + pharmacophore->push_back(p); + } + } + } +} +","C++" +"In Silico","baoilleach/pharao","src/calcPharm.cpp",".cpp","1286","43","/******************************************************************************* +calcPharm.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""calcPharm.h"" + + + +void +calcPharm(OpenBabel::OBMol* m, Pharmacophore* p, const Options& uo) +{ + if (uo.funcGroupVec[AROM]) { aromFuncCalc(m, p); } + if (uo.funcGroupVec[HDON]) { hDonFuncCalc(m, p); } + if (uo.funcGroupVec[HACC]) { hAccFuncCalc(m, p); } + if (uo.funcGroupVec[LIPO]) { lipoFuncCalc(m, p); } + + if (uo.funcGroupVec[NEGC] || uo.funcGroupVec[POSC]) + { + chargeFuncCalc(m, p); + } + if (uo.funcGroupVec[HYBH] || uo.funcGroupVec[HYBL]) + { + hybridCalc(m, p); + } + return; +} +","C++" +"In Silico","baoilleach/pharao","src/pharMerger.cpp",".cpp","2786","119","/******************************************************************************* +pharMerger.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""pharMerger.h"" + + + +PharMerger::PharMerger(): + _deltaSigma(0.7), + _threshold(0.075) +{ +} + + + +void +PharMerger::merge(Pharmacophore& phar) +{ + typedef std::set Group; + Group::iterator itG; + + std::list list1; + std::list list2; + std::list::iterator itL1, itL2; + + Pharmacophore p; + + int n(phar.size()); + for (int i(0); i < n; ++i) + { + if (phar[i].func == EXCL) + { + p.push_back(phar[i]); + continue; + } + Group g; + g.insert(i); + for (int j = i+1; j < n ; ++j) + { + if (phar[i].func != phar[j].func) + { + continue; + } + if (VolumeOverlap(phar[i], phar[j], false) > _threshold) + { + g.insert(j); + } + } + list1.push_back(g); + } + + for (itL1 = list1.begin(); itL1 != list1.end(); ++itL1) + { + bool partOf(false); + for (itL2 = list1.begin(); itL2 != list1.end(); ++itL2) + { + if (itL1 == itL2) + { + continue; + } + if (includes(itL2->begin(), itL2->end(), itL1->begin(), itL1->end())) + { + partOf = true; + break; + } + } + if (!partOf) + { + if (itL1->size() == 1) + { + p.push_back(phar[*(itL1->begin())]); + } + else + { + list2.push_back(*itL1); + } + } + } + + for (itL1 = list2.begin(); itL1 != list2.end(); ++itL1) + { + PharmacophorePoint pp; + pp.func = phar[*(itL1->begin())].func; + double sigma = 0.0; + for (itG = itL1->begin(); itG != itL1->end(); ++itG) + { + (pp.point).x += (phar[*itG].point).x; + (pp.point).y += (phar[*itG].point).y; + (pp.point).z += (phar[*itG].point).z; + sigma += _deltaSigma/phar[*itG].alpha; + } + (pp.point).x /= itL1->size(); + (pp.point).y /= itL1->size(); + (pp.point).z /= itL1->size(); + pp.alpha = 1.0/sigma; + + p.push_back(pp); + } + + phar = p; +} +","C++" +"In Silico","baoilleach/pharao","src/chargeFuncCalc.cpp",".cpp","1656","56","/******************************************************************************* +chargeFuncCalc.cpp - Pharao + +Copyright (C) 2005-2010 by Silicos NV + +This file is part of the Open Babel project. +For more information, see + +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 version 2 of the License. + +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. +*******************************************************************************/ + + + +#include ""chargeFuncCalc.h"" + + + +void +chargeFuncCalc(OpenBabel::OBMol* m, Pharmacophore* pharmacophore) +{ + // Create for every non-zero formal charge a pharmacophore point + int charge; + for(OpenBabel::OBMolAtomIter atom(m); atom; ++atom) + { + charge = atom->GetFormalCharge(); + if (charge < 0) + { + PharmacophorePoint p; + p.func = NEGC; + p.point.x = atom->x(); + p.point.y = atom->y(); + p.point.z = atom->z(); + p.alpha = funcSigma[NEGC]; + p.hasNormal = false; + pharmacophore->push_back(p); + } + else if (charge > 0) + { + PharmacophorePoint p; + p.func = POSC; + p.point.x = atom->x(); + p.point.y = atom->y(); + p.point.z = atom->z(); + p.alpha = funcSigma[POSC]; + p.hasNormal = false; + pharmacophore->push_back(p); + } + } +}","C++" +"In Silico","PacificBiosciences/minorseq","doc/FUSE.md",".md","824","32","

+ fuse - Reduce alignment into its representative sequence +

+ +

+ +

+ +## Install +Install the minorseq suite using bioconda, more info [here](../README.md). +One of the binaries is called `fuse`. + +## Input data +*Fuse* operates on aligned records in the BAM format. +BAM files have to PacBio-compliant, meaning, cigar `M` is forbidden. + +## Scope +Current scope of *Fuse* is creation of a high-quality consensus sequence. +Fuse includes in-frame insertions with a certain distance to each other. +Major deletions are being removed. + +## Output +*Fuse* provides a FASTA file per input. Output file is provided by the second +argument. + +## Example +Simple example: +``` +fuse m530526.align.bam m530526.fasta +``` + +Output: `m530526.fasta`","Markdown" +"In Silico","PacificBiosciences/minorseq","doc/MIXDATA.md",".md","1447","56","

+ mixdata - Generate In-Silico Mixtures +

+ +## Install +Install the minorseq suite using bioconda, more info [here](../README.md). +The script is called `mixdata`. + +## About +*Mixdata* operates on BAM files. +It mixes given BAM files at a given ratio and coverage. +The first file is taken as the major clone, all following files are mixed in +as minors with the provided percentage. + +## Options +The *mixdata* script uses env variables for parametrization: + +|Parameter|Description|Default| +|-|-|-| +|`COVERAGE`|The coverage of the final mixed BAM file.|3000| +|`PERCENTAGE`|The percentage of each minor clone.|1| +|`OUTPUT_PREFIX`|The output prefix of the generated file.|mix| + +## Example +### Defaults +Mix three BAM files with 98/1/1% at 3000x: +``` +$ ls +clone_1.bam clone_2.bam clone_3.bam +$ mixdata clone_*.bam +$ samtools view mix.bam | wc -l +3000 +``` + +Equivalent call: +``` +$ mixdata clone_1.bam clone_2.bam clone_3.bam +``` + +### Configuration +Mix five BAM files with + - 10% minors + - `clone_2.bam` as major with 60% + - 6000x coverage + - file name `insilico.bam` +``` +$ ls +clone_1.bam clone_2.bam clone_3.bam clone_4.bam clone_5.bam +$ COVERAGE=6000 PERCENTAGE=10 OUTPUT_PREFIX=insilico mixdata clone_{2,1,3,4,5}.bam +$ samtools view insilico.bam | wc -l +6000 +``` + +## Dependencies +Only dependency is [samtools](https://github.com/samtools/samtools), which is +part of the SMRT-bundle that is officially being provided by PacBio.","Markdown" +"In Silico","PacificBiosciences/minorseq","doc/JULIETFLOW.md",".md","1317","50","

+ julietflow - Minor variant pipeline +

+ +## Install +Install the minorseq suite using bioconda, more info [here](../README.md). +The script is called `julietflow`. + +## Input data +*Julietflow* operates on unaligned ccs reads in the BAM format and a close +reference sequence. +BAM files have to PacBio-compliant, meaning, cigar `M` is forbidden, and input +reads have to be greater RQ 0.99. + +## Scope +Current scope of *julietflow* is automatization of the re-align workflow for +minor variant calling. + +## Output +*Julietflow* provides the html output of juliet in the current directory and the +intermediate files in `tmp/` if `-k` is set. + +## Filtering +*Juliet* relies on high-quality input data, please filter your ccs data and +downsample it to 6000x: +``` +INPUT=yourdata.ccs.bam +OUTPUT=yourdata.filtered.ccs.bam +samtools view -H ${INPUT} > ${INPUT}.tmp +samtools view ${INPUT} | grep ""rq:f:0.99\|rq:f:1"" >> ${INPUT}.tmp +samtools view -bS ${INPUT}.tmp > ${OUTPUT} +``` + +## Example +``` +julietflow -i m530526.ccs.bam -r hxb2.fasta +``` + +Output: `m530526_cleric.html` + +## Dependencies +All dependencies are automatically installed. + +## Help +Please use `--help` for more options of *julietflow*. + +## Workflow +

+ +

","Markdown" +"In Silico","PacificBiosciences/minorseq","doc/JULIET.md",".md","14691","389","

+ juliet - Minor Variant Caller +

+ +

+ +

+ +## TOC +* [Scope](#scope) +* [Performance](#performance) +* [Model](#model) +* [Install](#install) +* [Input data](#input-data) +* [Output](#output) +* [Target configuration](#target-configuration) +* [Phasing](#phasing) +* [FAQ](#faq) + +## Scope +Current scope of *Juliet* is identification of codon-wise variants in coding +regions. *Juliet* performs a reference-guided, de-novo variant discovery +and annotates known drug-resistance mutations. There is no technical +limitation with respect to the target organism or gene. +A first version of variant phasing is available. +Insertion and deletion variants are currently being ignored; +support will be added in a future version. + +## Performance + +Both, theoretical and empirical, performance estimates agree with the following +statement: + +At a coverage of 6000 CCS reads with a predicted accuracy (RQ) of >=0.99, +the false positive and false negative rates are below 1% and +0.001% (10-5), respectively. + +## Model + +The underlying model is a statistical test, comparing the number of observed +mutated codons to the number of expected mutations at a given position. +The particular test is a Bonferroni-corrected Fisher's Exact test. + +## Install + +Install the minorseq suite using bioconda, more info [here](../README.md). +One of those binary executables is called `juliet`. + +## Input data +*Juliet* operates on CCS records in the BAM format. +Reads should be created with [CCS2](https://github.com/PacificBiosciences/unanimity/blob/master/doc/PBCCS.md) +using the `--richQVs` option. +BAM files have to PacBio-compliant, meaning, cigar `M` is forbidden. +*Juliet* currently does not demultiplex barcoded data; +provide one BAM per barcode. +Input CCS reads should have a minimal predicted accuracy of 0.99, +filtering instruction [available here](JULIETFLOW.md#filtering). +Reads that are not primary or supplementary alignments, get ignored. + +## Output +*Juliet* provides a JSON and/or HTML file: +``` +$ juliet data.align.bam patientZero.html +$ juliet data.align.bam patientZero.json +$ juliet data.align.bam patientZero.html patientZero.json +``` + +The HTML page is a 1:1 conversion of the JSON file and contains the identical +information, but more human-readable. + +The HTML file contains four sections: + + + +### Section 1. Input data + +This section of the HTML output summarizes the data provided, the +exact call for *juliet*, and version of *juliet* for traceability +purposes + + + +### Section 2. Target Config + +Details of the provided target config are summarized for traceability. +The config version, reference name and length, and annotated genes. +Each gene with its name in bold, followed by the reference start, end positions, +and possibly known drug resistance mutations. + + + +### Section 3. Variant Discovery + +For each gene open reading frame, there is one overview table. +Each row represents a variant position. +Each variant position consists of the reference codon, reference amino acid, +relative amino acid position in the gene, the mutated codon, the mutated amino +acid, the coverage, and possible annotated drug resistance mutations. +Clicking the row will show counts of the multiple-sequence alignment counts of +the -3 to +3 context positions. + + + +### Section 4. Drug Summaries +This view summarizes the variants grouped by annotated drug mutations: + + + +## Target configuration + +*Juliet* is a multi-purpose minor variant caller that uses simple +target configuration files to define different genes of interest such +as HIV open reading frames to BCR-ABL kinase regions. There are preinstalled +configurations to ease batch applications and allow immediate reproducibility. +A target configuration may contain multiple coding regions within a gene +sequence and optional drug resistance mutation positions. + +### Predefined target config +Running on predefined genome such as HIV: +``` +$ juliet --config ""HIV"" data.align.bam patientZero.html +``` + + + +Currently available configs are: `HIV`, `ABL1` + +### Customized target configuration +To define your own target configuration, create a JSON file. The root child +genes contains a list of coding regions, with +begin and end, the name of the gene, and a list of drug resistent mutations +drms. Each DRM consists of its name and the positions it targets. The ""drms"" +field is optional. If provided, the referenceSequence is being used to call +mutations, otherwise it will be tested against the major codon. All indices are +with respect to the provided alignment space, 1-based, begin-inclusive and +end-exclusive `[)`. +Here is a ""hiv.json"" target configuration file: +``` +{ + ""genes"": [ + { + ""begin"": 2550, + ""drms"": [ + { + ""name"": ""fancy drug"", + ""positions"": [ ""M41L"" ] + } + ], + ""end"": 2700, + ""name"": ""Reverse Transcriptase"" + } + ], + ""referenceName"": ""my seq"", + ""referenceSequence"": ""TGGAAGGGCT..."", + ""version"": ""Free text to version your config files"", + ""databaseVersion"": ""DrugDB version x.y.z (last updated YYYY-MM-DD)"" +} +``` + +Run with customized target config using the `--config` option: +``` +$ juliet --config hiv.json data.align.bam patientZero.html +``` + + + +Valid formats for `drms/positions` + + ""103"" <- only the reference position + ""M130"" <- reference amino acid and ref pos + ""M103L"" <- ref aa, ref pos, mutated aa + ""M103LKA"" <- ref aa, ref pos, list of possible mutated aas + ""103L"" <- ref pos and mut aa + ""103LG"" <- ref pos and list mut aas + +Missing amino acids are processed as wildcard `*` + +Example + + { ""name"": ""ATV/r"", ""positions"": [ ""V32I"", ""L33"", ""46IL"", ""I54VTALM"", ""V82ATFS"", ""84"" ] } + +### No target config +If no target config has been specific, it is recommended to at least specify the +region of interest to mark the correct reading frame so amino acids are +correctly translated. The output will be labeled with `unknown` as gene name: +``` +$ juliet data.align.bam patientZero.html +``` + + + +## Phasing + +*Juliet's* default mode is to call amino-acid / codon variants independently. +Using `--mode-phasing`, variant calls from distinct haplotypes are clustered +and visualized in the HTML output. +The row-wise variant calls are ""transposed"" onto per column haplotypes. +Each haplotype has an ID: `[A-Z]{1}[a-z]?`. +For each variant, colored boxes in this row mark haplotypes that contain this +variant. +Colored boxes per haplotype / column indicate variants that co-occur. +Wild type, no variant, is represented by plain dark gray. +A color palette helps to distinguish between columns. + + + +The JSON variant positions has an additional `haplotype_hit` bool array +with the length equal to the number of haplotypes. Each entry indicates if that +variant is present in the haplotype. A `haplotype` block under the root of the +JSON file contains counts and read names. The order of those haplotypes matches +the order of all `haplotype_hit` arrays. + +# FAQ + +### Why PacBio CCS for minor variants? +PacBio systems have shown to have no systematic errors and allow for +generation of high-quality CCS reads. *Juliet* can reliably call minor variants +and phase co-occurring mutation patterns without employing complex and unreliable +computational models. + +### Why is my chemistry not supported? +Official support is for Sequel chemistries. If you use Sequel and your chemistry +is not supported, your *juliet* installation might be outdated. +If your chemistry is not officially supported, e.g. RSII, permissive mode is +active. In this case, higher type I and II errors might be observed. + +### My coverage is much lower than 6000x +There is a trade-off between coverage and FP/FN rates. +The following table shows the minimal and advised coverages for different +expected minor frequencies. For the minimal coverage, FP/FN rates may increase; +for reliable coverages, the [above mentioned](#performance) estimates hold: + +|Percentage|Minimal|Reliable| +|-|-|-| +|1%|2500X|6000X| +|5%|500X|1200X| +|10%|250X|600X| + +### Can I go lower than 1%? +Yes, but we haven't tested this yet. In theory, at a coverage of ~25000X, +a 0.1% minor should be identified. Be aware at that coverage, RT and PCR errors +will be **highly** abundant. Make sure to run as few PCR rounds as necessary. + +### Why do I see so many false positive calls? +Maybe you ran a control/titration experiment to test *juliet's* performance and +see many false positive calls. All of those are likely to be artifacts of your +sample preparation, due to RT and PCR errors. Try to limit the number of PCR +rounds and use high-fidelity enzymes. +If that does not help, sample your coverage down to the advised reliable +coverage. We tested clean samples, amplified in plasmids, and at 25000x there +is not a single false positive call. + +### Is the a minimum threshold for reported haplotypes? +Yes, we need to see at least 10 reads from the same haplotype to report it. + +### Why are there N bases in the overview? +We filter bases based on the individual QV tracks to remove possible +heteroduplexes. A filtered base shows up as N and does not count towards the +coverage. + +### Can I use overlapping regions? +Yes! Each gene is treated separately. Overlapping region, even with different +reading frames are possible. This is important for densely encoded genomes like +HIV. + +### Can I use non-coding regions? +Yes, but any codon that does not translate to an amino acid is being ignored. +If you want explicit support, please contact us. + +### Can I call a smaller window from a target config? +Use `--region` to specify the begin-end window to subset the target config. + +### What if I don't use --richQVs generating CCS reads? +Without the `--richQVs` information, the number of false positive calls might +be higher, as *juliet* is missing information to filter actual heteroduplexes in +the sample provided. + +### Why do some variants have no associated haploypes? +Scenarios as in the following figure may happen. In this case, all reads +associated to that variant contain a frame-shift deletion and +thus won't be reported. + + + +### Why are there no haplotype columns, even though I activated phasing? +In this case, each and every read has at least one deletion in one of the +identified variant codon positions; thus reads cannot be assigned naïvely. +An upcoming version might fix this. + +### What about hyper-variable regions like HIV envelope? +We currently do not support hyper-variable regions and the above mentioned +performance characterics do not hold. Feel free to test it on your own. + +### What database did you use for the HIV drug-resistance mutations? +We copied the major variants from [hivdb.stanford.edu](https://hivdb.stanford.edu). + +### Are you going to maintain the drug-resistance mutations in the target configs? +No. Juliet is a general purpose minor variant caller. +The integrated target configs are meant for a quick start. +It is the user's responsibility to ensure that the used target configs are +correct and up-to-date. + +### I need a config for my target organism / gene. +Please read [Customized Target Configuration](JULIET.md#customized-target-configuration). + +### Can you give a target config example other than HIV? +For BCR-ABL, using the ABL1 gene with the +[following reference NM_005157.5](https://www.ncbi.nlm.nih.gov/nuccore/NM_005157.5), +a typical target config could look like this: +``` +{ + ""genes"": [ + { + ""name"": ""ABL1"", + ""begin"": 193, + ""end"": 3585, + ""drms"": [ + { + ""name"": ""imatinib"", + ""positions"": [ ""T315AI"",""Y253H"",""E255KV"",""V299L"",""F317AICLV"",""F359CIV"" ] + }, + { + ""name"": ""dasatinib"", + ""positions"": [ ""T315AI"",""V299L"",""F317AICLV"" ] + }, + { + ""name"": ""nilotinib"", + ""positions"": [ ""T315AI"",""Y253H"",""E255KV"",""F359CIV"" ] + }, + { + ""name"": ""bosutinib"", + ""positions"": [ ""T315AI"" ] + } + ] + } + ], + ""referenceName"": ""NM_005157.5"", + ""referenceSequence"": ""TTAACAGGCGCGTCCC..."" +} +``` + +### Can I filter for a minimal percentage? +Yes, with `--min-perc`. For example, `--min-perc 1` will only show variant calls +with an observed abundance of more than 1%. + +### Can I skip major variant calls, while using a target config? +Maybe your output looks like a rainbow with most of the calls being the major +call above 90%: + + + +The option `--max-perc` skips variants above a given threshold. +For example, `--max-perc 90` will only show variant calls with an observed +abundance of less than 90%. This might also help to phase minor variants. + +Another example, where major calls dilute phased minor variant haplotypes below +the threshold. + + +**BEFORE (partial screenshot):** + + + +**AFTER:** + + + + +### Can I filter for drug-resistance mutations? +Yes, with `--drm-only` only known variants from the target config are being called. + +### What's up with the haplotype tooltips? +There are two types of tooltips in the haplotype part of the table. +The first tooltip is for the ""Haplotypes %"" and shows the number of reads that +count towards (a) actually reported haplotypes, (b) haplotypes that have +less than 10 reads and are not being reported, +and (c) haplotypes that are not suitable for phasing. +Those first three categories are mutually exclusive and their sum is the +total number of reads going into juliet. +For the (c), the three different marginals provide insights into the sample +quality; as they are marginals, they are not exclusive and can overlap. +The following screenshot shows a sample with bad PCR conditions: + + + +The second type of tooltip is for each haplotype percentage and shows the +number of reads contributing to this haplotype: + +","Markdown" +"In Silico","PacificBiosciences/minorseq","doc/INTRODUCTION.md",".md","1526","60","## How to run your sample 101 + +### Step 1 +A simple bioconda installation: + +```sh +conda install minorseq +``` + +-------- +### Step 2 +Create CCS2 reads from your sequel chip + +> Juliet currently uses PacBio CCS reads as input. The use of CCS rich QVs allows sensitive minor variant calling. + +``` +ccs m54000_170101_050702_3545456.subreadset.xml yourdata.ccs.bam +``` + +-------- +### Step 3 +Filter CCS reads as described here: [JULIETFLOW.md#filtering](JULIETFLOW.md#filtering) + +> To ensure a uniform noise profile, we filter to 99% predicted +> accuracy. Barcode demultiplexing might be done. + +-------- +### Step 4 +Download the reference sequence of interest as `ref.fasta` + +> Juliet currently calls amino acid variants to a given refrence +> sequence so they might be easily related to known variants. + +-------- +### Step 5 +Create a target-config for your gene as described here: [JULIET.md#target-configuration](JULIET.md#target-configuration) + +> The target-config specifies Open Reading and how specific amino +> acids should be labeled in output results (ie Disease Resistant +> Mutation variants) + + +-------- +### Step 6 +Run *julietflow* + +> The calling sequence is very simple taking sequencing reads, the +> reference, and the reference annotation config. + +``` +julietflow -i yourdata.filtered.ccs.bam -r ref.fasta -c targetconfig.json +``` + +-------- +### Step 7 +Interpret results in `yourdata.json` or `yourdata.html` + +> 'yourdata.html' is easily viewed in a web browser and reflects the +> underlying results stored in 'yourdata.json' +","Markdown" +"In Silico","PacificBiosciences/minorseq","doc/CLERIC.md",".md","1459","44","

+ Cleric - Swap BAM alignment reference +

+ +

+ +

+ +## Install +Install the minorseq suite using bioconda, more info [here](../README.md). +One of the binaries is called `cleric`. + +## Input data +*Cleric* operates on aligned records in the BAM format, the original reference +and the target reference as FASTA. +BAM file have to PacBio-compliant, meaning, cigar `M` is forbidden. +Two sequences have to be provided, either in individual files or combined in one. +The header of the original reference must match the reference name in the BAM. + +## Scope +Current scope of *Cleric* is converting a given alignment to a different +reference. This is done by aligning the original and target reference sequences. +A transitive alignment is used to generate the new alignment. + +## Output +*Cleric* provides a BAM file with the file named as provided via the last argument. + +## Example +Simple example: +``` +cleric m530526.align.bam reference.fasta new_ref.fasta cleric_output.bam +``` + +Or: +``` +cat reference.fasta new_ref.fasta > combined.fasta +cleric m530526.align.bam combined.fasta cleric_output.bam +``` + +## FAQ +### Cleric does not finish. +Runtime is linear in the number of reads provided. The alignment step runs a +Needleman-Wunsch; with NxM runtime. Please do not provide references with +lengths of human chromosomes, but concentrate on your actual amplicon target.","Markdown" +"In Silico","repseqio/library-imgt","exec.sh",".sh","4301","132","#!/bin/bash + +# Linux readlink -f alternative for Mac OS X +function readlinkUniversal() { + targetFile=$1 + + cd `dirname $targetFile` + targetFile=`basename $targetFile` + + # iterate down a (possible) chain of symlinks + while [ -L ""$targetFile"" ] + do + targetFile=`readlink $targetFile` + cd `dirname $targetFile` + targetFile=`basename $targetFile` + done + + # compute the canonicalized name by finding the physical path + # for the directory we're in and appending the target file. + phys_dir=`pwd -P` + result=$phys_dir/$targetFile + echo $result +} + +os=`uname` +delta=100 + +dir="""" + +case $os in + Darwin) + dir=$(dirname ""$(readlinkUniversal ""$0"")"") + ;; + Linux) + dir=""$(dirname ""$(readlink -f ""$0"")"")"" + ;; + *) + echo ""Unknown OS."" + exit 1 + ;; +esac + +input="""" +redownload=false + +while [[ $# > 0 ]] +do + key=""$1"" + shift + case $key in + -d) + redownload=true + ;; + *) + input=""${key}"" + ;; + esac +done + +cacheFolder=""${dir}/cache"" +outputFolder=""${dir}/output"" +mkdir -p ${cacheFolder} +mkdir -p ${outputFolder} + +wg=""wget --load-cookies ${cacheFolder}/imgt-cookies.txt --save-cookies ${cacheFolder}/imgt-cookies.txt -qO-"" +awkPipe=""awk '{ if ((NR>1)&&($0~/^>/)) { printf(""\n%s"", $0); } else if (NR==1) { printf(""%s"", $0); } else { printf(""\t%s"", $0); } }' | grep -F ""CH1"" - | tr ""\t"" ""\n"""" + +taxonId=$(jq -r '.taxonId' ${input}) +sNames=$(jq -r -c '.speciesNames' ${input}) + +jq -r -c '.rules[]' ${input} | \ +while read rule; +do + t=$(echo ""${rule}"" | jq -r '.ruleType') + if [[ ""${t}"" == ""import"" ]]; + then + output=$(echo ""${rule}"" | jq -r '.output') + chain=$(echo ""${rule}"" | jq -r '.chain') + geneType=$(echo ""${rule}"" | jq -r '.geneType') + pFastaFile=${cacheFolder}/$(basename ${output}).p.fasta + pFastaFileTemp=${cacheFolder}/$(basename ${output}).p.tmp + + # Downloading file + if [ ! -f ${pFastaFile} ] || [ ${redownload} == true ]; + then + rm -f ${pFastaFile} + echo ""${rule}"" | jq -r -c '.sources[]' | \ + while read src; + do + echo ""Downloading: ${src}"" + $wg ${src} | pup -p 'pre:last-of-type' | sed ""/^$/d"" | sed ""/<.*pre>/d"" | sed 's/ *//' >> ${pFastaFile} + if [[ ""$geneType"" == ""C"" ]]; + then + awk '{ if ((NR>1)&&($0~/^>/)) { printf(""\n%s"", $0); } else if (NR==1) { printf(""%s"", $0); } else { printf(""\t%s"", $0); } }' ${pFastaFile} | \ + grep -E ""CH1|EX1|REGION"" - | \ + tr ""\t"" ""\n"" >> ${pFastaFileTemp} + mv ${pFastaFileTemp} ${pFastaFile} + fi + done + fi + + # Loading points position + pointsP=$(echo ""${rule}"" | jq -r '.anchorPoints[] | select(.position != null) | ""-P"" + .point + ""="" + (.position | tostring)' | tr '\n' ' ') + pointsL=$(echo ""${rule}"" | jq -r '.anchorPoints[] | select(.aaPattern != null) | @sh ""-L"" + .point + ""="" + (.aaPattern | tostring)' | tr '\n' ' ') + points=""${pointsP} ${pointsL}"" + + repseqio fromPaddedFasta -f ${points} --ignore-duplicates --chain ${chain} --taxon-id ${taxonId} --gene-type ${geneType} \ + --name-index 1 --functionality-index 3 ${pFastaFile} ${dir}/${output}.fasta ${dir}/${output}.json + + cat ${dir}/${output}.json | jq "".[].speciesNames |= ${sNames}"" > ${dir}/${output}.json.tmp + mv ${dir}/${output}.json.tmp ${dir}/${output}.json + fi + + if [[ ""${t}"" == ""fixTraTrd"" ]]; + then + libFile=${dir}/$(echo ""${rule}"" | jq -r '.file') + cat ${libFile} | \ + jq '(.[].genes[] | select((.name | test(""^TRAV"")) == true) .chains) |= [""TRA""]' | \ + jq '(.[].genes[] | select((.name | test(""DV"")) == true) .chains) |= . + [""TRD""]' | \ + jq '(.[].genes[] | select((.name | test(""^TRDV"")) == true) .chains) |= [""TRD""]' > ${libFile}.tmp + mv ${libFile}.tmp ${libFile} + fi + + if [[ ""${t}"" == ""removeTra"" ]]; + then + libFile=${dir}/$(echo ""${rule}"" | jq -r '.file') + cat ${libFile} | \ + jq 'del(.[].genes[] | select((.name | test(""^TRAV"")) == true))' > ${libFile}.tmp + mv ${libFile}.tmp ${libFile} + fi +done +","Shell" +"In Silico","repseqio/library-imgt","build.sh",".sh","2095","85","#!/bin/bash + +# Linux readlink -f alternative for Mac OS X +function readlinkUniversal() { + targetFile=$1 + + cd `dirname $targetFile` + targetFile=`basename $targetFile` + + # iterate down a (possible) chain of symlinks + while [ -L ""$targetFile"" ] + do + targetFile=`readlink $targetFile` + cd `dirname $targetFile` + targetFile=`basename $targetFile` + done + + # compute the canonicalized name by finding the physical path + # for the directory we're in and appending the target file. + phys_dir=`pwd -P` + result=$phys_dir/$targetFile + echo $result +} + +os=`uname` +delta=100 + +dir="""" + +case $os in + Darwin) + dir=$(dirname ""$(readlinkUniversal ""$0"")"") + ;; + Linux) + dir=""$(dirname ""$(readlink -f ""$0"")"")"" + ;; + *) + echo ""Unknown OS."" + exit 1 + ;; +esac + +function loge() { + echo ""$1"" + exit 1 +} + +# Checks that required software is installed in the system +type jq >/dev/null 2>&1 || loge ""Please install \""jq\"". Try \""brew install jq\"" or \""apt-get install jq\""."" +type pup >/dev/null 2>&1 || loge ""Please install \""pup\"". Try \""brew install pup\"" or \""apt-get install pup\""."" + +cacheFolder=""${dir}/cache"" +outputFolder=""${dir}/output"" + +if [[ ""$1"" == ""full"" ]]; +then + rm -rf ${cacheFolder} + rm -rf ${outputFolder} +fi + +mkdir -p ${cacheFolder} +mkdir -p ${outputFolder} + +wg=""wget --load-cookies ${cacheFolder}/imgt-cookies.txt --save-cookies ${cacheFolder}/imgt-cookies.txt -qO-"" + +for rule in ${dir}/rules/*.json; +do + ${dir}/exec.sh ${rule} +done + +tomerge=() + +for file in ${dir}/output/*.json; +do + out=${outputFolder}/$(basename ${file}).compiled + repseqio compile -f ${file} ${out} + tomerge+=(""${out}"") +done + +# imgtVersion=$($wg http://www.imgt.org/IMGT_vquest/share/textes/ | pup -p 'a[href=""./datareleases.html""] text{}' | sed 's/ *//g') +imgtVersion=$($wg http://www.imgt.org/IMGT_vquest/data_releases | grep '' | grep 'Release' | head -n 1 | sed 's:.*Release *::' | sed 's: *(.*::') +tag=$(git describe --always --tags) + +repseqio merge -f ${tomerge[@]} ${dir}/imgt.${imgtVersion}.s${tag}.json.gz +","Shell" +"In Silico","peterhcharlton/pwdb","pwdb_v1.0/publication_specific_scripts/ppg_components_plot.m",".m","7538","257","function ppg_components_plot +% ppg_components_plot creates a plot of the PPG signal illustrating the +% origins of light attenuation (arterial blood, venous blood and other +% tissues). +% +% ppg_components_plot +% +% This file creates an image adapted from: +% Peter H Charlton. (2018, August). Capitalising on Smart +% Wearables to Improve Health Monitoring. Zenodo. +% DOI: http://doi.org/10.5281/zenodo.1406011 +% Please cite this publication when using this image. +% +% Output: +% an EPS image in the same folder as this script +% +% Comments, Questions, Criticisms, Feedback, Contributions: +% See: http://peterhcharlton.github.io/RRest/contributions.html +% +% Licence: +% please see the accompanying file named ""LICENSE"" +% + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% This function contains the path of the folder in which to store the data +% (which requires modification) +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +up = setup_up; + +create_folders(up); + +download_data(up); + +extract_data(up); + +plot_data(up); + +end + +function up = setup_up + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% The path of the folder in which to store the data +% (which requires modification) +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +up.paths.folders.root = ['/Users/petercharlton/Desktop/temp/ppg_components_signals', filesep]; + +% remaining paths +up.paths.folders.data = [up.paths.folders.root, 'raw_data', filesep]; +up.paths.folders.plot = [up.paths.folders.root, 'plots', filesep]; +up.paths.converted_data = [up.paths.folders.data, 'converted_data']; + +% download paths +up.files.web = {'https://www.physionet.org/physiobank/database/bidmc/bidmc05'}; +up.files.times.deb = [3]; +up.files.times.fin = [8]; +up.files.sigs.names = {{'ppg'}}; +up.files.sigs.nos = {[2]}; + +close all + +% Check that the WFDB Matlab Toolbox has been installed +if ~exist('getWfdbClass', 'file') + error('Couldn''t find the WFDB Matlab Toolbox. Please install as described at the top of the file.') +end + +% Check that the folder in which to store downloaded data exists +if ~exist(up.paths.folders.root, 'dir') +% error('Couldn''t find the folder in which to store the data.') +end + +end + +function create_folders(up) + +folders = fieldnames(up.paths.folders); +for folder_no = 1 : length(folders) + eval(['curr_folder = up.paths.folders.' folders{folder_no} ';']) + + if ~exist(curr_folder) + mkdir(curr_folder) + end + +end + +end + +function download_data(up) + +exts = {'.hea', '.dat'}; + +for file_no = 1 : length(up.files.web) + + url = up.files.web{file_no}; + + temp = strfind(url, '/'); + filename = url(temp(end)+1:end); + filepath = [up.paths.folders.data, filename]; + + for ext_no = 1 : length(exts) + curr_ext = exts{ext_no}; + expected_outfilename = [filepath,curr_ext]; + if ~exist(expected_outfilename, 'file') + outfilename = websave([filepath,curr_ext],[url, curr_ext]); + end + end + +end + +end + +function extract_data(up) + +if exist([up.paths.converted_data, '.mat']) + return +end + +counter_no = 0; +for file_no = 1 : length(up.files.web) + + % Extract data from downloaded file + url = up.files.web{file_no}; + temp = strfind(url, '/'); + filename = url(temp(end)+1:end); + filepath = [up.paths.folders.data, filename]; + cd(up.paths.folders.data) + [signal,Fs,tm]=rdsamp(filename, [],[]); + + % Extract required data + no_sigs = length(up.files.sigs.names{file_no}); + for sig_no = 1 : no_sigs + curr_sig_no = up.files.sigs.nos{file_no}(sig_no); + curr_times = [up.files.times.deb(file_no), up.files.times.fin(file_no)]; + rel_els = find(tm>= curr_times(1) & tm <= curr_times(2)); + curr_sig.v = signal(rel_els,curr_sig_no); + curr_sig.t = [0:length(curr_sig.v)-1]./Fs; + + % store data + counter_no = counter_no+1; + data(counter_no).sig = curr_sig.v; + data(counter_no).t = curr_sig.t; + data(counter_no).db = strrep(url(temp(end-1)+1:temp(end)-1), 'db', ''); + data(counter_no).name = up.files.sigs.names{file_no}{sig_no}; + end + +end + +save(up.paths.converted_data, 'data') + +end + +function plot_data(up) + + +%% Make short PPG Plot + +% setup +load(up.paths.converted_data) +ftsize = 24; +pos_long = [20,20,500,250]; +pos_ppg = [20,20,600,600]; +pos_short = [20,20,1000,470]; + +% Extract data +temp = extractfield(data, 'name'); +sig_no = find(strcmp(temp, 'ppg')); clear temp +curr = data(sig_no); + +curr.fix = 1*ones(size(curr.t)); +curr.ven = curr.fix + 0.7 + 0.1*sin(curr.t*2*pi/4); +curr.sig = (curr.sig-min(curr.sig))/(max(curr.sig)-min(curr.sig)); +curr.ppg = curr.ven + 0.5 + curr.sig(:)'; + +%plot(curr.t, curr.fix), hold on, plot(curr.t, curr.ven), plot(curr.t, curr.ppg) + +% - Make figure (just PPG) +figure('Position', pos_short) +plot(curr.t, curr.ppg, 'k', 'LineWidth', 2) +ylim([0 3.31]) +set(gca, 'FontSize', ftsize, 'YTick', []) +xlabel('Time (s)', 'FontSize', ftsize) +title('Raw Photoplethysmogram', 'FontSize', ftsize) +box off +savepath = [up.paths.folders.plot, 'short_raw_ppg_init']; +print(savepath, '-depsc') +print(savepath, '-dpng') +close all + +% - Make figure (components) + +% fill in +figure('Position', pos_short) +h = area(curr.t, curr.ppg, 'LineStyle', 'none'); hold on +h.FaceColor = [1,0,0]; +plot(curr.t, curr.ppg, 'k', 'LineWidth', 2) +%plot(curr.t, curr.ven, '--k', 'LineWidth', 2) +h = area(curr.t, curr.ven, 'LineStyle', 'none'); hold on +h.FaceColor = [0,0,1]; +plot(curr.t, curr.ven, '--k', 'LineWidth', 2) +h = area(curr.t, curr.fix, 'LineStyle', 'none'); hold on +h.FaceColor = [0.8,0.8,0.8]; +plot(curr.t, curr.fix, '--k', 'LineWidth', 2) +ylim([0 3.31]) +set(gca, 'FontSize', ftsize, 'YTick', []) +xlabel('Time (s)', 'FontSize', ftsize) +ylab = ylabel({'PPG','(au)'}, 'FontSize', ftsize, 'Rotation', 0); +set(ylab, 'position', get(ylab,'position')-[0.2,0.1,0]); +%title('Raw Photoplethysmogram', 'FontSize', ftsize) +box off + +% annotate +dim = [.2 .19 .1 .1]; +str = 'Other Tissues'; +annotation('textbox',dim,'String',str,'FitBoxToText','on', 'LineStyle', 'none', 'BackgroundColor', [1,1,1], 'FontSize', ftsize, 'HorizontalAlignment', 'center'); +dim = [.2 .40 .1 .1]; +str = 'Venous Blood'; +annotation('textbox',dim,'String',str,'FitBoxToText','on', 'LineStyle', 'none', 'BackgroundColor', [1,1,1], 'FontSize', ftsize, 'HorizontalAlignment', 'center'); +dim = [.2 .58 .1 .1]; +str = 'Arterial Blood'; +annotation('textbox',dim,'String',str,'FitBoxToText','on', 'LineStyle', 'none', 'BackgroundColor', [1,1,1], 'FontSize', ftsize, 'HorizontalAlignment', 'center'); + +savepath = [up.paths.folders.plot, 'short_raw_ppg']; +print(savepath, '-depsc') +print(savepath, '-dpng') +close all + +end + +function sig_info = get_sig_info(curr_name) + +switch curr_name + case 'ecg' + sig_info.name = 'Electrocardiogram'; + sig_info.units = 'mV'; + case 'scg' + sig_info.name = 'Seismocardiogram'; + sig_info.units = ''; + case 'ppg' + sig_info.name = 'Photoplethysmogram'; + sig_info.units = ''; + case 'abp' + sig_info.name = 'Arterial Blood Pressure'; + sig_info.units = ''; + case 'imp' + sig_info.name = 'Impedance Pneumography'; + sig_info.units = ''; + case 'gyro' + sig_info.name = 'Gyroscope'; + sig_info.units = ''; + case 'accel' + sig_info.name = 'Acceleration'; + sig_info.units = ''; + +end + +end +","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/calculate_pwdb_input_parameters.m",".m","129399","2593","function parameters = calculate_pwdb_input_parameters +% CALCULATE_PWDB_INPUT_PARAMETERS calculates a set of Nektar1D input +% parameters for the virtual subjects in the pwdb Pulse Wave DataBase. +% +% calculate_pwdb_input_parameters +% +% Inputs: none required - please see the ""setup_up"" +% function below to adjust the virtual database configuration +% to your needs. +% +% Outputs: - parameters: a Matlab variable containing the input +% parameters. +% - a single file called ""inputs.mat"", which contains the +% parameters variable required by Nektar1D input files. This +% will be saved in the path specified in ""setup_up"", which +% should be adjusted before running this script. +% +% Accompanying Article: +% This code is provided to facilitate reproduction of the Pulse Wave +% Database described in: +% Charlton P.H. et al. Modelling arterial pulse waves in healthy +% ageing: in silico evaluation of haemodynamics and +% pulse wave indices, ~~ under review ~~ +% DOI: ~~ tbc ~~ +% Further information on the pwdb Pulse Wave Database is provided in +% this article and at the project website: +% https://peterhcharlton.github.io/pwdb +% +% Author: Peter H. Charlton +% +% Licence: +% Permission is hereby granted, free of charge, to any person obtaining a copy +% of this software and associated documentation files (the ""Software""), to deal +% in the Software without restriction, including without limitation the rights +% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +% copies of the Software, and to permit persons to whom the Software is +% furnished to do so, subject to the following conditions: +% +% The above copyright notice and this permission notice shall be included in all +% copies or substantial portions of the Software. +% +% THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +% SOFTWARE. +% +% Copyright (C) 2019 King's College London +% +% v.1.0 Peter H. Charlton, King's College London + +%% Settings +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%%%% SETTINGS TO CHANGE: This function specifies where to save the outputs, %%%% +%%%% and which database configuration to use %%%% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +up = setup_up; +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +%% Specify desired virtual database characteristics +vdb_characteristics = setup_vdb_characteristics(up); % Specifies variations (in terms of the no. of SD) in each parameter at baseline age and other ages + +%% Make plots of how parameters change with age and vary +if up.do_plot, make_param_plots(up); end + +%% Calculate equations for input parameters as a function of age +eqns = calculate_equations(up); + +%% Find variations in parameters for each simulation +variations = find_vdb_variations(vdb_characteristics); % Specifies the variation of each parameter (in terms of SD) from the age-specific baseline value for each simulation + +%% Find values of parameters for each simulation +parameters = calculate_vdb_parameters(variations, up); % Calculates the desired model parameter values for each simulation + +%% Add fixed Wk vascular bed parameters +parameters = add_wk_vascular_bed_parameters(parameters); + +%% Set fixed simulation parameters +parameters = specify_fixed_simulation_parameters(parameters); + +%% Make plots of expected haemodynamic characteristics +if up.do_plot, make_haemod_plots(parameters, up); end + +%% Generate aortic inflow waveforms +inflow = generate_aortic_inflow_waveforms(parameters); + +%% Save parameters to file +save([up.savefolder, 'inputs'], 'parameters', 'inflow') + +end + +function up = setup_up +% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%%%% This line specifies the where the outputs are saved %%%% +%%%% - This should be changed for your computer %%%% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +up.savefolder = '/Users/petercharlton/Documents/Data/Nektar1D/ageing_sims/'; % (needs to have a slash at the end) + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%%%% These lines specify which database configuration to use %%%% +%%%% - This should be changed according to your needs %%%% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +possible_configs = {'pwdb', 'initial_simulations', 'independent_variations', 'baseline_subject', 'baseline_subjects_at_each_age'}; +up.db_config = possible_configs{1}; % specifies which of the configurations to use. + +% See this webpage for further details on each of the configurations: +% https://github.com/peterhcharlton/pwdb/wiki/Generating-the-Input-Files + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +%%%% The rest of this function specifies some preliminary settings, which don't need to be changed %%%% + +% Initial setup +fprintf(['\n\n ~~~~~ Calculating input parameters for ' upper(up.db_config) ' database ~~~~~']) +fprintf('\n - Setting up universal parameters') +close all + +% add subdirectories within this file's directory to the path +[curr_folder, ~, ~] = fileparts(mfilename('fullpath')); +addpath(genpath(curr_folder)); + +% Specify all possible ages (only a subset of these will actually be used in the database): +up.mod_ages = 25:75; +% Specify the baseline age, which is the one the baseline model configuration corresponds to: +up.baseline_age = 25; + +% Give details of the Excel file which contains the baseline model geometry: +up.network_spec_sheet = 'Haemod 116 segments'; +curr_file_root = fileparts(mfilename('fullpath')); +up.network_spec_file = [curr_file_root, filesep, 'Input Data', filesep, '116_artery_model.txt']; + +% Specify whether or not to make plots +up.do_plot = 0; + +end + +function vdb_characteristics = setup_vdb_characteristics(up) +% This function specifies each of the input parameters for the virtual +% database configuration selected in the up.db_config variable, in the +% setup_up function. + +fprintf('\n - Setting up parameter variations across database subjects') + +%% Ages +% Specify the age of the baseline subject +vdb_characteristics.age.baseline = up.baseline_age; + +%% - Physiological Properties +% +% Specify for each property: +% - The number of values of this property to be changed: +% (a) in combination with other properties (i.e. if both HR and SV are varied in combination, then all possible combinations of these properties will be simulated) +% (b) independently of other properties (i.e. keep all properties except one at the mean value, whilst that property is varied on its own. Then repeat for other properties which are to be varied). +% at: +% (i) the baseline age (usually 25 years), and +% (ii) other ages (usually 35, 45, 55, 65 and 75 years). +% - The range over which to vary the property, specified as the number of +% SDs from the mean value. +% +% e.g. a value of ""2"" for the number of variations, and a value of ""1"" for +% the number of SDs, means that the parameter will be varied twice over the +% range of +/- 1 SD. i.e. it will take the values: +% [mean - 1SD, mean, mean + 1SD] +% +% e.g. a value of ""4"" for the number of variations, and a value of ""1"" for +% the number of SDs, means that the parameter will be varied four times +% over the range of +/- 1 SD. i.e. it will take the values: +% [mean - 1SD, mean - 0.5SD, mean, mean + 0.5SD, mean + 1SD] + +switch up.db_config + + %% %% %% Initial Simulations %% %% %% + % These consist of changing 10 parameters independently by +/- 1SD for the + % 25-year old baseline model, resulting in a total of 21 simulations (a + % baseline simulation, and then 2 simulations per parameter). + case 'initial_simulations' + + vdb_characteristics.age.all = 25; + + %% Cardiac properties + + % - Heart Rate (HR) + vdb_characteristics.hr.no_combination_variations_at_other_ages = 0; + vdb_characteristics.hr.no_independent_variations_at_other_ages = 0; + vdb_characteristics.hr.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.hr.no_independent_variations_at_baseline_age = 2; + vdb_characteristics.hr.variation_sds = 1; + + % - Stroke Volume (SV) + vdb_characteristics.sv.no_combination_variations_at_other_ages = 0; + vdb_characteristics.sv.no_independent_variations_at_other_ages = 0; + vdb_characteristics.sv.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.sv.no_independent_variations_at_baseline_age = 2; + vdb_characteristics.sv.variation_sds = 1; + + % - Left Ventricular Ejection Time (LVET): duration of systole + vdb_characteristics.lvet.no_combination_variations_at_other_ages = 0; + vdb_characteristics.lvet.no_independent_variations_at_other_ages = 0; + vdb_characteristics.lvet.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.lvet.no_independent_variations_at_baseline_age = 2; + vdb_characteristics.lvet.variation_sds = 1; + + % - Time to Peak Flow (t_pf): the time from the beginning of the aortic flow wave to its peak + vdb_characteristics.t_pf.no_combination_variations_at_other_ages = 0; + vdb_characteristics.t_pf.no_independent_variations_at_other_ages = 0; + vdb_characteristics.t_pf.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.t_pf.no_independent_variations_at_baseline_age = 2; + vdb_characteristics.t_pf.variation_sds = 1; + + % - Regurgitation volume (reg_vol): the amount of backwards flow at the end of systole + vdb_characteristics.reg_vol.no_combination_variations_at_other_ages = 0; + vdb_characteristics.reg_vol.no_independent_variations_at_other_ages = 0; + vdb_characteristics.reg_vol.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.reg_vol.no_independent_variations_at_baseline_age = 2; + vdb_characteristics.reg_vol.variation_sds = 1; + + %% Vascular bed properties + + % - Peripheral Vascular Compliance (pvc) + vdb_characteristics.pvc.no_combination_variations_at_other_ages = 0; + vdb_characteristics.pvc.no_independent_variations_at_other_ages = 0; + vdb_characteristics.pvc.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.pvc.no_independent_variations_at_baseline_age = 2; + vdb_characteristics.pvc.variation_sds = 1; + + % - Outflow Pressure (p_out) + vdb_characteristics.p_out.no_combination_variations_at_other_ages = 0; + vdb_characteristics.p_out.no_independent_variations_at_other_ages = 0; + vdb_characteristics.p_out.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.p_out.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.p_out.variation_sds = 0; + + % - Mean Blood Pressure (mbp): the peripheral vascular resistance is set to achieve the desired value of MBP + vdb_characteristics.mbp.no_combination_variations_at_other_ages = 0; + vdb_characteristics.mbp.no_independent_variations_at_other_ages = 0; + vdb_characteristics.mbp.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.mbp.no_independent_variations_at_baseline_age = 2; + vdb_characteristics.mbp.variation_sds = 1; + + % - Reflections logical: whether to include reflections + vdb_characteristics.reflect_log.no_combination_variations_at_other_ages = 0; + vdb_characteristics.reflect_log.no_independent_variations_at_other_ages = 0; + vdb_characteristics.reflect_log.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.reflect_log.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.reflect_log.variation_sds = 0; + + %% Arterial properties + + % - Pulse Wave Velocity (pwv) + vdb_characteristics.pwv.no_combination_variations_at_other_ages = 0; + vdb_characteristics.pwv.no_independent_variations_at_other_ages = 0; + vdb_characteristics.pwv.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.pwv.no_independent_variations_at_baseline_age = 2; + vdb_characteristics.pwv.variation_sds = 1; + + % - Diastolic blood pressure (dbp): the pressure corresponding to the initial luminal areas (note that this has very little affect) + vdb_characteristics.dbp.no_combination_variations_at_other_ages = 0; + vdb_characteristics.dbp.no_independent_variations_at_other_ages = 0; + vdb_characteristics.dbp.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.dbp.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.dbp.variation_sds = 0; + + % - Pressure drop (p_drop): the assumed pressure drop from the aortic root to the end of the arterial network + vdb_characteristics.p_drop.no_combination_variations_at_other_ages = 0; + vdb_characteristics.p_drop.no_independent_variations_at_other_ages = 0; + vdb_characteristics.p_drop.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.p_drop.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.p_drop.variation_sds = 0; + + % - Length of the proximal aorta (len) + vdb_characteristics.len.no_combination_variations_at_other_ages = 0; + vdb_characteristics.len.no_independent_variations_at_other_ages = 0; + vdb_characteristics.len.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.len.no_independent_variations_at_baseline_age = 2; + vdb_characteristics.len.variation_sds = 1; + + % - Diameter of the larger arteries (dia, e.g. ascending, descending aorta, carotid, brachial, ...) + vdb_characteristics.dia.no_combination_variations_at_other_ages = 0; + vdb_characteristics.dia.no_independent_variations_at_other_ages = 0; + vdb_characteristics.dia.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.dia.no_independent_variations_at_baseline_age = 2; + vdb_characteristics.dia.variation_sds = 1; + + % - Wall viscosity + vdb_characteristics.gamma.no_combination_variations_at_other_ages = 0; + vdb_characteristics.gamma.no_independent_variations_at_other_ages = 0; + vdb_characteristics.gamma.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.gamma.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.gamma.variation_sds = 0; + + %% Blood properties + + % - Blood density (rho) + vdb_characteristics.rho.no_combination_variations_at_other_ages = 0; + vdb_characteristics.rho.no_independent_variations_at_other_ages = 0; + vdb_characteristics.rho.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.rho.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.rho.variation_sds = 0; + + % - Blood viscosity (mu) + vdb_characteristics.mu.no_combination_variations_at_other_ages = 0; + vdb_characteristics.mu.no_independent_variations_at_other_ages = 0; + vdb_characteristics.mu.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.mu.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.mu.variation_sds = 0; + + %% - Simulation properties + + % - alpha: controls the shape of the velocity profile (assumed to be constant throughout the arterial tree) + vdb_characteristics.alpha.no_combination_variations_at_other_ages = 0; + vdb_characteristics.alpha.no_independent_variations_at_other_ages = 0; + vdb_characteristics.alpha.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.alpha.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.alpha.variation_sds = 0; + + % - time_step: which is the numerical time step used for calculations + vdb_characteristics.time_step.no_combination_variations_at_other_ages = 0; + vdb_characteristics.time_step.no_independent_variations_at_other_ages = 0; + vdb_characteristics.time_step.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.time_step.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.time_step.variation_sds = 0; + + % - visco_elastic_log: determines whether the simulations are elastic or visco-elastic + vdb_characteristics.visco_elastic_log.no_combination_variations_at_other_ages = 0; + vdb_characteristics.visco_elastic_log.no_independent_variations_at_other_ages = 0; + vdb_characteristics.visco_elastic_log.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.visco_elastic_log.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.visco_elastic_log.variation_sds = 0; + + + %% %% %% Pulse Wave Database %% %% %% + % These consist of changing 6 parameters in combination with each other by + % +/- 1SD for all ages (25, 35, 45, 55, 65 and 75), resulting in a total of + % 4,374 simulations. This is the configuration used for the Pulse Wave + % Database. + case 'pwdb' + + vdb_characteristics.age.all = 25:10:75; % Ten-year intervals + + %% Cardiac properties + + % - Heart Rate (HR) + vdb_characteristics.hr.no_combination_variations_at_other_ages = 2; + vdb_characteristics.hr.no_independent_variations_at_other_ages = 0; + vdb_characteristics.hr.no_combination_variations_at_baseline_age = 2; + vdb_characteristics.hr.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.hr.variation_sds = 1; + + % - Stroke Volume (SV) + vdb_characteristics.sv.no_combination_variations_at_other_ages = 2; + vdb_characteristics.sv.no_independent_variations_at_other_ages = 0; + vdb_characteristics.sv.no_combination_variations_at_baseline_age = 2; + vdb_characteristics.sv.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.sv.variation_sds = 1; + + % - Left Ventricular Ejection Time (LVET): duration of systole + vdb_characteristics.lvet.no_combination_variations_at_other_ages = 2; + vdb_characteristics.lvet.no_independent_variations_at_other_ages = 0; + vdb_characteristics.lvet.no_combination_variations_at_baseline_age = 2; + vdb_characteristics.lvet.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.lvet.variation_sds = 1; + + % - Time to Peak Flow (t_pf): the time from the beginning of the aortic flow wave to its peak + vdb_characteristics.t_pf.no_combination_variations_at_other_ages = 0; + vdb_characteristics.t_pf.no_independent_variations_at_other_ages = 0; + vdb_characteristics.t_pf.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.t_pf.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.t_pf.variation_sds = 1; + + % - Regurgitation volume (reg_vol): the amount of backwards flow at the end of systole + vdb_characteristics.reg_vol.no_combination_variations_at_other_ages = 0; + vdb_characteristics.reg_vol.no_independent_variations_at_other_ages = 0; + vdb_characteristics.reg_vol.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.reg_vol.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.reg_vol.variation_sds = 1; + + % - Reflections logical: whether to include reflections + vdb_characteristics.reflect_log.no_combination_variations_at_other_ages = 0; + vdb_characteristics.reflect_log.no_independent_variations_at_other_ages = 0; + vdb_characteristics.reflect_log.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.reflect_log.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.reflect_log.variation_sds = 0; + + %% Vascular bed properties + + % - Peripheral Vascular Compliance (pvc) + vdb_characteristics.pvc.no_combination_variations_at_other_ages = 0; + vdb_characteristics.pvc.no_independent_variations_at_other_ages = 0; + vdb_characteristics.pvc.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.pvc.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.pvc.variation_sds = 1; + + % - Outflow Pressure (p_out) + vdb_characteristics.p_out.no_combination_variations_at_other_ages = 0; + vdb_characteristics.p_out.no_independent_variations_at_other_ages = 0; + vdb_characteristics.p_out.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.p_out.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.p_out.variation_sds = 1; + + % - Mean Blood Pressure (mbp): the peripheral vascular resistance is set to achieve the desired value of MBP + vdb_characteristics.mbp.no_combination_variations_at_other_ages = 2; + vdb_characteristics.mbp.no_independent_variations_at_other_ages = 0; + vdb_characteristics.mbp.no_combination_variations_at_baseline_age = 2; + vdb_characteristics.mbp.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.mbp.variation_sds = 1; + + %% Arterial properties + + % - Pulse Wave Velocity (pwv) + vdb_characteristics.pwv.no_combination_variations_at_other_ages = 2; + vdb_characteristics.pwv.no_independent_variations_at_other_ages = 0; + vdb_characteristics.pwv.no_combination_variations_at_baseline_age = 2; + vdb_characteristics.pwv.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.pwv.variation_sds = 1; + + % - Diastolic blood pressure (dbp): the pressure corresponding to the initial luminal areas (note that this has very little affect) + vdb_characteristics.dbp.no_combination_variations_at_other_ages = 0; + vdb_characteristics.dbp.no_independent_variations_at_other_ages = 0; + vdb_characteristics.dbp.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.dbp.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.dbp.variation_sds = 0; + + % - Pressure drop (p_drop): the assumed pressure drop from the aortic root to the end of the arterial network + vdb_characteristics.p_drop.no_combination_variations_at_other_ages = 0; + vdb_characteristics.p_drop.no_independent_variations_at_other_ages = 0; + vdb_characteristics.p_drop.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.p_drop.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.p_drop.variation_sds = 0; + + % - Length of the proximal aorta (len) + vdb_characteristics.len.no_combination_variations_at_other_ages = 0; + vdb_characteristics.len.no_independent_variations_at_other_ages = 0; + vdb_characteristics.len.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.len.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.len.variation_sds = 1; + + % - Diameter of the larger arteries (dia, e.g. ascending, descending aorta, carotid, brachial, ...) + vdb_characteristics.dia.no_combination_variations_at_other_ages = 2; + vdb_characteristics.dia.no_independent_variations_at_other_ages = 0; + vdb_characteristics.dia.no_combination_variations_at_baseline_age = 2; + vdb_characteristics.dia.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.dia.variation_sds = 1; + + % - Wall viscosity + vdb_characteristics.gamma.no_combination_variations_at_other_ages = 0; + vdb_characteristics.gamma.no_independent_variations_at_other_ages = 0; + vdb_characteristics.gamma.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.gamma.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.gamma.variation_sds = 0; + + %% Blood properties + + % - Blood density (rho) + vdb_characteristics.rho.no_combination_variations_at_other_ages = 0; + vdb_characteristics.rho.no_independent_variations_at_other_ages = 0; + vdb_characteristics.rho.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.rho.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.rho.variation_sds = 0; + + % - Blood viscosity (mu) + vdb_characteristics.mu.no_combination_variations_at_other_ages = 0; + vdb_characteristics.mu.no_independent_variations_at_other_ages = 0; + vdb_characteristics.mu.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.mu.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.mu.variation_sds = 0; + + %% - Simulation properties + + % - alpha: controls the shape of the velocity profile (assumed to be constant throughout the arterial tree) + vdb_characteristics.alpha.no_combination_variations_at_other_ages = 0; + vdb_characteristics.alpha.no_independent_variations_at_other_ages = 0; + vdb_characteristics.alpha.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.alpha.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.alpha.variation_sds = 0; + + % - time_step: which is the numerical time step used for calculations + vdb_characteristics.time_step.no_combination_variations_at_other_ages = 0; + vdb_characteristics.time_step.no_independent_variations_at_other_ages = 0; + vdb_characteristics.time_step.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.time_step.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.time_step.variation_sds = 0; + + % - visco_elastic_log: determines whether the simulations are elastic or visco-elastic + vdb_characteristics.visco_elastic_log.no_combination_variations_at_other_ages = 0; + vdb_characteristics.visco_elastic_log.no_independent_variations_at_other_ages = 0; + vdb_characteristics.visco_elastic_log.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.visco_elastic_log.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.visco_elastic_log.variation_sds = 0; + + %% %% %% Independent variation in properties across ages %% %% %% + % These consist of changing each parameter independently by + % +/- 0.5 SD and +/- 1SD for all ages (25, 35, 45, 55, 65 and 75). This + % was the approach used in the preliminary pulse wave database. + case 'independent_variations' + + vdb_characteristics.age.all = 25:10:75; % Ten-year intervals + + %% Cardiac properties + + % - Heart Rate (HR) + vdb_characteristics.hr.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.hr.no_independent_variations_at_baseline_age = 4; + vdb_characteristics.hr.no_combination_variations_at_other_ages = 0; + vdb_characteristics.hr.no_independent_variations_at_other_ages = 4; + vdb_characteristics.hr.variation_sds = 1; + + % - Stroke Volume (SV) + vdb_characteristics.sv.no_combination_variations_at_other_ages = 0; + vdb_characteristics.sv.no_independent_variations_at_other_ages = 4; + vdb_characteristics.sv.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.sv.no_independent_variations_at_baseline_age = 4; + vdb_characteristics.sv.variation_sds = 1; + + % - Left Ventricular Ejection Time (LVET): duration of systole + vdb_characteristics.lvet.no_combination_variations_at_other_ages = 0; + vdb_characteristics.lvet.no_independent_variations_at_other_ages = 4; + vdb_characteristics.lvet.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.lvet.no_independent_variations_at_baseline_age = 4; + vdb_characteristics.lvet.variation_sds = 1; + + % - Time to Peak Flow (t_pf): the time from the beginning of the aortic flow wave to its peak + vdb_characteristics.t_pf.no_combination_variations_at_other_ages = 0; + vdb_characteristics.t_pf.no_independent_variations_at_other_ages = 4; + vdb_characteristics.t_pf.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.t_pf.no_independent_variations_at_baseline_age = 4; + vdb_characteristics.t_pf.variation_sds = 1; + + % - Regurgitation volume (reg_vol): the amount of backwards flow at the end of systole + vdb_characteristics.reg_vol.no_combination_variations_at_other_ages = 0; + vdb_characteristics.reg_vol.no_independent_variations_at_other_ages = 2; + vdb_characteristics.reg_vol.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.reg_vol.no_independent_variations_at_baseline_age = 2; + vdb_characteristics.reg_vol.variation_sds = 1; + + %% Vascular bed properties + + % - Peripheral Vascular Compliance (pvc) + vdb_characteristics.pvc.no_combination_variations_at_other_ages = 0; + vdb_characteristics.pvc.no_independent_variations_at_other_ages = 2; + vdb_characteristics.pvc.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.pvc.no_independent_variations_at_baseline_age = 2; + vdb_characteristics.pvc.variation_sds = 1; + + % - Outflow Pressure (p_out) + vdb_characteristics.p_out.no_combination_variations_at_other_ages = 0; + vdb_characteristics.p_out.no_independent_variations_at_other_ages = 2; + vdb_characteristics.p_out.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.p_out.no_independent_variations_at_baseline_age = 2; + vdb_characteristics.p_out.variation_sds = 1; + + % - Mean Blood Pressure (mbp): the peripheral vascular resistance is set to achieve the desired value of MBP + vdb_characteristics.mbp.no_combination_variations_at_other_ages = 0; + vdb_characteristics.mbp.no_independent_variations_at_other_ages = 4; + vdb_characteristics.mbp.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.mbp.no_independent_variations_at_baseline_age = 4; + vdb_characteristics.mbp.variation_sds = 1; + + % - Reflections logical: whether to include reflections + vdb_characteristics.reflect_log.no_combination_variations_at_other_ages = 0; + vdb_characteristics.reflect_log.no_independent_variations_at_other_ages = 0; + vdb_characteristics.reflect_log.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.reflect_log.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.reflect_log.variation_sds = 0; + + %% Arterial properties + + % - Pulse Wave Velocity (pwv) + vdb_characteristics.pwv.no_combination_variations_at_other_ages = 0; + vdb_characteristics.pwv.no_independent_variations_at_other_ages = 4; + vdb_characteristics.pwv.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.pwv.no_independent_variations_at_baseline_age = 4; + vdb_characteristics.pwv.variation_sds = 1; + + % - Diastolic blood pressure (dbp): the pressure corresponding to the initial luminal areas (note that this has very little affect) + vdb_characteristics.dbp.no_combination_variations_at_other_ages = 0; + vdb_characteristics.dbp.no_independent_variations_at_other_ages = 4; + vdb_characteristics.dbp.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.dbp.no_independent_variations_at_baseline_age = 4; + vdb_characteristics.dbp.variation_sds = 1; + + % - Pressure drop (p_drop): the assumed pressure drop from the aortic root to the end of the arterial network + vdb_characteristics.p_drop.no_combination_variations_at_other_ages = 0; + vdb_characteristics.p_drop.no_independent_variations_at_other_ages = 0; + vdb_characteristics.p_drop.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.p_drop.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.p_drop.variation_sds = 0; + + % - Length of the proximal aorta (len) + vdb_characteristics.len.no_combination_variations_at_other_ages = 0; + vdb_characteristics.len.no_independent_variations_at_other_ages = 4; + vdb_characteristics.len.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.len.no_independent_variations_at_baseline_age = 4; + vdb_characteristics.len.variation_sds = 1; + + % - Diameter of the larger arteries (dia, e.g. ascending, descending aorta, carotid, brachial, ...) + vdb_characteristics.dia.no_combination_variations_at_other_ages = 0; + vdb_characteristics.dia.no_independent_variations_at_other_ages = 4; + vdb_characteristics.dia.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.dia.no_independent_variations_at_baseline_age = 4; + vdb_characteristics.dia.variation_sds = 1; + + % - Wall viscosity + vdb_characteristics.gamma.no_combination_variations_at_other_ages = 0; + vdb_characteristics.gamma.no_independent_variations_at_other_ages = 0; + vdb_characteristics.gamma.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.gamma.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.gamma.variation_sds = 0; + + %% Blood properties + + % - Blood density (rho) + vdb_characteristics.rho.no_combination_variations_at_other_ages = 0; + vdb_characteristics.rho.no_independent_variations_at_other_ages = 0; + vdb_characteristics.rho.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.rho.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.rho.variation_sds = 0; + + % - Blood viscosity (mu) + vdb_characteristics.mu.no_combination_variations_at_other_ages = 0; + vdb_characteristics.mu.no_independent_variations_at_other_ages = 0; + vdb_characteristics.mu.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.mu.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.mu.variation_sds = 0; + + %% - Simulation properties + + % - alpha: controls the shape of the velocity profile (assumed to be constant throughout the arterial tree) + vdb_characteristics.alpha.no_combination_variations_at_other_ages = 0; + vdb_characteristics.alpha.no_independent_variations_at_other_ages = 0; + vdb_characteristics.alpha.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.alpha.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.alpha.variation_sds = 0; + + % - time_step: which is the numerical time step used for calculations + vdb_characteristics.time_step.no_combination_variations_at_other_ages = 0; + vdb_characteristics.time_step.no_independent_variations_at_other_ages = 0; + vdb_characteristics.time_step.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.time_step.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.time_step.variation_sds = 0; + + % - visco_elastic_log: determines whether the simulations are elastic or visco-elastic + vdb_characteristics.visco_elastic_log.no_combination_variations_at_other_ages = 0; + vdb_characteristics.visco_elastic_log.no_independent_variations_at_other_ages = 0; + vdb_characteristics.visco_elastic_log.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.visco_elastic_log.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.visco_elastic_log.variation_sds = 0; + + %% %% %% Single baseline simulation %% %% %% + % This is a single simulation of the baseline 25-year old model. + case 'baseline_subject' + + vdb_characteristics.age.all = 25; + + %% Cardiac properties + + % - Heart Rate (HR) + vdb_characteristics.hr.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.hr.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.hr.no_combination_variations_at_other_ages = 0; + vdb_characteristics.hr.no_independent_variations_at_other_ages = 0; + vdb_characteristics.hr.variation_sds = 0; + + % - Stroke Volume (SV) + vdb_characteristics.sv.no_combination_variations_at_other_ages = 0; + vdb_characteristics.sv.no_independent_variations_at_other_ages = 0; + vdb_characteristics.sv.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.sv.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.sv.variation_sds = 0; + + % - Left Ventricular Ejection Time (LVET): duration of systole + vdb_characteristics.lvet.no_combination_variations_at_other_ages = 0; + vdb_characteristics.lvet.no_independent_variations_at_other_ages = 0; + vdb_characteristics.lvet.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.lvet.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.lvet.variation_sds = 0; + + % - Time to Peak Flow (t_pf): the time from the beginning of the aortic flow wave to its peak + vdb_characteristics.t_pf.no_combination_variations_at_other_ages = 0; + vdb_characteristics.t_pf.no_independent_variations_at_other_ages = 0; + vdb_characteristics.t_pf.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.t_pf.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.t_pf.variation_sds = 0; + + % - Regurgitation volume (reg_vol): the amount of backwards flow at the end of systole + vdb_characteristics.reg_vol.no_combination_variations_at_other_ages = 0; + vdb_characteristics.reg_vol.no_independent_variations_at_other_ages = 0; + vdb_characteristics.reg_vol.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.reg_vol.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.reg_vol.variation_sds = 0; + + %% Vascular bed properties + + % - Peripheral Vascular Compliance (pvc) + vdb_characteristics.pvc.no_combination_variations_at_other_ages = 0; + vdb_characteristics.pvc.no_independent_variations_at_other_ages = 0; + vdb_characteristics.pvc.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.pvc.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.pvc.variation_sds = 0; + + % - Outflow Pressure (p_out) + vdb_characteristics.p_out.no_combination_variations_at_other_ages = 0; + vdb_characteristics.p_out.no_independent_variations_at_other_ages = 0; + vdb_characteristics.p_out.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.p_out.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.p_out.variation_sds = 0; + + % - Mean Blood Pressure (mbp): the peripheral vascular resistance is set to achieve the desired value of MBP + vdb_characteristics.mbp.no_combination_variations_at_other_ages = 0; + vdb_characteristics.mbp.no_independent_variations_at_other_ages = 0; + vdb_characteristics.mbp.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.mbp.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.mbp.variation_sds = 0; + + % - Reflections logical: whether to include reflections + vdb_characteristics.reflect_log.no_combination_variations_at_other_ages = 0; + vdb_characteristics.reflect_log.no_independent_variations_at_other_ages = 0; + vdb_characteristics.reflect_log.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.reflect_log.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.reflect_log.variation_sds = 0; + + %% Arterial properties + + % - Pulse Wave Velocity (pwv) + vdb_characteristics.pwv.no_combination_variations_at_other_ages = 0; + vdb_characteristics.pwv.no_independent_variations_at_other_ages = 0; + vdb_characteristics.pwv.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.pwv.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.pwv.variation_sds = 0; + + % - Diastolic blood pressure (dbp): the pressure corresponding to the initial luminal areas (note that this has very little affect) + vdb_characteristics.dbp.no_combination_variations_at_other_ages = 0; + vdb_characteristics.dbp.no_independent_variations_at_other_ages = 0; + vdb_characteristics.dbp.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.dbp.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.dbp.variation_sds = 0; + + % - Pressure drop (p_drop): the assumed pressure drop from the aortic root to the end of the arterial network + vdb_characteristics.p_drop.no_combination_variations_at_other_ages = 0; + vdb_characteristics.p_drop.no_independent_variations_at_other_ages = 0; + vdb_characteristics.p_drop.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.p_drop.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.p_drop.variation_sds = 0; + + % - Length of the proximal aorta (len) + vdb_characteristics.len.no_combination_variations_at_other_ages = 0; + vdb_characteristics.len.no_independent_variations_at_other_ages = 0; + vdb_characteristics.len.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.len.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.len.variation_sds = 0; + + % - Diameter of the larger arteries (dia, e.g. ascending, descending aorta, carotid, brachial, ...) + vdb_characteristics.dia.no_combination_variations_at_other_ages = 0; + vdb_characteristics.dia.no_independent_variations_at_other_ages = 0; + vdb_characteristics.dia.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.dia.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.dia.variation_sds = 0; + + % - Wall viscosity + vdb_characteristics.gamma.no_combination_variations_at_other_ages = 0; + vdb_characteristics.gamma.no_independent_variations_at_other_ages = 0; + vdb_characteristics.gamma.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.gamma.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.gamma.variation_sds = 0; + + %% Blood properties + + % - Blood density (rho) + vdb_characteristics.rho.no_combination_variations_at_other_ages = 0; + vdb_characteristics.rho.no_independent_variations_at_other_ages = 0; + vdb_characteristics.rho.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.rho.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.rho.variation_sds = 0; + + % - Blood viscosity (mu) + vdb_characteristics.mu.no_combination_variations_at_other_ages = 0; + vdb_characteristics.mu.no_independent_variations_at_other_ages = 0; + vdb_characteristics.mu.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.mu.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.mu.variation_sds = 0; + + %% - Simulation properties + + % - alpha: controls the shape of the velocity profile (assumed to be constant throughout the arterial tree) + vdb_characteristics.alpha.no_combination_variations_at_other_ages = 0; + vdb_characteristics.alpha.no_independent_variations_at_other_ages = 0; + vdb_characteristics.alpha.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.alpha.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.alpha.variation_sds = 0; + + % - time_step: which is the numerical time step used for calculations + vdb_characteristics.time_step.no_combination_variations_at_other_ages = 0; + vdb_characteristics.time_step.no_independent_variations_at_other_ages = 0; + vdb_characteristics.time_step.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.time_step.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.time_step.variation_sds = 0; + + % - visco_elastic_log: determines whether the simulations are elastic or visco-elastic + vdb_characteristics.visco_elastic_log.no_combination_variations_at_other_ages = 0; + vdb_characteristics.visco_elastic_log.no_independent_variations_at_other_ages = 0; + vdb_characteristics.visco_elastic_log.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.visco_elastic_log.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.visco_elastic_log.variation_sds = 0; + + %% %% %% Baseline simulation at each age %% %% %% + + case 'baseline_subjects_at_each_age' + + vdb_characteristics.age.all = 25:10:75; + + %% Cardiac properties + + % - Heart Rate (HR) + vdb_characteristics.hr.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.hr.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.hr.no_combination_variations_at_other_ages = 0; + vdb_characteristics.hr.no_independent_variations_at_other_ages = 0; + vdb_characteristics.hr.variation_sds = 0; + + % - Stroke Volume (SV) + vdb_characteristics.sv.no_combination_variations_at_other_ages = 0; + vdb_characteristics.sv.no_independent_variations_at_other_ages = 0; + vdb_characteristics.sv.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.sv.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.sv.variation_sds = 0; + + % - Left Ventricular Ejection Time (LVET): duration of systole + vdb_characteristics.lvet.no_combination_variations_at_other_ages = 0; + vdb_characteristics.lvet.no_independent_variations_at_other_ages = 0; + vdb_characteristics.lvet.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.lvet.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.lvet.variation_sds = 0; + + % - Time to Peak Flow (t_pf): the time from the beginning of the aortic flow wave to its peak + vdb_characteristics.t_pf.no_combination_variations_at_other_ages = 0; + vdb_characteristics.t_pf.no_independent_variations_at_other_ages = 0; + vdb_characteristics.t_pf.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.t_pf.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.t_pf.variation_sds = 0; + + % - Regurgitation volume (reg_vol): the amount of backwards flow at the end of systole + vdb_characteristics.reg_vol.no_combination_variations_at_other_ages = 0; + vdb_characteristics.reg_vol.no_independent_variations_at_other_ages = 0; + vdb_characteristics.reg_vol.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.reg_vol.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.reg_vol.variation_sds = 0; + + %% Vascular bed properties + + % - Peripheral Vascular Compliance (pvc) + vdb_characteristics.pvc.no_combination_variations_at_other_ages = 0; + vdb_characteristics.pvc.no_independent_variations_at_other_ages = 0; + vdb_characteristics.pvc.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.pvc.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.pvc.variation_sds = 0; + + % - Outflow Pressure (p_out) + vdb_characteristics.p_out.no_combination_variations_at_other_ages = 0; + vdb_characteristics.p_out.no_independent_variations_at_other_ages = 0; + vdb_characteristics.p_out.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.p_out.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.p_out.variation_sds = 0; + + % - Mean Blood Pressure (mbp): the peripheral vascular resistance is set to achieve the desired value of MBP + vdb_characteristics.mbp.no_combination_variations_at_other_ages = 0; + vdb_characteristics.mbp.no_independent_variations_at_other_ages = 0; + vdb_characteristics.mbp.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.mbp.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.mbp.variation_sds = 0; + + % - Reflections logical: whether to include reflections + vdb_characteristics.reflect_log.no_combination_variations_at_other_ages = 0; + vdb_characteristics.reflect_log.no_independent_variations_at_other_ages = 0; + vdb_characteristics.reflect_log.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.reflect_log.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.reflect_log.variation_sds = 0; + + %% Arterial properties + + % - Pulse Wave Velocity (pwv) + vdb_characteristics.pwv.no_combination_variations_at_other_ages = 0; + vdb_characteristics.pwv.no_independent_variations_at_other_ages = 0; + vdb_characteristics.pwv.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.pwv.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.pwv.variation_sds = 0; + + % - Diastolic blood pressure (dbp): the pressure corresponding to the initial luminal areas (note that this has very little affect) + vdb_characteristics.dbp.no_combination_variations_at_other_ages = 0; + vdb_characteristics.dbp.no_independent_variations_at_other_ages = 0; + vdb_characteristics.dbp.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.dbp.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.dbp.variation_sds = 0; + + % - Pressure drop (p_drop): the assumed pressure drop from the aortic root to the end of the arterial network + vdb_characteristics.p_drop.no_combination_variations_at_other_ages = 0; + vdb_characteristics.p_drop.no_independent_variations_at_other_ages = 0; + vdb_characteristics.p_drop.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.p_drop.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.p_drop.variation_sds = 0; + + % - Length of the proximal aorta (len) + vdb_characteristics.len.no_combination_variations_at_other_ages = 0; + vdb_characteristics.len.no_independent_variations_at_other_ages = 0; + vdb_characteristics.len.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.len.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.len.variation_sds = 0; + + % - Diameter of the larger arteries (dia, e.g. ascending, descending aorta, carotid, brachial, ...) + vdb_characteristics.dia.no_combination_variations_at_other_ages = 0; + vdb_characteristics.dia.no_independent_variations_at_other_ages = 0; + vdb_characteristics.dia.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.dia.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.dia.variation_sds = 0; + + % - Wall viscosity + vdb_characteristics.gamma.no_combination_variations_at_other_ages = 0; + vdb_characteristics.gamma.no_independent_variations_at_other_ages = 0; + vdb_characteristics.gamma.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.gamma.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.gamma.variation_sds = 0; + + %% Blood properties + + % - Blood density (rho) + vdb_characteristics.rho.no_combination_variations_at_other_ages = 0; + vdb_characteristics.rho.no_independent_variations_at_other_ages = 0; + vdb_characteristics.rho.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.rho.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.rho.variation_sds = 0; + + % - Blood viscosity (mu) + vdb_characteristics.mu.no_combination_variations_at_other_ages = 0; + vdb_characteristics.mu.no_independent_variations_at_other_ages = 0; + vdb_characteristics.mu.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.mu.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.mu.variation_sds = 0; + + %% - Simulation properties + + % - alpha: controls the shape of the velocity profile (assumed to be constant throughout the arterial tree) + vdb_characteristics.alpha.no_combination_variations_at_other_ages = 0; + vdb_characteristics.alpha.no_independent_variations_at_other_ages = 0; + vdb_characteristics.alpha.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.alpha.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.alpha.variation_sds = 0; + + % - time_step: which is the numerical time step used for calculations + vdb_characteristics.time_step.no_combination_variations_at_other_ages = 0; + vdb_characteristics.time_step.no_independent_variations_at_other_ages = 0; + vdb_characteristics.time_step.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.time_step.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.time_step.variation_sds = 0; + + % - visco_elastic_log: determines whether the simulations are elastic or visco-elastic + vdb_characteristics.visco_elastic_log.no_combination_variations_at_other_ages = 0; + vdb_characteristics.visco_elastic_log.no_independent_variations_at_other_ages = 0; + vdb_characteristics.visco_elastic_log.no_combination_variations_at_baseline_age = 0; + vdb_characteristics.visco_elastic_log.no_independent_variations_at_baseline_age = 0; + vdb_characteristics.visco_elastic_log.variation_sds = 0; + +end + +% If the number of SDs of variation for any parameter which is to be varied +% is set at zero, then change it to a default value of 1. +params = fieldnames(vdb_characteristics); params = params(~strcmp(params, 'age')); +for param_no = 1 : length(params) + curr_param = params{param_no}; + eval(['curr_data = vdb_characteristics.' curr_param ';']); + if curr_data.variation_sds == 0 & ... + sum([abs(curr_data.no_combination_variations_at_other_ages), ... + abs(curr_data.no_independent_variations_at_other_ages), ... + abs(curr_data.no_combination_variations_at_baseline_age), ... + abs(curr_data.no_independent_variations_at_baseline_age)]) > 0 + eval(['vdb_characteristics.' curr_param '.variation_sds = 1;']); + end + +end + +end + +function variations = find_vdb_variations(vdb_characteristics) +% This function converts the database configuration (set in +% ""setup_vdb_characteristics"") into the number of SD to vary each parameter +% by in each simulation. + +fprintf('\n - Finding variation values') + +%% Find variations for each characteristic +% i.e. find out what values (in terms of SD from the mean) each parameter +% should take in the database, at what age(s), and whether to inclue these +% variations independently or in combination with each other. +varying_params = setxor(fieldnames(vdb_characteristics), 'age'); +ages = vdb_characteristics.age; +for varying_param_no = 1 : length(varying_params) + eval(['curr_varying_param = vdb_characteristics.' varying_params{varying_param_no} ';']) + eval(['param_variations.' varying_params{varying_param_no} ' = find_param_values(curr_varying_param, ages);']); +end + +%% Assemble list of variations for each simulation + +[variations.params, variations.ages, variations.age_nos] = deal([]); +variations.param_names = varying_params; +for age_no = 1 : length(ages.all) + curr_age = ages.all(age_no); + + % identify variations in each parameter (in terms of SD from the mean) + % for this age, and categorise them according to whether these + % variations are to be used independently, or in combination with each other. + [ind_variations, comb_variations] = deal(cell(length(varying_params),1)); + for varying_param_no = 1 : length(varying_params) + eval(['curr_variations = param_variations.' varying_params{varying_param_no} ';']); + rel_variation_els = curr_variations.ages == curr_age; + rel_variations = curr_variations.variations(rel_variation_els); rel_variations = rel_variations(:)'; + rel_comb_log = curr_variations.comb_log(rel_variation_els); + + ind_variations{varying_param_no} = rel_variations(~rel_comb_log); + comb_variations{varying_param_no} = rel_variations(rel_comb_log); + + clear rel_comb_log rel_variations rel_variation_els curr_variations + end + clear varying_param_no + + % find independent variations + all_ind_variations = []; + for varying_param_no = 1 : length(ind_variations) + rel_ind_variations = ind_variations{varying_param_no}; + temp = zeros(length(rel_ind_variations),length(varying_params)); + temp(:,varying_param_no) = rel_ind_variations(:); + all_ind_variations = [all_ind_variations; temp]; + clear temp rel_ind_variations + end + clear varying_param_no + % NB: all_ind_variations is a matrix specifying the variation (in terms + % of SD) of each parameter (columns correspond to different parameters) + % for each simulation (rows correspond to simulations). + + % find combination variations + combvec_text = ''; + for s = 1 : length(comb_variations) + combvec_text = [combvec_text, 'comb_variations{' num2str(s) '}, ']; + end + combvec_text = combvec_text(1:end-2); + eval(['all_comb_variations = combvec(' combvec_text ');']); + all_comb_variations = all_comb_variations'; + % NB: all_comb_variations is a matrix specifying the variation (in terms + % of SD) of each parameter (columns correspond to different parameters) + % for each simulation (rows correspond to simulations). + + % extract baseline simulation + baseline_el = sum(abs(all_comb_variations')) == 0; + baseline_sim = all_comb_variations(baseline_el,:); + all_comb_variations = all_comb_variations(~baseline_el,:); + + % sort variations to put independent ones immediately after baseline ones + additional_ind_variations = sum(all_comb_variations==0,2) == size(all_comb_variations,2)-1; + if ~isempty(all_comb_variations) + all_ind_variations = [all_ind_variations; all_comb_variations(additional_ind_variations,:)]; + end + all_ind_variations = sortrows(all_ind_variations); + all_comb_variations = all_comb_variations(~additional_ind_variations,:); + + % list variations + variations.params = [variations.params; baseline_sim; all_ind_variations; all_comb_variations]; + variations.ages = [variations.ages; curr_age*ones(1+size(all_comb_variations,1)+size(all_ind_variations,1),1)]; + variations.age_nos = [variations.age_nos; age_no*ones(1+size(all_comb_variations,1)+size(all_ind_variations,1),1)]; + +end + +%% Re-order variations to put the priority ones first: +% Prioritise: +% (i) baseline for age +priority1 = sum(variations.params~=0,2) == 0; +% (ii) single parameter changed +priority2 = sum(variations.params~=0,2) == 1 & ~priority1; +% (iii) all parameters changed +priority3 = sum(variations.params~=0,2) == max(sum(variations.params~=0,2)) & ~priority1 & ~priority2; +% (iv) remainder +remainder = ~priority1 & ~priority2 & ~priority3; +% Re-order +new_order = [find(priority1); find(priority2); find(priority3); find(remainder)]; +clear priority1 priority2 priority3 remainder +variations.params = variations.params(new_order,:); +variations.ages = variations.ages(new_order); +variations.age_nos = variations.age_nos(new_order); +clear new_order + +%% Eliminate non-sensical variations of categorical options +% This are non-numerical parameters - i.e. logicals which indicate whether +% or not to model something (such as whether or not to model +% visco-elasticity in arterial walls). +cat_options = {'visco_elastic_log', 'reflect_log'}; + +for param_no = 1 : length(variations.param_names) + + % skip if this parameter isn't a categorical option + if ~sum(strcmp(variations.param_names{param_no}, cat_options)) + continue + end + + % eliminate non-sensical (i.e. negative) variations + variations_to_keep = variations.params(:,param_no) == 0 | variations.params(:,param_no) == -1; + variations.params = variations.params(variations_to_keep,:); + variations.ages = variations.ages(variations_to_keep); + variations.age_nos = variations.age_nos(variations_to_keep); + clear variations_to_keep + +end + +end + +function param_variations = find_param_values(curr_param, ages) +% This function works out what values (in terms of SD from the mean) each parameter +% should take in the database, at what age(s), and whether to inclue these +% variations independently or in combination with each other. + +% cycle through each age +param_variations.ages = []; +param_variations.variations = []; +param_variations.comb_log = []; +param_variations.baseline_log = []; + +for age_no = 1 : length(ages.all) + curr_age = ages.all(age_no); + + % extract relevant info on desired variations + if curr_age == ages.baseline + no_combination_variations = curr_param.no_combination_variations_at_baseline_age; + no_independent_variations = curr_param.no_independent_variations_at_baseline_age; + else + no_combination_variations = curr_param.no_combination_variations_at_other_ages; + no_independent_variations = curr_param.no_independent_variations_at_other_ages; + end + + % Find variations + total_variations = no_combination_variations + no_independent_variations; + if total_variations > 0 + all_variations = linspace(-1*curr_param.variation_sds,curr_param.variation_sds, total_variations+1); + else + all_variations = 0; + end + clear total_variations + + % Find which of these are in combination, and which are independent + if no_combination_variations > 0 + comb_variations = linspace(-1*curr_param.variation_sds,curr_param.variation_sds, no_combination_variations+1); + else + comb_variations = []; + end + comb_variation_log = false(length(all_variations),1); + for s = 1 : length(all_variations) + if sum(all_variations(s) == comb_variations) + comb_variation_log(s) = true; + end + end + clear s comb_variations no_combination_variations no_independent_variations + + % find which are baseline + baseline_variation_log = logical(all_variations' == 0); + comb_variation_log = baseline_variation_log | comb_variation_log; + + % assemble matrix of desired variations + param_variations.ages = [param_variations.ages; curr_age*ones(length(all_variations),1)]; clear curr_age + param_variations.variations = [param_variations.variations; all_variations(:)]; clear all_variations + param_variations.comb_log = logical([param_variations.comb_log; comb_variation_log]); clear comb_variation_log + param_variations.baseline_log = logical([param_variations.baseline_log; baseline_variation_log]); clear baseline_variation_log + +end + +end + +function parameters = calculate_vdb_parameters(variations, up) +% This function converts the list of variations of each parameter (in terms +% of SD from the mean) into absolute values which can be prescribed to the +% model. For instance, the ""variations"" variable might say that heart rate +% should be varied by [-1, 0, 1] SD from the mean at age 25. This function +% converts that information into actual heart rate values (such as [60, 70, +% 80] bpm, if the mean +/- SD HR at age 25 was 70+/-10 bpm). + +fprintf('\n - Calculating model input parameters\n\n') + +% setup +required_age = unique(variations.ages); +parameters.age = variations.ages; +parameters.variations = rmfield(variations, {'ages', 'age_nos'}); + +%% Calculate mean and SD values for parameters which either: (i) are independent of age, or (ii) are solely dependent on age +ind_params = {'t_pf', 'reg_vol', 'p_out', 'rho', 'mu', 'alpha', 'time_step', 'p_drop', 'visco_elastic_log', 'reflect_log'}; +age_dep_params = {'dbp', 'pvc', 'dbp', 'mbp', 'hr', 'sv', 'len', 'dia_asc', 'dia_desc_thor', 'dia_abd', 'dia_carotid'}; +params = [age_dep_params, ind_params]; +eqns = struct; + +% Calculate values at each age ... +for curr_age_no = 1 : length(required_age) + curr_age = required_age(curr_age_no); + + % ... for each parameter + for param_no = 1 : length(params) + curr_param = params{param_no}; + + % Find the mean and sd values for this parameter for this age + [baseline_val, sd, eqn] = extract_values_from_literature(curr_age, curr_param, up); + + % store results + eval(['phys_vals.' curr_param '.val(curr_age_no,1) = baseline_val;']) + eval(['phys_vals.' curr_param '.sd(curr_age_no,1) = sd;']) + + % store equation + eval(['eqns.' curr_param ' = eqn;']) + + clear baseline_val sd curr_param abbr eqn + end + clear param_no curr_age +end +clear curr_age_no params age_dep_params ind_params + +%% Calculate values of parameters which are either: (i) independent of, or (ii) dependent on, the model baseline for each simulation +ind_params = {'hr', 'sv', 't_pf', 'reg_vol', 'dbp', 'mbp', 'mu', 'alpha', 'time_step', 'p_drop', 'visco_elastic_log', 'reflect_log'}; +dep_params = {'pvc', 'p_out', 'rho'}; +params = [ind_params, dep_params]; clear ind_params dep_params + +% cycle through each parameter +for param_no = 1 : length(params) + curr_param = params{param_no}; + curr_param_col = find(strcmp(variations.param_names, curr_param)); + + % extract variations for this parameter for each simulation + param_variations.no_sd = variations.params(:,curr_param_col); clear curr_param_col + param_variations.age_ind = variations.age_nos; + + % calculate values for this parameter for each simulation + eval(['curr_param_phys_vals = phys_vals.' curr_param ';']) + param_values = curr_param_phys_vals.val(param_variations.age_ind) + (param_variations.no_sd .* curr_param_phys_vals.sd(param_variations.age_ind)); + clear param_variations + + % store these values + eval(['parameters.' curr_param ' = param_values;']) + + clear curr_param +end +clear param_no params + +%% Correct time step for visco-elastic simulations +% This ensures that the time step is short enough for visco-elastic simulations to run + +max_visco_elastic_time_step = 1e-5; +% identify visco-elastic simulations which have a time step above the maximum value +time_steps_to_change = parameters.time_step > max_visco_elastic_time_step & ... + parameters.visco_elastic_log == 1; +% reset the time step of these simulations to 1e-5 (the max for visco-elastic) +parameters.time_step(time_steps_to_change) = max_visco_elastic_time_step; + + +%% Calculate parameters which are dependent on several initial model parameters + +%% -- len -- +% length of proximal aorta +curr_param = 'len'; + +% import geometry of arterial tree from data file +baseline_network_spec = obtain_network_spec(eqns, up); + +% extract param variations for this parameter +curr_param_col = find(strcmp(variations.param_names, curr_param)); +param_variations.no_sd = variations.params(:,curr_param_col); +param_variations.age_ind = variations.age_nos; + +% Find desired proximal aortic lengths for each simulation +eval(['curr_param_phys_vals = phys_vals.' curr_param ';']) +temp_param_values = curr_param_phys_vals.val(param_variations.age_ind) + (param_variations.no_sd .* curr_param_phys_vals.sd(param_variations.age_ind)); % values in mm + +% Scale these desired lengths so that the desired length at the baseline +% age is equal to the length in the initial model configuration. +param_baseline_val = 1000*sum(baseline_network_spec.length(baseline_network_spec.proximal_aorta)); % length of proximal aorta in mm +model_scale_factor = param_baseline_val/curr_param_phys_vals.val(required_age == up.baseline_age); +model_param_values = temp_param_values*model_scale_factor/1000; % the required lengths of the proximal aorta in each of the simulations, in m + +% For each simulation, find the lengths of the individual proximal aortic +% segments which sum to give these scaled desired lengths. +baseline_proximal_aorta_lengths = baseline_network_spec.length(baseline_network_spec.proximal_aorta); +baseline_proximal_aorta_lengths = baseline_proximal_aorta_lengths(:)'; +proximal_aorta_param_values = repmat(baseline_proximal_aorta_lengths, [length(model_param_values),1]) .* (model_param_values/sum(baseline_proximal_aorta_lengths)); % in m + +% store these values in the network spec for each simulation +for sim_no = 1 : length(variations.ages) + parameters.network_spec{sim_no} = baseline_network_spec; + parameters.network_spec{sim_no}.length(baseline_network_spec.proximal_aorta) = proximal_aorta_param_values(sim_no,:); +end + +%% -- dia -- +% diameter of asc aorta, desc aorta, abd aorta, and common carotid artery +% (more or less - it's actually all segments with a radius of >= 0.003462 m) +curr_param = 'dia'; + +% extract variations for this parameter +curr_param_col = find(strcmp(variations.param_names, curr_param)); +param_variations.no_sd = variations.params(:,curr_param_col); +param_variations.age_ind = variations.age_nos; + +% find overall percentage change in aortic diameter across all four sites for each age +baseline_dia_age_no = 1; +curr_artery_dia = phys_vals.dia_asc.val; perc_change(:,1) = 100*curr_artery_dia/curr_artery_dia(baseline_dia_age_no); % the values are for each baseline simulation for each age +curr_artery_dia = phys_vals.dia_desc_thor.val; perc_change(:,2) = 100*curr_artery_dia/curr_artery_dia(baseline_dia_age_no); +curr_artery_dia = phys_vals.dia_abd.val; perc_change(:,3) = 100*curr_artery_dia/curr_artery_dia(baseline_dia_age_no); +curr_artery_dia = phys_vals.dia_carotid.val; perc_change(:,4) = 100*curr_artery_dia/curr_artery_dia(baseline_dia_age_no); +curr_param_phys_vals.val = mean(perc_change,2); +clear curr_artery_dia perc_change + +% To find eqn: perc_change = curr_param_phys_vals.val; age = 25:10:75; age = age(:); tbl = table(perc_change, age); mdl = fitlm(tbl, 'perc_change ~ age') + +% Find the SD (as a proportion of the mean diameter) +sd_div_mean = mean([2.4/25.7,2.3/26.5,2.1/28.8,3.1/29.0]); % From Agmon 2003 +% Find the SD (absolute value) +curr_param_phys_vals.sd = sd_div_mean*curr_param_phys_vals.val; + +% find the desired diameter as a proportion of the baseline diameter for each simulation +prop_of_baseline = curr_param_phys_vals.val(param_variations.age_ind) + (param_variations.no_sd .* curr_param_phys_vals.sd(param_variations.age_ind)); +prop_of_baseline = prop_of_baseline/100; % converts from percent to proportion + +% store these values in the network spec for each simulation +av_radius = mean([parameters.network_spec{1}.inlet_radius, parameters.network_spec{1}.outlet_radius],2); +segs_to_increase = av_radius >= 0.003462*sqrt(1.5); % all segments with radius greater than 4.24mm (3.46 mm scaled by sqrt(1.5)) are increased in diameter +outlet_nodes_to_increase = parameters.network_spec{1}.outlet_node(segs_to_increase); % the outlet diameters for all these segments should be increased. +additional_inlets_to_increase = false(length(parameters.network_spec{1}.inlet_node),1); % the inlets of segments attached to the ends of the segments whose outlet diameters are increased should also be increased. +for s = 1 : length(parameters.network_spec{1}.inlet_node) + curr_inlet_node = parameters.network_spec{1}.inlet_node(s); + if sum(outlet_nodes_to_increase == curr_inlet_node) > 0 + additional_inlets_to_increase(s) = true; + end +end +inlets_to_increase = segs_to_increase | additional_inlets_to_increase; +for sim_no = 1 : length(variations.ages) + parameters.network_spec{sim_no}.inlet_radius(inlets_to_increase) = parameters.network_spec{sim_no}.inlet_radius(inlets_to_increase)*prop_of_baseline(sim_no); + parameters.network_spec{sim_no}.outlet_radius(segs_to_increase) = parameters.network_spec{sim_no}.outlet_radius(segs_to_increase)*prop_of_baseline(sim_no); +end + +%% -- lvet -- +curr_param = 'lvet'; + +% extract variations for this parameter +curr_param_col = find(strcmp(variations.param_names, curr_param)); +param_variations.no_sd = variations.params(:,curr_param_col); +param_variations.age_ind = variations.age_nos; + +% setup model for lvet (based on data from Weissler 1961) +hr = [68,68,85,72,49,120,56,60,66,65,56,72,62,68,57,65,80, 93,84,80,74,100]'; sv = [82,81,62,95,98,44,106,102, 96,82,92,74,107,93,101,109,79, 49,71,59,76,43]'; lvet = 1000*[0.27,0.275,0.235,0.265,0.290,0.2,0.315,0.32,0.31,0.285,0.305,0.260,0.300,0.270,0.305,0.285,0.250, 0.2,0.235,0.24,0.24,0.19]'; +tbl = table(hr,sv,lvet); +modelspec = 'lvet ~ 1 + hr + sv'; +mdl = fitlm(tbl,modelspec); % model of LVET as a function of HR and SV +[lvet_val,lvet_ci] = predict(mdl,[parameters.hr, parameters.sv], 'Alpha', 0.3173); % I think a coefficient of 0.3173 gives one SD +lvet_sd = lvet_val - lvet_ci(:,1); % SD of LVET + +% calculate values of this parameter for each simulation +param_values = lvet_val + (param_variations.no_sd .* lvet_sd); + +% normalise LVETs for each age to have the desired mean and SD +baseline_vals.mean = 282; % Using Mynard 2015's value for the mean +baseline_vals.sd = 282*(24.43/295.29); % Use the values from Gerstenblith 1977 (295.29 +/- 24.43 ms) to find the SD + +ages = unique(variations.ages); +for age_no = 1 : length(ages) + + % identify data corresponding to this age + rel_els = variations.ages == ages(age_no); + rel_lvet = param_values(rel_els); + + % normalise lvet data + rel_lvet = baseline_vals.mean * rel_lvet/mean(rel_lvet); + if std(rel_lvet) > 0 % i.e. if there's more than one simulation at this age. + rel_lvet = mean(rel_lvet) + (baseline_vals.sd * (rel_lvet-mean(rel_lvet))/std(rel_lvet)); + end + + % re-insert normalised data + param_values(rel_els) = rel_lvet; + +end + +% store these values +eval(['parameters.' curr_param ' = param_values;']) + +%% -- pvr -- +% scale the peripheral vascular resistance Windkessel values to achieve the desired MBP +sims_co = parameters.hr.*parameters.sv/1000; % cardiac output for each simulation in l/min +mean_flow = sims_co/(1000*60); % cardiac output converted to m3/sec +network_r = (133.33*parameters.p_drop)./mean_flow; % resistance of network +parameters.pvr = (((133.33*parameters.mbp) - parameters.p_out)./mean_flow) - network_r; % where PVR is in Pa s/m3 + +%% -- pwv -- +% Find the appropriate constants (k1, k2, k3) for the equation describing +% the relationship between arterial stiffness and arterial radius for each +% simulation. This is done in four steps. + +% STEP 1: Find reference PWV values for different ages and different MBPs + +% original data from Mattace-Raso2010, table 6: PWV = A*age + B*age^2 + C specified for different BP ranges +A = [0.000, 0.000, 0.000, 0.000, 0.044]; +B = [0.83, 0.99, 1.05, 1.18, 0.85]*1e-3; +C = [5.55, 5.69, 5.91, 6.17, 5.73]; +sbp = [115, 125, 135, 150, 170]; +dbp = [77.5, 82.5, 87.5, 95, 105]; +init_mbp_vals = dbp+(0.4*(sbp-dbp)); % calculate approximate MBP corresponding to these SBP and DBP values using 0.4 constant from article; similar to 0.412 constant from: ""Formula and nomogram for the sphygmomanometric calculation of the mean arterial pressure"", http://heart.bmj.com/content/heartjnl/84/1/64.full.pdf + +% extend range of MBP values by extrapolating at: +% - lower end +no_to_interpolate = 5; +interp_els = (1-no_to_interpolate):0; +new_sbp_vals = interp1(1:3, sbp(1:3), interp_els, 'linear', 'extrap'); +new_dbp_vals = interp1(1:3, dbp(1:3), interp_els, 'linear', 'extrap'); +new_A_vals = interp1(1:3, A(1:3), interp_els, 'linear', 'extrap'); +new_B_vals = interp1(1:3, B(1:3), interp_els, 'linear', 'extrap'); +new_C_vals = interp1(1:3, C(1:3), interp_els, 'linear', 'extrap'); +% store these new values +sbp = [new_sbp_vals, sbp]; +dbp = [new_dbp_vals, dbp]; +A = [new_A_vals, A]; +B = [new_B_vals, B]; +C = [new_C_vals, C]; + +% - upper end +no_to_interpolate = 3; +interp_els = 2+(1:no_to_interpolate); +new_sbp_vals = interp1(1:2, sbp([end-1, end]), interp_els, 'linear', 'extrap'); +new_dbp_vals = interp1(1:2, dbp([end-1, end]), interp_els, 'linear', 'extrap'); +new_A_vals = interp1(1:2, A([end-1, end]), interp_els, 'linear', 'extrap'); +new_B_vals = interp1(1:2, B([end-1, end]), interp_els, 'linear', 'extrap'); +new_C_vals = interp1(1:2, C([end-1, end]), interp_els, 'linear', 'extrap'); +% store these new values +sbp = [sbp, new_sbp_vals]; +dbp = [dbp, new_dbp_vals]; +A = [A, new_A_vals]; +B = [B, new_B_vals]; +C = [C, new_C_vals]; + +% calculate mbp +mbps.vals = dbp+(0.4*(sbp-dbp)); % approximation as above: 0.4 constant from article; 0.412 constant from: http://heart.bmj.com/content/heartjnl/84/1/64.full.pdf +mbps.inds = 1 : length(mbps.vals); + +% data from Mattace-Raso2010 table 5 (median and 10 and 90 pc, therefore these represent +/- 40% in each direction) +no_sds = range(norminv([0.5, 0.9])); % in this case, for 80% confidence interval + +sd_percentile.lower_v = (1/no_sds)*100* [(6.0-5.2)/6.0, (6.4-5.7)/6.4, (6.7-5.8)/6.7, (7.2-5.7)/7.2, (7.6-5.9)/7.6; ... + (6.5-5.4)/6.5, (6.7-5.3)/6.7, (7.0-5.5)/7.0, (7.2-5.5)/7.2, (7.6-5.8)/7.6; ... + (6.8-5.8)/6.8, (7.4-6.2)/7.4, (7.7-6.5)/7.7, (8.1-6.8)/8.1, (9.2-7.1)/9.2; ... + (7.5-6.2)/7.5, (8.1-6.7)/8.1, (8.4-7.0)/8.4, (9.2-7.2)/9.2, (9.7-7.4)/9.7; ... + (8.7-7.0)/8.7, (9.3-7.6)/9.3, (9.8-7.9)/9.8, (10.7-8.4)/10.7, (12.0-8.5)/12.0; ... + (10.1-7.6)/10.1, (11.1-8.6)/11.1, (11.2-8.6)/11.2, (12.7-9.3)/12.7, (13.5-10.3)/13.5 ... + ]; +sd_percentile.upper_v = (1/no_sds)*100* [(7.0-6.0)/6.0, (7.5-6.4)/6.4, (7.9-6.7)/6.7, (9.3-7.2)/7.2, (9.9-7.6)/7.6; ... + (7.9-6.5)/6.5, (8.2-6.7)/6.7, (8.8-7.0)/7.0, (9.3-7.2)/7.2, (11.2-7.6)/7.6; ... + (8.5-6.8)/6.8, (9.0-7.4)/7.4, (9.5-7.7)/7.7, (10.8-8.1)/8.1, (13.2-9.2)/9.2; ... + (9.2-7.5)/7.5, (10.4-8.1)/8.1, (11.3-8.4)/8.4, (12.5-9.2)/9.2, (14.9-9.7)/9.7; ... + (11.4-8.7)/8.7, (12.2-9.3)/9.3, (13.2-9.8)/9.8, (14.1-10.7)/10.7, (16.5-12.0)/12.0; ... + (13.8-10.1)/10.1, (15.5-11.1)/11.1, (15.8-11.2)/11.2, (16.7-12.7)/12.7, (18.2-13.5)/13.5 ... + ]; +sd_percentile.age = 25:10:75; + +% add on extrapolated values (assuming a constant percentage value for the SD outside of the specified data range) +sd_percentile.mbp = [0, init_mbp_vals, 500]; +sd_percentile.lower_v = [sd_percentile.lower_v(:,1), sd_percentile.lower_v, sd_percentile.lower_v(:,end)]; +sd_percentile.upper_v = [sd_percentile.upper_v(:,1), sd_percentile.upper_v, sd_percentile.upper_v(:,end)]; + +% find reference PWV values for different ages and different MBPs +age = 20:80; +for n = 1 : length(A) + pwv_age(:,n) = A(n)*age + B(n)*(age.^2) + C(n); +end + +% STEP 2: Calculate mean and SD values for carotid-femoral PWV for each simulation according to age and MBP + +% calculate expected MBP for each simulation +sims_co = parameters.hr.*parameters.sv/1000; % in l/min +mean_flow = sims_co/(1000*60); % in m3/sec +sims_mbp = ((mean_flow.*(parameters.pvr+network_r)) + parameters.p_out)/133.33; % where PVR is in Pa s/m3 + +% setup variables +[initial_pwv.cf.v, initial_pwv.cf.sd_perc_lower, initial_pwv.cf.sd_perc_upper, parameters.desired_pwv_aorta, parameters.desired_pwv_leg, parameters.desired_pwv_arm, parameters.expected_pwv_aorta, parameters.expected_pwv_leg, parameters.expected_pwv_arm] = deal(nan(length(parameters.age),1)); +for sim_no = 1 : length(parameters.age) + + % find values for this age + curr_age = parameters.age(sim_no); + [~, rel_age_el] = min(abs(age-curr_age)); + rel_pwv_age_vals = pwv_age(rel_age_el,:); + + % find values for this MBP from within those for this age + rel_mbp_ind = interp1(mbps.vals, mbps.inds, sims_mbp(sim_no), 'linear', 'extrap'); + if rel_mbp_ind > length(mbps.vals) + rel_mbp_ind = length(mbps.vals); + end + if rel_mbp_ind < 1 + rel_mbp_ind = 1; + end + + % find mean value for cf PWV for this age and mbp + initial_pwv.cf.v(sim_no) = interp1(mbps.inds, rel_pwv_age_vals, rel_mbp_ind); + parameters.desired_pwv_leg(sim_no) = 0.056.*((initial_pwv.cf.v(sim_no)-6.15)/0.092)+7.91; % obtained from Avolio 1983 by combining eqns for PWVao and PWVleg + parameters.desired_pwv_arm(sim_no) = 0.048.*((initial_pwv.cf.v(sim_no)-6.15)/0.092)+9.98; % obtained from Avolio 1983 by combining eqns for PWVao and PWVarm + + % find SD value for cf PWV for this age and mbp + rel_sd_percentiles_lower = sd_percentile.lower_v(sd_percentile.age == curr_age, :); + rel_sd_percentiles_upper = sd_percentile.upper_v(sd_percentile.age == curr_age, :); + initial_pwv.cf.sd_perc_lower(sim_no,1) = interp1(sd_percentile.mbp, rel_sd_percentiles_lower, sims_mbp(sim_no)); + initial_pwv.cf.sd_perc_upper(sim_no,1) = interp1(sd_percentile.mbp, rel_sd_percentiles_upper, sims_mbp(sim_no)); + +end + +% STEP 3: Calculate the desired cf-PWV value for each simulation based on: +% (i) the mean and SD values for this age and MBP, and +% (ii) the variation in PWV from the mean for this simulation. + +% calculate actual cf-pwv values, taking into account variation from mean values for the age group +curr_param = 'pwv'; +curr_param_col = find(strcmp(variations.param_names, curr_param)); +param_variations.no_sd = variations.params(:,curr_param_col); +lower_els = param_variations.no_sd < 0; +parameters.desired_pwv_aorta = nan(size(lower_els)); +parameters.desired_pwv_aorta(~lower_els) = initial_pwv.cf.v(~lower_els) .* (1 + (param_variations.no_sd(~lower_els).*(initial_pwv.cf.sd_perc_upper(~lower_els)/100))); +parameters.desired_pwv_aorta(lower_els) = initial_pwv.cf.v(lower_els) .* (1 + (param_variations.no_sd(lower_els).*(initial_pwv.cf.sd_perc_lower(lower_els)/100))); + +% STEP 4: Find appropriate values of k1, k2 and k3 to achieve these desired cf-PWVs + +k1 = 3.0e6; % [g/s^2/cm] % (Mynard's) +k2 = -9*1.5; % [/cm] % This is increased by a factor of 1.5 from Mynard 2015's value to achieve the desired pulse wave shapes (and amplification) +k3 = 3.37e5; % [g/s^2/cm] % (Mynard's) + +% Prepare figure to plot wave speeds +if up.do_plot && strcmp(up.db_config, 'baseline_subjects_at_each_age') + max_vals = [0,0]; min_val = inf; + paper_size = [1200,400]; figure('Position', [20,20,paper_size]) +end +for sim_no = 1 : length(parameters.age) + + % extract desired cf PWVs for this simulation + desired_wave_speeds.aorta = parameters.desired_pwv_aorta(sim_no); + desired_wave_speeds.arm = parameters.desired_pwv_arm(sim_no); + desired_wave_speeds.leg = parameters.desired_pwv_leg(sim_no); + + % extract network parameters for this simulation + rel_network_spec = parameters.network_spec{sim_no}; + + % extract density of blood + rho = parameters.rho(sim_no); + + % determine optimal value for k3 using a search algorithm (which + % minimises the difference between the desired and expected cf PWV). + options = optimset('MaxFunEvals',200, 'display', 'off'); + optimal_k1_and_2 = [k1,k2]; + k3_cost_function = @(k3)calculate_k3_cost_function(rel_network_spec, optimal_k1_and_2, k3, rho, desired_wave_speeds); + [optimal_k3, ~] = fminsearch(k3_cost_function,k3, options); + optimal_k = [k1, k2, optimal_k3]; + + % store the optimal values of the constants + store_k(sim_no,:) = optimal_k; + parameters.network_spec{sim_no}.k = optimal_k; + + optimal_wave_speeds = calculate_theoretical_wave_speeds(rel_network_spec, optimal_k, rho); + + errors(sim_no,:) = [desired_wave_speeds.aorta - optimal_wave_speeds.aorta, ... + desired_wave_speeds.arm - optimal_wave_speeds.arm, ... + desired_wave_speeds.leg - optimal_wave_speeds.leg]; + + parameters.expected_pwv_aorta(sim_no) = optimal_wave_speeds.aorta; + parameters.expected_pwv_arm(sim_no) = optimal_wave_speeds.arm; + parameters.expected_pwv_leg(sim_no) = optimal_wave_speeds.leg; + + if up.do_plot && strcmp(up.db_config, 'baseline_subjects_at_each_age') + + % Find expected wave speeds for all arterial segments + ave_radius = mean([rel_network_spec.inlet_radius(:), rel_network_spec.outlet_radius(:)], 2); + ave_radius_cm = 100*ave_radius; + Eh_D0 = (optimal_k(1)*exp(optimal_k(2)*ave_radius_cm))+optimal_k(3); % Eh/D0 (from Mynard's 2015 paper, eqn 3) + c0_squared = (2/3)*(Eh_D0/(rho/1000)); % from Mynard's 2015 paper, eqn 3, converts rho from kg/m3 to g/cm3 + wave_speed = sqrt(c0_squared)/100; % converts from cm/s to m/s. + [~, order] = sort(ave_radius_cm); + + % plot + color_intensity = 0.2+0.5*(sim_no/length(parameters.age)); + curr_color = color_intensity*[1,1,1]; + leg_h(sim_no,1) = plot(2*10*ave_radius_cm(order), wave_speed(order), 'Color', curr_color, 'LineWidth', 2); + hold on + + % tidy up + ftsize = 28; + set(gca, 'FontSize', ftsize) + ylabel('Wave Speed [m/s]', 'FontSize', ftsize); + xlabel('Arterial Diameter [mm]', 'FontSize', ftsize); + title('PWV vs Diameter', 'FontSize', ftsize); + labels{sim_no,1} = num2str(parameters.age(sim_no)); + box off + max_vals(1) = max([max_vals(1), max(2*10*ave_radius_cm)]); + min_val = min([min_val, min(wave_speed)]); + max_vals(2) = max([max_vals(2), max(wave_speed)]); + end + +end + +if up.do_plot && strcmp(up.db_config, 'baseline_subjects_at_each_age') + xlim([0 1.15*max_vals(1)]) + ylim([0.95*min_val max_vals(2)+0.05*min_val]) + lgd = legend(flipud(leg_h), flipud(labels), 'FontSize', ftsize, 'Location', 'SouthEast'); + title(lgd,'Age') + PrintFigs(gcf, paper_size/70, [up.savefolder, 'Wave_speeds']) + +end + +close all +% Make plot +if up.do_plot + + paper_size = [900, 270]; + figure('Position', [20,20,paper_size]) + ftsize = 16; + lims = [5.5, 12.5]; + subplot(1,3,1) + plot(parameters.desired_pwv_aorta, parameters.expected_pwv_aorta, 'bx', 'MarkerSize', 8), hold on, + plot(lims, lims, 'k') + xlabel('Desired', 'FontSize', ftsize), ylabel('Prescribed', 'FontSize', ftsize) + title('Carotid-femoral PWV', 'FontSize', ftsize) + set(gca, 'FontSize', ftsize) + xlim(lims), ylim(lims) + + subplot(1,3,2) + plot(parameters.desired_pwv_arm, parameters.expected_pwv_arm, 'bx', 'MarkerSize', 8), hold on, + plot(lims, lims, 'k') + xlabel('Desired', 'FontSize', ftsize), ylabel('Prescribed', 'FontSize', ftsize) + title('Brachial-radial PWV', 'FontSize', ftsize) + set(gca, 'FontSize', ftsize) + xlim(lims), ylim(lims) + + subplot(1,3,3) + plot(parameters.desired_pwv_leg, parameters.expected_pwv_leg, 'bx', 'MarkerSize', 8), hold on, + plot(lims, lims, 'k') + xlabel('Desired', 'FontSize', ftsize), ylabel('Prescribed', 'FontSize', ftsize) + title('Femoral-ankle PWV', 'FontSize', ftsize) + set(gca, 'FontSize', ftsize) + xlim(lims), ylim(lims) + + % Save figure + PrintFigs(gcf, paper_size/70, [up.savefolder, 'Prescribed_vs_desired_PWVs']) + +end + +%% --- gamma coefficients --- +baseline_Gamma_b0 = 400*1.5; % a factor of 1.5 times larger than 400 g/s in Mynard 2015 +baseline_Gamma_b1 = 100*1.5; % a factor of 1.5 times larger than 100 g cm/s in Maynard 2015 +[parameters.gamma_b1, parameters.gamma_b0] = deal(nan(size(parameters.age))); + +% find out how many SD to vary gamma by +curr_param = 'gamma'; +curr_param_col = strcmp(variations.param_names, curr_param); +param_variations.no_sd = variations.params(:,curr_param_col); +parameters.gamma_b0 = baseline_Gamma_b0 .* (1 + param_variations.no_sd); +parameters.gamma_b1 = baseline_Gamma_b1.* (1 + param_variations.no_sd); + +%% Save table of equations +make_table_equations(up.savefolder, eqns); + +end + +function make_param_plots(up) + +% setup +required_age = 25:1:75; +params = {'pwv_cf', 'pwv_fa', 'pwv_br', 't_pf', 'lvet', 'reg_vol', 'pvc', 'dbp', 'mbp', 'hr', 'sv', 'len', 'dia_asc', 'dia_desc_thor', 'dia_abd', 'dia_carotid'}; +ftsize = 32; +lwidth = 2; +paper_size = [500,400]; + +% Extract data from literature for these params +for curr_age_no = 1 : length(required_age) + curr_age = required_age(curr_age_no); + + for param_no = 1 : length(params) + curr_param = params{param_no}; + + if strcmp(curr_param, 'lvet') + baseline_val = 295.29; + sd = 24.43; + elseif strcmp(curr_param, 'pwv_cf') + raw_vals = [5.94618071428571;6.53537900000000;7.39549485714286;8.28360714285714;9.23771257142857;10.3004642857143]; + baseline_val = interp1(25:10:75, raw_vals, curr_age); + raw_sd_vals = [10.4040552809651;13.2051470873787;11.8934986269314;13.5115098873697;15.0291697484146;19.1777415260153].*raw_vals/100; + sd_min = interp1(25:10:75,raw_sd_vals, curr_age); + raw_sd_vals = [13.0050691012063;16.8065508384820;18.5716246860543;19.2832834122860;24.2420005849521;28.7696946479979].*raw_vals/100; + sd_max = interp1(25:10:75,raw_sd_vals, curr_age); + clear raw_vals raw_sd_vals + elseif strcmp(curr_param, 'pwv_fa') + baseline_val = (5.6*curr_age+791)/100; + sd_min = zeros(size(curr_age)); + sd_max = zeros(size(curr_age)); + elseif strcmp(curr_param, 'pwv_br') + baseline_val = (4.8*curr_age+998)/100; + sd_min = zeros(size(curr_age)); + sd_max = zeros(size(curr_age)); + else + % calculate this parameter's baseline val and SD for this age + [baseline_val, sd, eqn] = extract_values_from_literature(curr_age, curr_param, up); + %[baseline_val, sd, eqn] = calculate_val(curr_age, curr_param, value_source, up); + end + + % store results + eval(['phys_vals.' curr_param '.val(curr_age_no,1) = baseline_val;']) + if exist('sd', 'var') + eval(['phys_vals.' curr_param '.sd_min(curr_age_no,1) = sd;']) + eval(['phys_vals.' curr_param '.sd_max(curr_age_no,1) = sd;']) + else + eval(['phys_vals.' curr_param '.sd_min(curr_age_no,1) = sd_min;']) + eval(['phys_vals.' curr_param '.sd_max(curr_age_no,1) = sd_max;']) + end + + clear baseline_val sd curr_param abbr eqn + + end + clear param_no curr_age + +end +clear curr_age_no + +% Make a plot of each of these params in turn +for param_no = 1 : length(params) + curr_param = params{param_no}; + + % get relevant data + eval(['rel_data = phys_vals.' curr_param ';']) + if strcmp(curr_param, 'dbp') + rel_data.val = rel_data.val/133.33; + rel_data.sd_min = rel_data.sd_min/133.33; + rel_data.sd_max = rel_data.sd_max/133.33; + end + if strcmp(curr_param, 'pwv_fa') || strcmp(curr_param, 'pwv_br') + rel_data = phys_vals.pwv_cf; + end + rel_data.sd_min_1 = rel_data.val - rel_data.sd_min; + rel_data.sd_min_2 = rel_data.val - 2*rel_data.sd_min; + rel_data.sd_plus_1 = rel_data.val + rel_data.sd_max; + rel_data.sd_plus_2 = rel_data.val + 2*rel_data.sd_max; + + % change peripheral PWVs + if strcmp(curr_param, 'pwv_fa') + rel_data.val = 0.056.*((rel_data.val-6.15)/0.092)+7.91; % obtained from \cite{Avolio1983} by combining eqns for PWVao and PWVleg + rel_data.sd_min_1 = 0.056.*((rel_data.sd_min_1-6.15)/0.092)+7.91; + rel_data.sd_min_2 = 0.056.*((rel_data.sd_min_2-6.15)/0.092)+7.91; + rel_data.sd_plus_1 = 0.056.*((rel_data.sd_plus_1-6.15)/0.092)+7.91; + rel_data.sd_plus_2 = 0.056.*((rel_data.sd_plus_2-6.15)/0.092)+7.91; + elseif strcmp(curr_param, 'pwv_br') + rel_data.val = 0.048.*((rel_data.val-6.15)/0.092)+9.98; % obtained from \cite{Avolio1983} by combining eqns for PWVao and PWVarm + rel_data.sd_min_1 = 0.048.*((rel_data.sd_min_1-6.15)/0.092)+9.98; + rel_data.sd_min_2 = 0.048.*((rel_data.sd_min_2-6.15)/0.092)+9.98; + rel_data.sd_plus_1 = 0.048.*((rel_data.sd_plus_1-6.15)/0.092)+9.98; + rel_data.sd_plus_2 = 0.048.*((rel_data.sd_plus_2-6.15)/0.092)+9.98; + end + + % Make figure + figure('Position', [20, 20, paper_size]) + subplot('Position', [0.19,0.21,0.80,0.70]) + fprintf(['\n - Making plot for ' curr_param]) + + % plot data + plot(required_age, rel_data.val, 'k', 'LineWidth', lwidth), + hold on + plot(required_age, rel_data.sd_min_1, '--k', 'LineWidth', lwidth) + plot(required_age, rel_data.sd_min_2, '--k', 'LineWidth', lwidth) + plot(required_age, rel_data.sd_plus_1, '--k', 'LineWidth', lwidth) + plot(required_age, rel_data.sd_plus_2, '--k', 'LineWidth', lwidth) + + % tidy up + xlim([min(required_age), max(required_age)]); + temp = [min(rel_data.sd_min_2), max(rel_data.sd_plus_2)]; + ylim([min(temp)-0.1*range(temp), max(temp)+0.1*range(temp)]) + set(gca, 'FontSize', ftsize-2) + xlabel('Age [years]', 'FontSize', ftsize) + [label, units, abbr, graph_title, graph_title_no_units] = make_param_label(curr_param); + if strcmp(curr_param, 'len') + units = 'mm'; + abbr = 'Length'; + end + if length(curr_param)>3 & strcmp(curr_param(1:3), 'dia') + units = 'mm'; + abbr = 'Diameter'; + end + temp = strfind(abbr, '_'); + if ~isempty(temp) + abbr = abbr(1:temp-1); + end + ylabel([abbr, ' [' units ']'], 'FontSize', ftsize) + title(graph_title_no_units, 'FontSize', ftsize) + box off + grid on + + % save + savepath = [up.savefolder, 'changes_w_age_', curr_param]; + PrintFigs(gcf, paper_size/60, savepath) + +end + +end + +function make_haemod_plots(parameters, up) + +% setup +params = fieldnames(parameters); +params = params(~strcmp(params,'variations') & ~strcmp(params,'fixed') & ~strcmp(params,'wk_params')... + & ~strcmp(params,'desired_pwv_aorta') & ~strcmp(params,'desired_pwv_arm') & ~strcmp(params,'desired_pwv_leg')... + & ~strcmp(params,'network_spec') & ~strcmp(params,'age')); +ftsize = 32; +lwidth = 2; +paper_size = [500,400]; +age = parameters.age; +required_age = unique(age); + +% Make a plot of each of these params in turn +for param_no = 1 : length(params) + curr_param = params{param_no}; + + [rel_data.val, sds] = deal(nan(length(required_age),1)); + for age_no = 1 : length(required_age) + + rel_els = age == required_age(age_no); + eval(['curr_data = parameters.' curr_param '(rel_els);']) + if strcmp(curr_param, 'dbp') + curr_data = curr_data/133.33; % convert from Pa to mmHg + end + rel_data.val(age_no) = mean(curr_data); + sds(age_no) = std(curr_data); + end + rel_data.sd_min_1 = rel_data.val - sds; + rel_data.sd_min_2 = rel_data.val - 2*sds; + rel_data.sd_plus_1 = rel_data.val + sds; + rel_data.sd_plus_2 = rel_data.val + 2*sds; + + % Make figure + figure('Position', [20, 20, paper_size]) + subplot('Position', [0.18,0.21,0.80,0.70]) + fprintf(['\n - Making plot for ' curr_param]) + + % plot data + plot(required_age, rel_data.val, 'k', 'LineWidth', lwidth), + hold on + plot(required_age, rel_data.sd_min_1, '--k', 'LineWidth', lwidth) + plot(required_age, rel_data.sd_min_2, '--k', 'LineWidth', lwidth) + plot(required_age, rel_data.sd_plus_1, '--k', 'LineWidth', lwidth) + plot(required_age, rel_data.sd_plus_2, '--k', 'LineWidth', lwidth) + + % tidy up + xlim([min(required_age), max(required_age)]); + temp = [min(rel_data.sd_min_2), max(rel_data.sd_plus_2)]; + if range(temp) == 0 + temp = [temp(1)-1, temp(1)+1]; + end + ylim([min(temp)-0.1*range(temp), max(temp)+0.1*range(temp)]) + set(gca, 'FontSize', ftsize-2) + xlabel('Age [years]', 'FontSize', ftsize) + [label, units, abbr, graph_title, graph_title_no_units] = make_param_label(curr_param); + temp = strfind(abbr, '_'); + if ~isempty(temp) + abbr = abbr(1:temp-1); + end + ylabel([abbr, ' [' units ']'], 'FontSize', ftsize) + title(graph_title_no_units, 'FontSize', ftsize) + box off + grid on + + % save + savepath = [up.savefolder, 'expected_changes_w_age_', curr_param]; + PrintFigs(gcf, paper_size/60, savepath) + +end + +end + +function PrintFigs(h, paper_size, savepath) +set(h,'PaperUnits','inches'); +set(h,'PaperSize', [paper_size(1), paper_size(2)]); +set(h,'PaperPosition',[0 0 paper_size(1) paper_size(2)]); +set(gcf,'color','w'); +print(h,'-depsc',savepath) +%print(h,'-dpdf',savepath) +close all; + +% save +fid = fopen([savepath, '.txt'], 'w'); +p = mfilename('fullpath'); +p = strrep(p, '\', '\\'); +fprintf(fid, ['Figures generated by:\n\n ' p '.m \n\n on ' datestr(today)]); +fclose all; + +end + +function wave_speeds = calculate_theoretical_wave_speeds(rel_network_spec, k, rho) + +% find current wave speeds of each segment (based on average radius) +ave_radius = mean([rel_network_spec.inlet_radius(:), rel_network_spec.outlet_radius(:)], 2); +ave_radius_cm = 100*ave_radius; +wave_speed = empirical_wave_speed(ave_radius_cm, k, rho); + +% find current wave speeds along certain paths +% - aorta:carotid-femoral (noting that carotid and femoral measurements are taken half way along carotid and femoral arteries) +lens_aorta_carotid = [rel_network_spec.length([1,2]); rel_network_spec.length(15)/2]; +carotid_radius_cm = 100* (rel_network_spec.inlet_radius(15) - (0.25*(rel_network_spec.inlet_radius(15) - rel_network_spec.outlet_radius(15)))); +path_speeds_aorta_carotid = [wave_speed([1,2]); empirical_wave_speed(carotid_radius_cm, k, rho)]; + +lens_aorta_femoral = [rel_network_spec.length([1,2,14,18,27,28,35,37,39,41,42,44]); rel_network_spec.length(46)/2]; +femoral_radius_cm = 100* (rel_network_spec.inlet_radius(46) - (0.25*(rel_network_spec.inlet_radius(46) - rel_network_spec.outlet_radius(46)))); +path_speeds_aorta_femoral = [wave_speed([1,2,14,18,27,28,35,37,39,41,42,44]); empirical_wave_speed(femoral_radius_cm, k, rho)]; + +path_len = sum(lens_aorta_femoral)-sum(lens_aorta_carotid); +time_taken = sum(lens_aorta_femoral./path_speeds_aorta_femoral) - sum(lens_aorta_carotid./path_speeds_aorta_carotid); +wave_speeds.aorta = path_len/time_taken; + +% - arm:brachial-radial (noting that brachial measurements are taken half way along brachial) +lens_aorta_radial = rel_network_spec.length([1,2,14,19,21,22]); +path_speeds_aorta_radial = wave_speed([1,2,14,19,21,22]); +lens_aorta_brachial = [rel_network_spec.length([1,2,14,19]); rel_network_spec.length(21)*0.75]; +lens_aorta_brachial = [rel_network_spec.length([1,2,14,19]); rel_network_spec.length(21)/2]; %%%%% CHANGE +brachial_radius_cm = 100* (rel_network_spec.inlet_radius(21) - (0.375*(rel_network_spec.inlet_radius(21) - rel_network_spec.outlet_radius(21)))); +brachial_radius_cm = 100* (rel_network_spec.inlet_radius(21) - (0.5*(rel_network_spec.inlet_radius(21) - rel_network_spec.outlet_radius(21)))); %%%%%% CHANGE +path_speeds_aorta_brachial = [wave_speed([1,2,14,19]); empirical_wave_speed(brachial_radius_cm, k, rho)]; + +path_len = sum(lens_aorta_radial)-sum(lens_aorta_brachial); +time_taken = sum(lens_aorta_radial./path_speeds_aorta_radial) - sum(lens_aorta_brachial./path_speeds_aorta_brachial); +wave_speeds.arm = path_len/time_taken; + +% - leg:femoral-ankle +ankle_els = [1,2,14,18,27,28,35,37,39,41,42,44,46,49]; +lens_aorta_ankle = rel_network_spec.length(ankle_els); +path_speeds_aorta_ankle = wave_speed(ankle_els); +femoral_els = [1,2,14,18,27,28,35,37,39,41,42,44]; +lens_aorta_femoral = rel_network_spec.length(femoral_els); +path_speeds_aorta_femoral = wave_speed(femoral_els); + +path_len = sum(lens_aorta_ankle)-sum(lens_aorta_femoral); +time_taken = sum(lens_aorta_ankle./path_speeds_aorta_ankle) - sum(lens_aorta_femoral./path_speeds_aorta_femoral); +wave_speeds.leg = path_len/time_taken; + +end + +function wave_speed = empirical_wave_speed(ave_radius_cm, k, rho) + +Eh_D0 = (k(1)*exp(k(2)*ave_radius_cm))+k(3); % Eh/D0 (from Mynard's 2015 paper, eqn 3) +c0_squared = (2/3)*(Eh_D0/(rho/1000)); % from Mynard's 2015 paper, eqn 3, converts rho from kg/m3 to g/cm3 +wave_speed = sqrt(c0_squared)/100; % converts from cm/s to m/s. + +end + +function wave_speed_cost_function = calculate_k3_cost_function(rel_network_spec, k, k3, rho, desired_wave_speeds) + +wave_speeds = calculate_theoretical_wave_speeds(rel_network_spec, [k(1), k(2), k3], rho); + +wave_speed_diffs = [wave_speeds.aorta - desired_wave_speeds.aorta, ... + wave_speeds.arm - desired_wave_speeds.arm, ... + wave_speeds.leg - desired_wave_speeds.leg]; + +% - cost function is solely based on aortic wave speed +temp = wave_speed_diffs(1); +wave_speed_cost_function = sqrt(mean(temp.^2)); + +end + +function [baseline_val, sd, eqn] = extract_values_from_literature(required_age, param, up) + +% extract data from the most reliable article(s) for this parameter +article_data = extract_data_from_articles(param, up); + +% interpolate article data (using best fit) to provide values at each age of interest +abs_data = fit_article_data(article_data, param, up); + +% Calculate baseline value and SD +eqn = abs_data; +if sum(strcmp(fieldnames(eqn), 'mean_f')) + % for linear changes where you can simply use the linear regression equation + baseline_val = eqn.mean_f.p1 * required_age + eqn.mean_f.p2; + sd = eqn.sd_f.p1 * required_age + eqn.sd_f.p2; +else + % for non-linear changes where you have to query the value at this particular age + rel_el = eqn.age == required_age; + baseline_val = eqn.mean(rel_el); + sd = eqn.sd(rel_el); +end + +end + +function article_data = extract_data_from_articles(param, up) + +switch param + + case 'sv' + + % All data obtained from male european data given in Table A2a and A2b of Poppe 2015 + article_data.val.age = 20:80; + sv_u = 102.35 - 0.3856*article_data.val.age; + sv_l = 42.94 - 0.1193*article_data.val.age; + article_data.val.v = (sv_u + sv_l)/2; % approx median value + article_data.sd.age = 20:80; + article_data.sd.mean_val = article_data.val.v; + article_data.sd.v= (sv_u-sv_l)/range(norminv([0.05,0.95])); % the 90% range specified by the upper and lower reference values, divided by the number of SDs from the mean (measuring both directions) which contain 90% of normally distributed values. + + case 'hr' + + % Mean data obtained from male data in Fig.1 of Yashin2006 + article_data.val.age = 32.5:5:92.5; + temp = [80,95,97.5,96,94,93,90,84,76,66,57,51,51]; + article_data.val.v = 66 + (12*(temp-5)/(99-5)); + + % SD data calculated from Table 1 of Petersen2017 (assumed to remain constant with age) + + means = [67,69,70]; sds = [10,12,11]; n = [240,333,231]; + overall_n = sum(n); + overall_mean = sum(means.*n)/overall_n; + overall_sd_squared = 0; + for dataset_no = 1 : length(n) + curr_n = n(dataset_no); + curr_mean = means(dataset_no); + curr_sd = sds(dataset_no); + curr_contribution_to_sd_squared = ((curr_sd^2) * (curr_n-1)) + ... + (curr_n*curr_mean^2) + (curr_n*(overall_mean^2)) - ... + (2*curr_n*curr_mean*overall_mean); + overall_sd_squared = overall_sd_squared + (curr_contribution_to_sd_squared/(overall_n-1)); + end + overall_SD = sqrt(overall_sd_squared); + + article_data.sd.age = [51, 59, 68]; + article_data.sd.mean_val = ones(1,3)*overall_mean; + article_data.sd.v = ones(1,3)*overall_SD; + + case 'dia_asc' % 'Dia - Aorta Asc' + + % Mean data obtained from Fig.4 of Hickson2010 (mm) - L1 + article_data.val.age = [24,34,45,57,63,73]; + article_data.val.v = 10 + (25*[35.5,38.5,41.75,42.0,44.0,44.5]./47); + + % SD data obtained from male data in Table 2 of Agmon2003 (assumed to remain constant with age and distance along the aorta) + % - obtained 8.9 % variation by considering male data at all three relevant aortic sites + article_data.sd.age = article_data.val.age; % these are from Hickson2010 + article_data.sd.mean_val = article_data.val.v; % these are from Hickson2010 + article_data.sd.v = (8.9/100)*article_data.val.v; + + case 'dia_desc_thor' % 'Dia - Aorta D Thor' + + % Mean data obtained from Fig.4 of Hickson2010 (mm) - L2 + article_data.val.age = [24,34,45,57,63,73]; + article_data.val.v = 10 + (25*[48,53.5,58.5,58,65,64.5]./108); + + % SD data obtained from male data in Table 2 of Agmon2003 (assumed to remain constant with age and distance along the aorta) + % - obtained 8.9 % variation by considering male data at all three relevant aortic sites + article_data.sd.age = article_data.val.age; % these are from Hickson2010 + article_data.sd.mean_val = article_data.val.v; % these are from Hickson2010 + article_data.sd.v = (8.9/100)*article_data.val.v; + + case 'dia_abd' % 'Dia - Aorta Abd' + + % Mean data obtained from Fig. 4 of Hickson2010 (mm) - L4 + article_data.val.age = [24,34,45,57,63,73]; + article_data.val.v = 10 + (25*[29.5,35,38,37,42.5,44]./108); + + % SD data obtained from male data in Table 2 of Agmon2003 (assumed to remain constant with age and distance along the aorta) + % - obtained 8.9 % variation by considering male data at all three relevant aortic sites + article_data.sd.age = article_data.val.age; % these are from Hickson2010 + article_data.sd.mean_val = article_data.val.v; % these are from Hickson2010 + article_data.sd.v = (8.9/100)*article_data.val.v; + + case 'dia_carotid' % 'Dia - Carotid' + + % All data taken from the male data in Table 1 of Hansen1995 (mm) + article_data.val.age = [14,25,46,60,71]; + article_data.val.v = [6.9, 7.7, 8.3, 8.2, 9.0]; + article_data.sd.age = [14,25,46,60,71]; + article_data.sd.mean_val = [6.9, 7.7, 8.3, 8.2, 9.0]; + article_data.sd.v = [0.7, 0.4, 0.8, 0.8, 0.7]; + + case 'len' % 'Length - Aorta Asc' + + % Mean data from Table 1 and Fig. 4 of Hickson2010 (mm) - ages in table 1, lengths in fig 4 + article_data.val.age = [24,34,45,57,63,73]; % From Hickson + article_data.val.v = [90, 100, 100, 108, 118, 128]; % NEEDS MEASURING + + % SD data obtaine from Table 1 of Bensalah2014 + article_data.sd.age = [24,34,45,57,63,73]; % From Hickson + article_data.sd.mean_val = [90, 100, 100, 108, 118, 128]; % NEEDS MEASURING + article_data.sd.v = mean([14.0/105.5, 17.2/126.9])*article_data.sd.mean_val; % from the two groups in Table1 of Bensalah 2014 + + case 't_pf' + + % All data obtained from Table 1 of Bensalah2014 (ms) + article_data.val.v = 104; + article_data.sd.mean_val = 104; + article_data.sd.v = 22; + + % All data obtained from PEF control group in Table 1 of Kamimura2016 (ms) + article_data.val.v = 79; + article_data.sd.mean_val = 79; + article_data.sd.v = 11; + + case 'reg_vol' + + % All data obtained from Table 1 of Bensalah2014 (ml) + article_data.val.v = 0.73; + article_data.sd.mean_val = 0.73; + article_data.sd.v = 0.63; + + case 'pvr' + + % Mean data obtained from Fig. 2 of McVeigh1999 (dyne s cm-5) + article_data.val.age = 20:80; + article_data.val.v = (8.1*article_data.val.age) + 926.9; % invasive (Fig. 2) + %article_data.val.v = (12.3*article_data.val.age) + 691.7; % non-invasive (Fig. 3) + article_data.sd.age = article_data.val.age; + + % SD data obtained from text in Bertand1985 (dyne s cm-5) + article_data.sd.mean_val = article_data.val.v; + article_data.sd.v = (180/1170)*article_data.sd.mean_val; % Data from Bertand1985 (dyne s cm-5) + + + case 'pvc' + + % Mean data obtained from Fig.2 of McVeigh1999 (ml/mmHg) + article_data.val.age = 20:80; + article_data.val.v = (-0.001*article_data.val.age) + 0.113; % invasive (Fig.2) + %article_data.val.v = (-0.002*article_data.val.age) + 0.151; % non-invasive (Fig. 3) + article_data.sd.age = article_data.val.age; + + % SD data obtained from the results section (p.1245) of Resnick2000 (ml/mmHg) + article_data.sd.mean_val = article_data.val.v; + article_data.sd.v = (0.02/0.073)*article_data.sd.mean_val; % Data from Resnick2000, results p.1245 (ml/mmHg) + + % scale to make pvc a scaling factor + scaling_factor = 1/article_data.val.v(article_data.val.age == 25); + article_data.val.v = article_data.val.v*scaling_factor; + article_data.sd.mean_val = article_data.val.v; + article_data.sd.v = article_data.sd.v*scaling_factor; + + case 'p_out' + + % Data taken from DOI: 10.1152/jappl.1993.74.2.946 Parazynski 1993 + article_data.val.v = 33.2*133.33; + article_data.sd.mean_val = article_data.val.v; + article_data.sd.v = 1.5*sqrt(13)*133.3; + + case 'rho' + + article_data.val.v = 1060; % kg/m3 + article_data.sd.mean_val = article_data.val.v; + article_data.sd.v = 0.1*article_data.sd.mean_val; % no particular reason for using this value + + case 'mbp' + + % All data obtained from male data in Table 1 of McEniery2005 + article_data.val.age = 15.5:10:85.5; % assumed mid-points of age categories + article_data.val.v = [88, 89, 92, 95, 95, 94, 93, 92]; % i think these are obtained by integrating the central BP waveform, which was obtained from radial waveform using Sphygmocor + article_data.sd.age = article_data.val.age; + article_data.sd.mean_val = article_data.val.v; + article_data.sd.v = [8, 8, 8, 7, 7, 7, 7, 8]; + + case 'dbp' + + % All data obtained from male data in Table 1 of McEniery2005 + % although they are peripheral, looking at CSBP and CPP, they seem to be similar to central DBPs. + article_data.val.age = 15.5:10:85.5; % assumed mid-points of age categories + article_data.val.v = 133.33*[73, 75, 77, 79, 79, 78, 76, 75]; % i think these are obtained by integrating the central BP waveform, which was obtained from radial waveform using Sphygmocor + article_data.sd.age = article_data.val.age; + article_data.sd.mean_val = article_data.val.v; + article_data.sd.v = 133.33*[8, 8, 7, 6, 6, 6, 6, 9]; + + case 'p_drop' + + article_data.val.v = 3.0; + article_data.val.v = 0; + article_data.sd.mean_val = article_data.val.v; + article_data.sd.v = 10; % temporary data (no particular reason for using this value) + + case 'mu' + + article_data.val.v = 2.5e-3; % Pa s (2e-3 provides a lower pressure drop between aorta and periphery than 3e-3). + article_data.sd.mean_val = article_data.val.v; + article_data.sd.v = 1e-3; % temporary data (no particular reason for using this value) + + case 'alpha' + + article_data.val.v = 4/3; + article_data.sd.mean_val = article_data.val.v; + article_data.sd.v = 0.16; % temporary data (no particular reason for using this value) + + case 'time_step' + + article_data.val.v = 5e-5; % s + article_data.sd.mean_val = article_data.val.v; + article_data.sd.v = 2e-5; % temporary data (no particular reason for using this value) + + case 'visco_elastic_log' + + article_data.val.v = 1; % logical: 1 indicates visco-elastic + article_data.sd.mean_val = article_data.val.v; + article_data.sd.v = 1; + + case 'reflect_log' + + article_data.val.v = 1; % logical: 1 indicates normal reflections + article_data.sd.mean_val = article_data.val.v; + article_data.sd.v = 1; +end + + +end + +function abs_data = fit_article_data(article_data, param, up) + +change_type = identify_chosen_change(param); + +abs_data.age = up.mod_ages; +thresh = 1e-10; + +if strcmp(change_type, 'increase') || strcmp(change_type, 'decrease') + + % fit mean values (using linear fit) + abs_data.mean_f=fit(article_data.val.age(:),article_data.val.v(:),'poly1'); + abs_data.mean = feval(abs_data.mean_f,abs_data.age); abs_data.mean = abs_data.mean(:)'; + % fit SDs (using linear fit) + abs_data.sd_f=fit(article_data.sd.age(:),article_data.sd.v(:),'poly1'); + abs_data.sd = feval(abs_data.sd_f,abs_data.age); abs_data.sd = abs_data.sd(:)'; + +elseif strcmp(change_type, 'complex') + + % fit mean values (using non-linear fit) + abs_data.mean = interp1(article_data.val.age, article_data.val.v, abs_data.age, 'pchip', 'extrap'); + % fit SDs (using linear fit) + abs_data.sd_f=fit(article_data.sd.age(:),article_data.sd.v(:),'poly1'); + abs_data.sd = feval(abs_data.sd_f,abs_data.age); abs_data.sd = abs_data.sd(:)'; + +elseif strcmp(change_type, 'none') + + % copy across mean + abs_data.mean = mean(article_data.val.v)*ones(length(abs_data.age),1); + abs_data.mean_f.p1 = 0; + abs_data.mean_f.p2 = mean(article_data.val.v); + % copy across SD + abs_data.sd = mean(article_data.sd.v)*ones(length(abs_data.age),1); + abs_data.sd_f.p1 = 0; + abs_data.sd_f.p2 = mean(article_data.sd.v); + +end + +end + +function [change_type, sd_type] = identify_chosen_change(param) + +switch param + case 'sv' + change_type = 'decrease'; + case 'hr' + change_type = 'complex'; + case 'dia_asc' + change_type = 'increase'; + case 'dia_desc_thor' + change_type = 'increase'; + case 'dia_abd' + change_type = 'increase'; + case 'dia_carotid' + change_type = 'increase'; + case 'len' + change_type = 'increase'; + case 'Length - Aorta D Thor' + change_type = 'none'; + case 'Length - Aorta Abd' + change_type = 'none'; + case 'Length - Carotid' + change_type = 'none'; + case 'lvet' + change_type = 'none'; + case 't_pf' + change_type = 'none'; + case 'reg_vol' + change_type = 'none'; + case 'pvr' + change_type = 'increase'; + case 'pvc' + change_type = 'decrease'; + sd_type = 'relative'; + case 'Stiffness - Radial' + change_type = 'none'; + case 'Stiffness - Iliac' + change_type = 'none'; + case 'Stiffness - Femoral' + change_type = 'none'; + case 'Stiffness - Carotid' + change_type = 'increase'; + case 'Stiffness - Brachial' + change_type = 'increase'; + case 'Stiffness - Aorta D Thor' + change_type = 'increase'; + case 'Stiffness - Aorta Asc' + change_type = 'increase'; + case 'Stiffness - Aorta Abd' + change_type = 'increase'; + case 'PWV - Aorta' + change_type = 'increase'; + case 'PWV - Arm' + change_type = 'increase'; + case 'PWV - Leg' + change_type = 'increase'; + case 'p_out' + change_type = 'none'; + case 'rho' + change_type = 'none'; + case 'mu' + change_type = 'none'; + case 'alpha' + change_type = 'none'; + case 'time_step' + change_type = 'none'; + case 'mbp' + change_type = 'complex'; + case 'dbp' + change_type = 'complex'; + case 'p_drop' + change_type = 'none'; + case 'visco_elastic_log' + change_type = 'none'; + case 'reflect_log' + change_type = 'none'; +end + +end + +function network_spec = obtain_network_spec(eqns, up) +% This function loads the network spec from the file specifying the +% arterial geometry. + +% Load data +temp = tdfread(up.network_spec_file); + +% Store relevant fields +network_spec.seg_no = temp.Segment_No; +network_spec.inlet_node = temp.Inlet_node; +network_spec.outlet_node = temp.Outlet_node; +network_spec.length = temp.Length_0x5Bm0x5D; +network_spec.inlet_radius = temp.Inlet_Radius_0x5Bm0x5D; +network_spec.outlet_radius = temp.Outlet_Radius_0x5Bm0x5D; +network_spec.segment_name = temp.Name; + +% identify various properties +[network_spec.proximal_aorta, network_spec.aorta, network_spec.asc_aorta, network_spec.desc_thor_aorta, network_spec.abd_aorta, network_spec.both_carotid, network_spec.femoral_dorsalis, network_spec.brachial_radial] = deal(false(length(network_spec.seg_no),1)); +network_spec.proximal_aorta([1,2]) = true; % excluded 14 because it seemed to be beyond the usual definition of ""aortic arch"" +network_spec.aorta([1,2,14,18,27,28,35,37,39,41]) = true; +network_spec.asc_aorta([1,2]) = true; +network_spec.desc_thor_aorta([14,18,27]) = true; % needs checking +network_spec.abd_aorta([28,35,37,39,41]) = true; % needs checking +network_spec.both_carotid([5,15]) = true; +network_spec.femoral_dorsalis([46,49]) = true; % the dorsalis is ""a continuation of the left anterior artery"": https://en.wikipedia.org/wiki/Dorsalis_pedis_artery +network_spec.brachial_radial([21,22]) = true; % left side +network_spec.asc_aorta_femoral([1,2,14,18,27,28,35,37,39,41,42,44]) = true; % left side + +end + +function parameters = add_wk_vascular_bed_parameters(parameters) + +fprintf('\n - Adding in Wk vascular bed parameters') + +%% Load Windkessel data +parameters.wk_params = [6.9040,0.021726;20.755,0.026499;16.852,0.032637;16.852,0.032637;10.824,0.050811;8.368,0.065727;8.368,0.065727;21.252,0.02606;27.832,0.019761;54.084,0.010169;10.374,0.053018;26.119,0.021057;32.29,0.017033;32.29,0.017033;14.786,0.037197;14.824,0.037102]; + +end + +function parameters = specify_fixed_simulation_parameters(parameters) + +fprintf('\n - Specifying fixed simulation parameters') + +%% ~~~~~~~~~~~~~~~~~~ General Model Settings ~~~~~~~~~~~~~~~~~~ + +%- Terminal conditions +%parameters.fixed.types.terminal = 'reflect'; % 'reflect' or 'absorb' + +%- Arterial tree +parameters.fixed.arterial_tree = 'M116art'; % 'M55art', 'M96_art', or 'M116_art' + +% specify which segments are to be modelled as visco-elastic (if visco-elastic modelling is being used): +parameters.fixed.visco_elastic_segments = 'some'; % 'all', 'hand', or 'some' +switch parameters.fixed.visco_elastic_segments + % if element is less than or equal to this length then make elastic rather than visco-elastic + case 'all' % results in flow not being subsonic in simulation + parameters.fixed.elmt_shortL_vw = 0.000; %Short element [m] + case 'hand' % ensures that all the arteries in the path of the digital artery are visco-elastic + parameters.fixed.elmt_shortL_vw = 0.009; %Short element [m] + case 'some' % original setting from Marie's work (NB: it doesn't seem to run if it's less than 0.011) + parameters.fixed.elmt_shortL_vw = 0.011; %Short element [m] +end + +%% ~~~~~~~~~~~~~~~~~~ Numerical Simulation Settings ~~~~~~~~~~~~~~~~~~ + +%- Simulation settings +parameters.fixed.duration = 6.5; %Duration of simulation [s] (originally 8.5 s) +parameters.fixed.output_dt = 1e-3; %Time step of .his output history files [s] +parameters.fixed.iostep_t = 0.1; %Time step of .out output files (flag -O) [s] +parameters.fixed.LinearForm = 0; %1 if linear, 0 if nonlinear +parameters.fixed.p_order = 3; %Polynomial order +parameters.fixed.q_order = 3; %Quadrature order +parameters.fixed.elmt_shortL_reduced = 0.016; % reduces complexity if element is less than this length [m] % original setting from Marie's work +parameters.fixed.p_reduced = 2; %Reduced order for short segments +parameters.fixed.q_reduced = 2; +parameters.fixed.int_time = 2; %Time integration order (INTTYPE) +parameters.fixed.elmt = 0.02; %Length of a single element in spatial discretisation [m] +parameters.fixed.R1_FIXED = 0; %=1 if windkessel R1 is fixed via input dataFile; =0 if R1 = characteristic impedance Z0 + +%- Simulation outputs +parameters.fixed.artery_output = [1 2 5 7 8 14 15 18 21 22 27 38 39 41 46 49 55 56 60 61 62 63 68 71 74 75 76 85 87 102 103 104 105 112 113 114 115]; %Vessel number where output is created, at proximal, mid, and distal points +parameters.fixed.artery_output = [1 2 5 7 8 14 15 18 19 21 22 27 28 35 37 39 41 42 44 46 49 87 108 112]; % Adapted by PC to give only the segments he's interested in +parameters.fixed.artery_output = 1:116; % trying all of them. + +%% ~~~~~~~~~~~~~~~~~~ Post-processing Settings ~~~~~~~~~~~~~~~~~~ + +%- Arterial segments and paths of interest (used for post-processing) +parameters.fixed.aorta_path = [1 2 14 18 27 28 35 37 39 41]; +% these go: segment number; relevant element of that segment; path of segments leading up to that segment +parameters.fixed.Art_aorta = 1; parameters.fixed.Pt_aorta = 1; parameters.fixed.Path_aorta = []; +parameters.fixed.Art_asc = 1; parameters.fixed.Pt_asc = 2; parameters.fixed.Path_asc = []; % +mid length 1 +parameters.fixed.Art_desc = 18; parameters.fixed.Pt_desc = 2; parameters.fixed.Path_desc = [1 2 14]; % +mid length 18 +parameters.fixed.Art_thoAo = 27; parameters.fixed.Pt_thoAo = 2; parameters.fixed.Path_thoAo = [1 2 14 18]; %+ mid length 27 +parameters.fixed.Art_bif = 41; parameters.fixed.Pt_bif = 3; parameters.fixed.Path_bif = parameters.fixed.aorta_path; +parameters.fixed.Art_car = 15; parameters.fixed.Pt_car = 2; parameters.fixed.Path_car = [1 2]; % +mid length 15 +parameters.fixed.Art_ren = 38; parameters.fixed.Pt_ren = 2; parameters.fixed.Path_ren = [1 2 14 18 27 28 35 37]; % +mid length 38 +%parameters.fixed.Art_iliac = 50; parameters.fixed.Pt_iliac = 2; parameters.fixed.Path_iliac = [aorta_path, 42]; % +mid length 50 +parameters.fixed.Art_brach = 21; parameters.fixed.Pt_brach = 3; parameters.fixed.Path_brach = [1 2 14 19 21]; % up to the end of brachial +parameters.fixed.Art_rad = 22; parameters.fixed.Pt_rad = 2; parameters.fixed.Path_rad = [1 2 14 19 21]; % +mid length 22 +parameters.fixed.Art_dig = 112;parameters.fixed.Pt_dig = 3; parameters.fixed.Path_dig = [1 2 14 19 21 22 108 112]; % up to the end of digital +parameters.fixed.Art_ankle = 49; parameters.fixed.Pt_ankle = 3; parameters.fixed.Path_ankle = [parameters.fixed.aorta_path, 42, 44, 46, 49]; % up to the end of ankle +parameters.fixed.Art_fem = 46; parameters.fixed.Pt_fem = 1; parameters.fixed.Path_fem = [parameters.fixed.aorta_path, 42 44]; % +parameters.fixed.Path_brain = [1, 2, 15, 16, 79, 65, 96, 71, 72]; +%parameters.fixed.Art_tibPost=54; parameters.fixed.Pt_tibPost = 3; parameters.fixed.Path_tibPost = [parameters.fixed.aorta_path, 42, 50, 52, 54]; +parameters.fixed.arteriograph_path = [18 27 28 35 37 39 41]; % added arteriograph path length, from: DOI 10.1007/s10439-010-9945-1 +parameters.fixed.relevant_paths = {'dig', 'ankle'}; + +end + +function inflow = generate_aortic_inflow_waveforms(parameters) + +fprintf('\n - Generating aortic inflow waves') + +for sim_no = 1 : length(parameters.age) + + % setup input parameters for this subject + input_params.wave_type = 'Mynard'; % use the template wave shape from Mynard 2015. + input_params.HR = parameters.hr(sim_no); + input_params.SV = parameters.sv(sim_no); + input_params.T_Peak_Flow = parameters.t_pf(sim_no); + input_params.Reg_Vol = parameters.reg_vol(sim_no); + input_params.LVET = parameters.lvet(sim_no); + input_params.plot_multiple = true; + input_params.do_plot = false; + + % save space + temp = AorticFlowWave_orig(input_params); + temp = rmfield(temp, 't'); + temp.v = single(temp.v); + inflow{sim_no} = temp; clear temp + + if rem(sim_no,100) == 0 + fprintf(['\n ' num2str(sim_no)]) + end +end + +end + +function make_table_equations(savefolder, eqns) + +%% Find equation text + +cardiac_params = {'HR', 'SV', 't_PF', 'reg_vol'}; +arterial_params = {'MBP'}; +vascular_params = {'PVC'}; +params = [cardiac_params, arterial_params, vascular_params]; + +no_sf = 3; + +for param_no = 1 : length(params) + curr_param = params{param_no}; + eval(['curr_eqn = eqns.' lower(curr_param) ';']) + + % Formulate equation for mean + if sum(strcmp(fieldnames(curr_eqn), 'mean_f')) + curr_mean_eqn = num2str(round(curr_eqn.mean_f.p2, no_sf, 'significant')); + if curr_eqn.mean_f.p1 ~= 0 && abs(curr_eqn.mean_f.p1) > 1e-10 + temp = num2str(round(curr_eqn.mean_f.p1, no_sf, 'significant')); + if strcmp(temp(1), '-') + temp = [' -- ', temp(2:end)]; + else + temp = [' + ', temp]; + end + curr_mean_eqn = [curr_mean_eqn, temp ' * age']; + end + + else + curr_mean_eqn = 'non-linear change'; + end + + % Formulate equation for SD + curr_sd_eqn = num2str(round(curr_eqn.sd_f.p2, no_sf, 'significant')); + if curr_eqn.sd_f.p1 ~= 0 && abs(curr_eqn.sd_f.p1) > 1e-10 + temp = num2str(round(curr_eqn.sd_f.p1, no_sf, 'significant')); + if strcmp(temp(1), '-') + temp = [' -- ', temp(2:end)]; + else + temp = [' + ', temp]; + end + curr_sd_eqn = [curr_sd_eqn, temp ' * age']; + end + + + % store equations + eval(['eqns_text.' curr_param '.mean = curr_mean_eqn;']) + eval(['eqns_text.' curr_param '.sd = curr_sd_eqn;']) +end + + +%% Create Table + +table_text = ['\\textbf{Cardiac} & & \\\\', newline]; +table_text = add_params_table_text(table_text, cardiac_params, eqns_text); +table_text = [table_text, '\\hline', newline]; +table_text = [table_text, '\\textbf{Arterial} & & \\\\', newline]; +table_text = add_params_table_text(table_text, arterial_params, eqns_text); +table_text = [table_text, '\\hline', newline]; +table_text = [table_text, '\\textbf{Vascular Beds} & & \\\\', newline]; +table_text = add_params_table_text(table_text, vascular_params, eqns_text); + +fid = fopen([savefolder, 'eqns_table.txt'], 'w'); +fprintf(fid, table_text); +fclose(fid); + +end + +function table_text = add_params_table_text(table_text, curr_params, eqns_text) + +for param_no = 1 : length(curr_params) + + curr_param = curr_params{param_no}; + + % Make label + [label, units, abbr, graph_title] = make_param_label(curr_param); + + % Extract relevant text + eval(['curr_eqns_text = eqns_text.' curr_param ';']) + + % Insert this line of the table + table_line = ['- ', label]; + table_line = [table_line, ' & ' curr_eqns_text.mean ' & ' curr_eqns_text.sd ]; + table_line = [table_line, '\\\\', newline]; + table_text = [table_text, table_line]; + clear table_line + +end + +end + +function eqns = calculate_equations(up) + +cardiac_params = {'sv', 'hr', 't_pf', 'reg_vol'}; +arterial_params = {'mbp', 'len'}; +vascular_params = {'pvc', 'p_out'}; +blood_params = {'rho'}; +params = [cardiac_params, arterial_params, vascular_params, blood_params]; + +for param_no = 1 : length(params) + + param = params{param_no}; + + %% Calculating values from raw data extracted from the literature + + % extract data from the most reliable article(s) for this parameter + article_data = extract_data_from_articles(param, up); + + % interpolate article data (using best fit) to provide values at each age of interest + eqn = fit_article_data(article_data, param, up); + + % Store equation for this parameter + if sum(strcmp(fieldnames(eqn), 'mean_f')) + eval(['eqns.' param '.mean_f = eqn.mean_f;']); + end + eval(['eqns.' param '.sd_f = eqn.sd_f;']); + +end + +% % Correct for length +% curr_init_length = eqns.len.mean_f.p1*up.baseline_age+eqns.len.mean_f.p2; +% scale_factor = 100/curr_init_length; +% eqns.len.mean_f.p1 = eqns.len.mean_f.p1*scale_factor; +% eqns.len.mean_f.p2 = eqns.len.mean_f.p2*scale_factor; +% eqns.len.sd_f.p1 = eqns.len.sd_f.p1*scale_factor; +% eqns.len.sd_f.p2 = eqns.len.sd_f.p2*scale_factor; + +%% Make table for publication +make_table_equations(up.savefolder, eqns); + +end","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/asi_case_study.m",".m","24519","698","function asi_case_study(pwdb_no) +% ASI_CASE_STUDY generates the plots reported in the case study on +% assessing aortic stiffness from digital PPG waves +% +% asi_case_study +% +% Inputs: - the 'pwdb_data' file produced by 'export_pwdb.m'. +% +% Outputs: - plots illustrating the results of the case study +% +% Accompanying Article: +% This code is provided to facilitate reproduction of the Pulse Wave +% Database described in: +% Charlton P.H. et al. Modelling arterial pulse waves in healthy +% ageing: a database for in silico evaluation of haemodynamics +% and pulse wave indices, ~~ under review ~~ +% DOI: ~~ tbc ~~ +% Further information on the pwdb Pulse Wave Database is provided in +% this article and at the project website: +% https://peterhcharlton.github.io/pwdb +% +% Author: Peter H. Charlton +% +% Licence: +% Permission is hereby granted, free of charge, to any person obtaining a copy +% of this software and associated documentation files (the ""Software""), to deal +% in the Software without restriction, including without limitation the rights +% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +% copies of the Software, and to permit persons to whom the Software is +% furnished to do so, subject to the following conditions: +% +% The above copyright notice and this permission notice shall be included in all +% copies or substantial portions of the Software. +% +% THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +% SOFTWARE. +% +% Copyright (C) 2019 King's College London +% +% v.1.0 Peter H. Charlton, King's College London + +fprintf('\n --- Running Aortic Stiffness Indices (ASI) Case Study ---') + +% Setup paths with current simulation paths +PATHS = setup_paths_for_post_processing(pwdb_no); + +% Create ASI plots +create_plots = 0; +if create_plots, create_asi_plots(PATHS, pwdb_no); end + +% Extract ASIs +collate_ASIs(PATHS); + +% % Quantify correlations of all ASIs +analyse_ASIs(PATHS, pwdb_no); + +% Make correlation graphs +correlation_graphs(PATHS, pwdb_no); + +% Make results figures +% results_figures(PATHS, pwdb_no); + +end + +function create_asi_plots(PATHS, sim_no) + +fprintf('\n - Creating Arterial Stiffness Index Plots') +%% Pulse wave indices + +% Load collated data +load(PATHS.collated_data) + +% Find baseline simulation +[data.baseline_sim_all, data.baseline_sim_age] = deal(false(length(collated_data),1)); +for sim_no = 1 : length(collated_data) + if sum(collated_data(sim_no).input_data.sim_settings.variations.params ~= 0) == 0 + data.baseline_sim_age(sim_no) = true; + if collated_data(sim_no).input_data.sim_settings.age == 25 + data.baseline_sim_all(sim_no) = true; + end + end +end +sim_to_use = find(data.baseline_sim_all); + +% Make plots in turn +sites = {'digital', 'carotid', 'carotid', 'radial'}; +%site_domain_no = [15, 15, 22, 112]; +signals = {'PPG', 'PPG', 'P','P', 'PPG'}; +domains = extractfield(collated_data(1).output_data, 'domain_no'); +fs = 1000; + +for plot_no = 1 : length(sites) + + % Identify relevant data + switch sites{plot_no} + case 'carotid' + dom_no = 15; + dist_prop = 0.5; + case 'radial' + dom_no = 22; + dist_prop = 1; + case 'digital' + dom_no = 112; + dist_prop = 1; + end + rel_row = find(domains == dom_no); + rel_data = collated_data(sim_to_use).output_data(rel_row); + req_dist = dist_prop*collated_data(sim_to_use).input_data.sim_settings.network_spec.length(dom_no); + [~, rel_dist_el] = min(abs(rel_data.distances-req_dist)); + rel_data.P = rel_data.P(:,rel_dist_el); + rel_data.PPG = rel_data.PPG_WK(:,rel_dist_el); + rel_data.t = [0:length(rel_data.P)-1]/fs; + + sig.fs = fs; + eval(['sig.v = rel_data.' signals{plot_no} ';']); + options.save_folder = '/Users/petercharlton/Google Drive/Work/Publications/In Preparation/2018 BIHS Conference/figure/'; + options.save_file = [sites{plot_no}, '_', signals{plot_no}, '_']; + options.plot_third_deriv = false; + PulseAnalyse6(sig, options); + +end + + +end + +function collate_ASIs(PATHS) + +fprintf('\n - Collating Arterial Stiffness Indices and Input Parameters') +%% Pulse wave indices + +% Load collated data +load(PATHS.exported_data_mat_pwdb_data) + +% settings +pw_param_names = {'AGI_mod', 'AI_c', 'RI', 'SI'}; +pwv_names = {'a', 'cf', 'br', 'fa'}; + +% Cycle through each simulation +subj_counter = 0; +for subj_no = 1 : length(data.config.age) + + % skip if this is an implausible subject + if ~data.plausibility.plausibility_log(subj_no) + continue + end + subj_counter = subj_counter+1; + + % record sim no + asi_data.sim(subj_counter,1) = subj_no; + asi_data.baseline_sim_all(subj_counter,1) = data.config.baseline_sim_for_all(subj_no); + asi_data.baseline_sim_age(subj_counter,1) = data.config.baseline_sim_for_age(subj_no); + + % Extract model input parameters for this simulation + input_vars = {'hr', 'sv', 'lvet', 'mbp', 'dia', 'pwv', 'age'}; + for input_var_no = 1 : length(input_vars) + eval(['asi_data.i_' input_vars{input_var_no} '(subj_counter,1) = data.config.' input_vars{input_var_no} '(subj_no);']); + + if ~strcmp(input_vars{input_var_no}, 'age') + rel_col = find(strcmp(input_vars{input_var_no}, data.config.variations.param_names)); + eval(['asi_data.i_' input_vars{input_var_no} '_SD(subj_counter,1) = data.config.variations.params(subj_no, rel_col);']); + end + + end + + feat_no = 0; + + % Cycle through pulse wave features + for param_no = 1 : length(pw_param_names) + curr_param_name = pw_param_names{param_no}; + feat_no = feat_no + 1; + + % Extract pulse wave features (at each site, for each signal) + asi_data.feat_names{1,feat_no} = curr_param_name; + + eval(['asi_data.val(subj_counter,feat_no) = data.haemods(subj_no).' curr_param_name ';']); + + clear curr_param_name + end + clear param_no + + + % Add in Pulse wave velocities + for pwv_name_no = 1 : length(pwv_names) + curr_param_name = pwv_names{pwv_name_no}; + eval(['asi_data.pwv_' curr_param_name '(subj_counter,1) = data.haemods(subj_no).PWV_' curr_param_name ';']); + end + clear pwv_name_no + +end +clear subj_no subj_counter + +save(PATHS.collated_ASIs, 'asi_data') + +end + +function correlation_graphs(PATHS, sim_no) + +fprintf('\n - Making correlation graphs') + +% setup +% rel_min_age = 25; rel_max_age = 55; +rel_min_age = 45; rel_max_age = 45; +lwidth = 2; +ftsize = 16; +markersize = 7; +paper_size = [400,300]; + +% Load ASI data +load(PATHS.collated_ASIs) +load(PATHS.ASI_results) + +% Highlighted age group +for feat_no = 1 : length(asi_data.feat_names) + + figure('Position', [20,20,paper_size]) + plot(asi_data.pwv_a, asi_data.val(:,feat_no), '.', 'MarkerSize', 8, 'Color', 0.2*[1 1 1]), hold on + h = lsline; + h.Color = 'k'; + + rel_els = asi_data.i_age >= rel_min_age & asi_data.i_age <= rel_max_age; + plot(asi_data.pwv_a(rel_els), asi_data.val(rel_els,feat_no), '.r', 'MarkerSize', 8), hold on + + set(gca, 'FontSize', ftsize) + xlabel('Aortic PWV (m/s)', 'FontSize', ftsize) + ylab_txt = strrep(asi_data.feat_names{feat_no}, '_', ' '); + ylab_txt = strrep(ylab_txt, 'AI c', 'AIx'); + ylab_txt = strrep(ylab_txt, 'AGI mod', 'AGI mod (unitless)'); + ylab_txt = strrep(ylab_txt, 'SI', 'SI (m/s)'); + ylab_txt = strrep(ylab_txt, 'RI', 'RI (unitless)'); + ylabel(ylab_txt, 'FontSize', ftsize) + feat_no = find(strcmp(rsq.feat_names, asi_data.feat_names{feat_no})); + rel_rsq = rsq.v(feat_no); + if rel_min_age == rel_max_age + rel_rsq_age = rsq_age.v(feat_no,find(rsq_age.age >= rel_min_age & rsq_age.age <= rel_max_age)); + else + refs = asi_data.pwv_a; + vals = asi_data.val(:,feat_no); + rel_els = find(asi_data.i_age >= rel_min_age & asi_data.i_age <= rel_max_age & ~isnan(vals) ); + temp = corrcoef(refs(rel_els), vals(rel_els)); + rel_rsq_age = temp(1,2)^2; clear temp + + end + + % R2 for all data + dim1 = [.2 .65 .3 .3]; + dim2 = [.2 .55 .3 .3]; + str = ['R^2 = ' num2str(rel_rsq,'%0.2f')]; + annotation('textbox',dim1,'String',str,'FitBoxToText','on','LineStyle','None', 'FontSize', ftsize, 'Color', 0.2*[1,1,1]); + str = ['R^2 = ' num2str(rel_rsq_age,'%0.2f')]; + annotation('textbox',dim2,'String',str,'FitBoxToText','on','LineStyle','None', 'FontSize', ftsize, 'Color', 'r'); + + box off + curr_range = range(asi_data.val(:,feat_no)); + ylim([min(asi_data.val(:,feat_no))-0.1*curr_range, max(asi_data.val(:,feat_no))-0.1*curr_range]) + if strcmp(ylab_txt, 'AIx') + ylim([min(asi_data.val(:,feat_no))-0.1*curr_range, 35]) + end + curr_range = range(asi_data.pwv_a); + xlim([min(asi_data.pwv_a)-0.1*curr_range, max(asi_data.pwv_a)-0.1*curr_range]) + PrintFigs(gcf, paper_size/70, [PATHS.CaseStudies, 'ASI_correlation_plot_hl_' asi_data.feat_names{feat_no}]) + +end + +% All data +for feat_no = 1 : length(asi_data.feat_names) + + figure('Position', [20,20,paper_size]) + plot(asi_data.pwv_a, asi_data.val(:,feat_no), 'x'), hold on + h = lsline; + h.Color = 'k'; + + set(gca, 'FontSize', ftsize) + xlabel('Aortic PWV [m/s]', 'FontSize', ftsize) + ylabel('Modified Ageing Index [au]', 'FontSize', ftsize) + ylabel(strrep(asi_data.feat_names{feat_no}, '_', ' '), 'FontSize', ftsize) + feat_no = find(strcmp(rsq.feat_names, asi_data.feat_names{feat_no})); + rel_rsq = rsq.v(feat_no); + title(['R^2 = ' num2str(rel_rsq,'%0.2f')], 'FontSize', ftsize) + box off + curr_range = range(asi_data.val(:,feat_no)); + ylim([min(asi_data.val(:,feat_no))-0.1*curr_range, max(asi_data.val(:,feat_no))-0.1*curr_range]) + curr_range = range(asi_data.pwv_a); + xlim([min(asi_data.pwv_a)-0.1*curr_range, max(asi_data.pwv_a)-0.1*curr_range]) + PrintFigs(gcf, paper_size/70, [PATHS.CaseStudies, 'ASI_correlation_plot_' asi_data.feat_names{feat_no}]) + +end + +end + +function analyse_ASIs(PATHS, sim_no) + +fprintf('\n - Analysing Performances of Arterial Stiffness Indices') + +paper_size = [200,200,700,300]; + +% Load ASI data +load(PATHS.collated_ASIs) + +% calculate correlation coefficients +refs = asi_data.pwv_a; +for feat_no = 1 : length(asi_data.feat_names) + vals = asi_data.val(:,feat_no); + rel_els = find(~isnan(vals)); + [temp, temp2] = corrcoef(refs(rel_els), vals(rel_els)); + rsq.v(feat_no,1) = temp(1,2)^2; + p(feat_no,1) = temp2(2); clear temp temp2 + + % best-fit line + f = fit(vals(rel_els), refs(rel_els), 'poly2'); + est_refs = feval(f, vals(rel_els)); + + % BA stats + errors = est_refs - refs(rel_els); + fit_asi_ba.bias(feat_no) = mean(errors); + fit_asi_ba.sd(feat_no) = std(errors); + fit_asi_ba.mae(feat_no) = mean(abs(errors)); + + fit_asi_ba.med_ae(feat_no) = median(abs(errors)); + fit_asi_ba.lq_ae(feat_no) = quantile(abs(errors), 0.25); + fit_asi_ba.uq_ae(feat_no) = quantile(abs(errors), 0.75); + + %clear errors f est_refs + +end +rsq.feat_names = asi_data.feat_names; +fit_asi_ba.names = asi_data.feat_names(:); + +% calculate correlation coefficients for each age group +refs = asi_data.pwv_a; +ages = unique(asi_data.i_age); +for feat_no = 1 : length(asi_data.feat_names) + for age_no = 1 : length(ages) + vals = asi_data.val(:,feat_no); + rel_els = find(~isnan(vals) & asi_data.i_age == ages(age_no)); + temp = corrcoef(refs(rel_els), vals(rel_els)); + rsq_age.v(feat_no,age_no) = temp(1,2)^2; clear temp + end +end +rsq_age.feat_names = asi_data.feat_names; +rsq_age.age = ages; + +% calculate pwv accuracy and precision +temp = fieldnames(asi_data); +pwv_types = temp(~cellfun(@isempty, strfind(temp, 'pwv_'))); +pwv_types = pwv_types(~strcmp(pwv_types, 'i_pwv_SD')); +pwv_types = pwv_types(~strcmp(pwv_types, 'pwv_aortic')); +for pwv_no = 1 : length(pwv_types) + + % Rsq stats + eval(['vals = asi_data.' pwv_types{pwv_no} ';']); + rel_els = ~isnan(vals); + temp = corrcoef(refs(rel_els), vals(rel_els)); + ba.rsq(pwv_no,1) = temp(1,2)^2; clear temp + + % BA stats + errors = vals(rel_els) - refs(rel_els); + ba.bias(pwv_no) = mean(errors); + ba.sd(pwv_no) = std(errors); + + % best-fit line + f = fit(vals(rel_els), refs(rel_els), 'poly2'); + est_refs = feval(f, vals(rel_els)); + + % BA stats + errors = est_refs - refs(rel_els); + fit_ba.bias(pwv_no) = mean(errors); + fit_ba.sd(pwv_no) = std(errors); + fit_ba.mae(pwv_no) = mean(abs(errors)); + + fit_ba.med_ae(pwv_no) = median(abs(errors)); + fit_ba.lq_ae(pwv_no) = quantile(abs(errors), 0.25); + fit_ba.uq_ae(pwv_no) = quantile(abs(errors), 0.75); + clear errors f est_refs + + % Age-specific Rsq values + for age_no = 1 : length(ages) + rel_els = find(~isnan(vals) & asi_data.i_age == ages(age_no)); + temp = corrcoef(refs(rel_els), vals(rel_els)); + ba.rsq_age.v(pwv_no,age_no) = temp(1,2)^2; clear temp + end + clear age_no rel_els vals errors +end +ba.feat_names = pwv_types; +fit_ba.names = pwv_types(:); + +% De-compose names of pulse wave inds +rsq.ind{feat_no} = rsq.feat_names{feat_no}; + +save(PATHS.ASI_results, 'rsq', 'rsq_age', 'ba', 'fit_ba', 'fit_asi_ba'); + +end + +function results_figures(PATHS, sim_no) + +fprintf('\n - Making results figures') + +load(PATHS.ASI_results) + +% setup +lwidth = 2; +ftsize = 16; +markersize = 7; + +%% Correlation results summary +do_plot = 1; +if do_plot + + addpath(genpath('/Users/petercharlton/Google Drive/Work/Code/Tools')) + paper_size = [450,270]; + figure('Position', [20,20,paper_size]) + subplot('Position', [0.03,0.19,0.95,0.81]) + ftsize = 16; + corr_res.pwv = ba.rsq(:); + corr_res.asi = rsq.v(:); + + data = [corr_res.pwv;corr_res.asi]; + catIdx = [ones(size(corr_res.pwv));zeros(size(corr_res.asi))]; + plotSpread(data,'categoryIdx',catIdx,... + 'categoryMarkers',{'+','o'},'categoryColors',{'r','b'}) + view([90 -90]) + lgd = legend({'Single-PW ASIs','PWVs'},'Location','SouthEast'); + lgd.Orientation = 'Horizontal'; + ylabel('Correlation with aortic PWV, R^2', 'FontSize', ftsize) + set(gca, 'FontSize', ftsize, 'XTick', []) + xlim([0.25 1.6]) + ylim([0 1]) + + PrintFigs(gcf, paper_size/70, [PATHS.CaseStudies, 'ASI_analysis_corr_summary']) + clear corr_res +end + +%% Correlation all vs age-groups +do_plot = 1; +if do_plot + + paper_size = [540,250]; + figure('Position', [20,20,paper_size]) + ftsize = 20; + temp_els = [find(strcmp(rsq.feat_names, 'PPG_15_c_div_a')), ... + find(strcmp(rsq.feat_names, 'P_22_b_div_a')), ... + find(strcmp(rsq.feat_names, 'PPG_112_d_div_a'))]; + corr_res.pwv.all = ba.rsq(:); + corr_res.asi.all = rsq.v(temp_els); + corr_res.pwv.age = ba.rsq_age.v(:); + corr_res.asi.age = rsq_age.v(temp_els,:); corr_res.asi.age = corr_res.asi.age(:); + + data = [corr_res.pwv.age; corr_res.pwv.all]; + gps = [ones(size(corr_res.pwv.age)); 2*ones(size(corr_res.pwv.all))]; + boxplot(data, gps, 'Widths', 0.7) + box off + ylim([0 1]) + view([90 -90]) + set(gca,'FontSize', ftsize, 'XTickLabel', {'Age-specific','All data'}) + ylabel('Correlation with Aortic PWV, R^2', 'FontSize', ftsize) + abc = findobj(gca, 'Type', 'Line'); + set(abc, 'LineWidth', 2) + PrintFigs(gcf, paper_size/70, [PATHS.CaseStudies, 'ASI_analysis_corr_age_all_PWV']) + + figure('Position', [20,20,paper_size]) + data = [corr_res.asi.age; corr_res.asi.all]; + gps = [ones(size(corr_res.asi.age)); 2*ones(size(corr_res.asi.all))]; + boxplot(data, gps, 'Widths', 0.7) + box off + ylim([0 1]) + view([90 -90]) + set(gca,'FontSize', ftsize, 'XTickLabel', {'Age-specific','All data'}) + ylabel('Correlation with Aortic PWV, R^2', 'FontSize', ftsize) + abc = findobj(gca, 'Type', 'Line'); + set(abc, 'LineWidth', 2) + PrintFigs(gcf, paper_size/70, [PATHS.CaseStudies, 'ASI_analysis_corr_age_all_ASI']) + +end + +%% PWV B-A results +do_plot = 1; +if do_plot + + paper_size = [400,270]; + figure('Position', [20,20,paper_size]) + subplot('Position', [0.29,0.17,0.69,0.81]) + pwv_names = ba.feat_names; + + [~,order] = sort(ba.bias); + + counter = 0; + for pwv_no = order + + % Plot the results for this PWV technique + counter = counter+1; + y_val = counter; + line_coords.x_loa = [ba.bias(pwv_no) - 2*ba.sd(pwv_no), ba.bias(pwv_no) + 2*ba.sd(pwv_no)]; + line_coords.x_bias = ba.bias(pwv_no); + line_coords.y = y_val*ones(1,2); + % - LOAs + plot(line_coords.x_loa, line_coords.y, 'o-k', 'LineWidth', lwidth, 'MarkerFaceColor', 'k', 'MarkerSize', markersize), hold on + % - Bias + plot(line_coords.x_bias, line_coords.y(1), 'dk', 'LineWidth', lwidth, 'MarkerFaceColor', 'k', 'MarkerSize', markersize+2), hold on + + end + + % Tidy-up + ax = gca; + set(gca, 'FontSize', ftsize, 'YTick', 1:length(pwv_names), 'YTickLabel', strrep(strrep(pwv_names(order), 'pwv_', ''), '_', '-')) + xlabel('Error [m/s]', 'FontSize', ftsize) + ylim([0.5 length(pwv_names)+0.5]) + box off + legend('LOAs', 'Bias','Location','SouthEast') + PrintFigs(gcf, paper_size/70, [PATHS.CaseStudies, 'ASI_analysis_PWV_BA']) + +end + +%% Plot Median AEs + +do_plot = 0; +if do_plot + [~,order] = sort(fit_ba.med_ae); + order = order(1:3); + + counter = 0; + for pwv_no = order + + % Plot the results for this PWV technique + counter = counter+1; + y_val = counter; + line_coords.x_loa = [fit_ba.lq_ae(pwv_no), fit_ba.uq_ae(pwv_no)]; + line_coords.x_bias = fit_ba.med_ae(pwv_no); + line_coords.y = y_val*ones(1,2); + % - LOAs + plot(line_coords.x_loa, line_coords.y, 'o-k', 'LineWidth', lwidth, 'MarkerFaceColor', 'k', 'MarkerSize', markersize), hold on + % - Bias + plot(line_coords.x_bias, line_coords.y(1), 'dk', 'LineWidth', lwidth, 'MarkerFaceColor', 'k', 'MarkerSize', markersize+2), hold on + + end + + temp_els = [find(strcmp(fit_asi_ba.names, 'AGI_mod')), ... + find(strcmp(fit_asi_ba.names, 'P_22_b_div_a')), ... + find(strcmp(fit_asi_ba.names, 'PPG_112_slope_b_d'))]; + [~,temp] = sort(fit_asi_ba.mae(temp_els)); rel_asi_ba_els = temp_els(temp(1:3)); + clear temp + for asi_no = 1 : length(rel_asi_ba_els) + + curr_el = rel_asi_ba_els(asi_no); + + % Plot the results for this ASI technique + counter = counter+1; + y_val = counter; + line_coords.x_loa = [fit_asi_ba.lq_ae(curr_el), fit_asi_ba.uq_ae(curr_el)]; + line_coords.x_bias = fit_asi_ba.med_ae(curr_el); + line_coords.y = y_val*ones(1,2); + % - LOAs + plot(line_coords.x_loa, line_coords.y, 'o-b', 'LineWidth', lwidth, 'MarkerFaceColor', 'b', 'MarkerSize', markersize), hold on + % - Bias + plot(line_coords.x_bias, line_coords.y(1), 'db', 'LineWidth', lwidth, 'MarkerFaceColor', 'b', 'MarkerSize', markersize+2), hold on + + + + end + + % Tidy-up + ax = gca; + all_names = [fit_ba.names(order); fit_asi_ba.names(rel_asi_ba_els)]; + set(gca, 'FontSize', ftsize, 'YTick', 1:length(all_names), 'YTickLabel', strrep(strrep(all_names, 'pwv_', ''), '_', '-')) + xlabel('Error [m/s]', 'FontSize', ftsize) + ylim([0.5 length(all_names)+0.5]) + box off + legend('IQR', 'Median','Location','SouthEast') + PrintFigs(gcf, paper_size/70, [PATHS.CaseStudies, 'ASI_analysis_PWV_med_AE_fit']) +end + +%% Plot fitted B-A Results + +do_plot = 0; +if do_plot + + [~,order] = sort(fit_ba.sd); + + counter = 0; + for pwv_no = order + + % Plot the results for this PWV technique + counter = counter+1; + y_val = counter; + line_coords.x_loa = [fit_ba.bias(pwv_no) - 2*fit_ba.sd(pwv_no), fit_ba.bias(pwv_no) + 2*fit_ba.sd(pwv_no)]; + line_coords.x_bias = fit_ba.bias(pwv_no); + line_coords.y = y_val*ones(1,2); + % - LOAs + plot(line_coords.x_loa, line_coords.y, 'o-k', 'LineWidth', lwidth, 'MarkerFaceColor', 'k', 'MarkerSize', markersize), hold on + % - Bias + plot(line_coords.x_bias, line_coords.y(1), 'dk', 'LineWidth', lwidth, 'MarkerFaceColor', 'k', 'MarkerSize', markersize+2), hold on + + end + + [~,temp] = sort(fit_asi_ba.sd); rel_asi_ba_els = temp(1:5); clear temp + for asi_no = 1 : length(rel_asi_ba_els) + + curr_el = rel_asi_ba_els(asi_no); + + % Plot the results for this ASI technique + counter = counter+1; + y_val = counter; + line_coords.x_loa = [fit_asi_ba.bias(curr_el) - 2*fit_asi_ba.sd(curr_el), fit_asi_ba.bias(curr_el) + 2*fit_asi_ba.sd(curr_el)]; + line_coords.x_bias = fit_asi_ba.bias(curr_el); + line_coords.y = y_val*ones(1,2); + % - LOAs + plot(line_coords.x_loa, line_coords.y, 'o-b', 'LineWidth', lwidth, 'MarkerFaceColor', 'b', 'MarkerSize', markersize), hold on + % - Bias + plot(line_coords.x_bias, line_coords.y(1), 'db', 'LineWidth', lwidth, 'MarkerFaceColor', 'b', 'MarkerSize', markersize+2), hold on + + + end + + % Tidy-up + ax = gca; + set(gca, 'FontSize', ftsize, 'YTick', 1:length(pwv_names), 'YTickLabel', strrep(strrep(pwv_names(order), 'pwv_', ''), '_', '-')) + xlabel('Error [m/s]', 'FontSize', ftsize) + ylim([0.5 length(pwv_names)+0.5]) + box off + legend('95% CI', 'Mean','Location','SouthEast') + PrintFigs(gcf, paper_size/70, [PATHS.CaseStudies, 'ASI_analysis_PWV_BA_fit']) + +end + +%% Correlation plot for all ages and only one age group + +load(PATHS.collated_ASIs) +rel_asi_name = 'AGI_mod'; +%rel_asi_name = 'best'; +if strcmp(rel_asi_name, 'best') + [~, order] = sort(rsq.v, 'descend'); + rel_el = order(1); +else + rel_el = find(strcmp(rsq.feat_names, rel_asi_name)); +end + +% make plot +figure('Position', [20,20,paper_size]) +subplot('Position', [0.20,0.17,0.78,0.80]) +plot(asi_data.pwv_a, asi_data.val(:,rel_el),'xb','LineWidth',2), hold on, +lsline +set(gca, 'FontSize', ftsize) +xlabel('Reference aortic PWV [m/s]', 'FontSize', ftsize) +if rel_el == 1 + ylabel(strrep(rel_asi_name, '_', ' '), 'FontSize', ftsize) +else + ylab = ylabel('ASI', 'FontSize', ftsize, 'Rotation', 0); + set(ylab, 'Units', 'Normalized', 'Position', [-0.15, 0.5, 0]); +end + +box off +%text(10,-0.9,{'All ages', ['R^2 = ' num2str(ranking(1),3)]}, 'Color', 'b','FontSize', ftsize) +text(10,-0.7,{'All ages', ['R^2 = ' num2str(rsq.v(rel_el),2)]}, 'Color', 'b','FontSize', ftsize) +PrintFigs(gcf, paper_size/70, [PATHS.CaseStudies, 'ASI_analysis_correlation_all_ages'], 0) +%text(6,-0.96,{'Aged 40-50', ['R^2 = ' num2str(rsq_age.v(order(1)),3)]}, 'Color', 'r','FontSize', ftsize) +rel_els = asi_data.i_age == 45; +plot(asi_data.pwv_a(rel_els), asi_data.val(rel_els,rel_el),'xr','LineWidth',2) +text(6,0,{'Aged 40-50', ['R^2 = ' num2str(rsq_age.v(rel_el, 3),1)]}, 'Color', 'r','FontSize', ftsize) +PrintFigs(gcf, paper_size/70, [PATHS.CaseStudies, 'ASI_analysis_correlation_single_age']) + + +end + +function PrintFigs(h, paper_size, savepath, close_plot) +set(h,'PaperUnits','inches'); +set(h,'PaperSize', [paper_size(1), paper_size(2)]); +set(h,'PaperPosition',[0 0 paper_size(1) paper_size(2)]); +set(gcf,'color','w'); +print(h,'-dpdf',savepath) +print(h,'-depsc',savepath) +%print(h,'-dpng',savepath) + +% if you want .eps illustrations, then do as follows: +up.eps_figs = 0; +if up.eps_figs + % you need to download 'export_fig' from: + % http://uk.mathworks.com/matlabcentral/fileexchange/23629-export-fig + export_fig_dir_path = 'C:\Documents\Google Drive\Work\Projects\PhD\Github\phd\Tools\Other Scripts\export_fig\altmany-export_fig-76bd7fa\'; + addpath(export_fig_dir_path) + export_fig(savepath, '-eps') +end + +if nargin > 3 && ~close_plot +else + close all; +end + +% save +fid = fopen([savepath, '.txt'], 'w'); +p = mfilename('fullpath'); +p = strrep(p, '\', '\\'); +fprintf(fid, ['Figures generated by:\n\n ' p '.m \n\n on ' datestr(today)]); +fclose all; + +end","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/create_input_files_for_a_simulation.m",".m","27736","642","function FileName = create_input_files_for_a_simulation(sim_settings, up) +% CREATE_INPUT_FILES_FOR_A_SIMULATION creates a set of Nektar1D input files +% for this particular virtual subject. +% +% create_input_files_for_a_simulation +% +% Inputs: (all passed from create_pwdb_input_files.m) +% - sim_settings: a structure of settings for this particular +% virtual subject. +% - up: a structure of parameters (mainly folder paths) used +% when creating the input files. +% +% Outputs: - input files for Nektar simulations: +% - filename.in: the main input file (containing details of vascular properties) +% - filename_IN_1.bcs: an additional input file (containing the input flow waveform) +% - filename.mat: a Matlab file containing details of the settings used to create these input files +% - shell script files to make it easier to run a batch of simulations +% +% Usage: This script is called by create_pwdb_input_files.m +% +% Accompanying Article: +% This code is provided to facilitate reproduction of the Pulse Wave +% Database described in: +% Charlton P.H. et al. Modelling arterial pulse waves in healthy +% ageing: in silico evaluation of haemodynamics and +% cardiovascular indices, ~~ under review ~~ +% DOI: ~~ tbc ~~ +% Further information on the pwdb Pulse Wave Database is provided in +% this article and at the project website: +% https://peterhcharlton.github.io/pwdb +% +% Author: Peter H. Charlton +% +% Licence: +% Permission is hereby granted, free of charge, to any person obtaining a copy +% of this software and associated documentation files (the ""Software""), to deal +% in the Software without restriction, including without limitation the rights +% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +% copies of the Software, and to permit persons to whom the Software is +% furnished to do so, subject to the following conditions: +% +% The above copyright notice and this permission notice shall be included in all +% copies or substantial portions of the Software. +% +% THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +% SOFTWARE. +% +% Copyright (C) 2019 King's College London +% +% v.1.0 Contributed to by: Marie Willemet, Jordi Alastruey, and Peter H. Charlton + +%% Setup parameters + +% setup paths +up = setup_up(sim_settings, up); + +% Setup Geometry, including +% - lengths +% - diameters +params.geo = setup_geo_params(sim_settings, up); + +% Setup Physical params, including +% - Eh +% - peripheral resistance +params.phys = setup_phys_params(sim_settings, up); + +% setup Nektar mesh +% (influenced by geometry) +params.mesh = setup_mesh(params, sim_settings, up); + +% Store Inflow Waveform +params.inflow = sim_settings.inflow; + +% Calculate Outflow +% (influenced by all sorts: PVR, lengths ...) +params.outlet = calc_outflow(params, sim_settings, up); + +%% Write Nektar input files +up = write_input_files(params, up, sim_settings); +create_inflow_file(params, up); + +%% Save workspace +sim_up = up; clear up +save([sim_up.paths.Matlab_computer_PathRoot, sim_up.paths.OutputFile_workspace]); + +%% output filename +FileName = sim_up.paths.OutputFile(1:end-3); + +end + +function up = setup_up(sim_settings, up) + +% prepare filename of output files + +% output files (.in and .bcs) +up.paths.OutputFile = [sim_settings.filename, '.in']; % Generated input file for Nektar +up.paths.OutputFile_inflow = [sim_settings.filename, '_IN_1.bcs']; % Generated inflow BC file for Nektar + +% other output files +up.paths.OutputFile_workspace = [sim_settings.filename, '.mat']; % Saved workspace variables + +end + +function geo_params = setup_geo_params(sim_settings, up) + +%% Setup geometry + +% - Extracting parameters from raw data +geo_params.node1 = sim_settings.network_spec.inlet_node; %Nodes at proximal ends - start at 1 to 56 +geo_params.node2 = sim_settings.network_spec.outlet_node; %Nodes at distal ends +geo_params.L = sim_settings.network_spec.length; %Segment length [m] +geo_params.Rad_prox = sim_settings.network_spec.inlet_radius; %Proximal radius [m] +geo_params.Rad_dist = sim_settings.network_spec.outlet_radius; %Distal radius [m] +geo_params.nbSeg = length(sim_settings.network_spec.length); %Number of arterial segments + +% - Specifying network connections +geo_params.GEO.E = geo_params.nbSeg; %Number of edges +geo_params.GEO.N = max([max(geo_params.node1) max(geo_params.node2)]); %Number of nodes +geo_params.GEO.NodesAtEdges = [geo_params.node1 geo_params.node2]; +geo_params.GEO = DefineGeometry(geo_params.GEO); + +end + +function phys_params = setup_phys_params(sim_settings, up) + +%% ==== Arterial wall properties + +% Empirical parameters for PWV from Mynard et al. 2015 +phys_params.wall.Eh_k1 = sim_settings.network_spec.k(1); %g/s^2/cm +phys_params.wall.Eh_k2 = sim_settings.network_spec.k(2); %cm^(-1) +phys_params.wall.Eh_k3 = sim_settings.network_spec.k(3); %g/s^2/cm + +% Empirical parameters for Gamma from Mynard et al. 2015 +phys_params.wall.Gamma_b0 = sim_settings.gamma_b0; % baseline: 400 g/s +phys_params.wall.Gamma_b1 = sim_settings.gamma_b1; % baseline: 100 g cm/s= + +%% ==== Fluid properties + +phys_params.fluid.mu = sim_settings.mu; % 3.5e-3; %Fluid Viscosity [Pa*s] +phys_params.fluid.density = sim_settings.rho; % usually 1060; %Fluid Density [kg/m3] +phys_params.fluid.alpha = sim_settings.alpha; % 1.1; %Velocity profile coef + +end + +function mesh_params = setup_mesh(params, sim_settings, up) + +mesh_params.p_orderV = sim_settings.fixed.p_order.*ones(params.geo.nbSeg,1); %Vector with polynomial orders +mesh_params.q_orderV = sim_settings.fixed.q_order.*ones(params.geo.nbSeg,1); %Vector with quadrature orders +mesh_params.nbElemBySeg = ceil(params.geo.L./sim_settings.fixed.elmt); %number of elements in each segment + +% If the length of the element is < 1cm, +% - group the two last elements of the domain (if there are more than 1 element in the domain) +% - or reduce the polynomial and quadrature order to 2 (if there is only one element in the domain) +displayed_red_order = 0; +% cycle through each element +for i=1:params.geo.nbSeg + + % identify distances of each element. NB: this elaborate scheme avoids the + % rounding errors sometimes produced by: temp = [[0:sim_settings.fixed.elmt:params.geo.L(i)],params.geo.L(i)]; + no_els = ceil(params.geo.L(i)/sim_settings.fixed.elmt); + no_complete_els = floor(params.geo.L(i)/sim_settings.fixed.elmt); + temp = 0; + for el_no = 1 : no_complete_els + temp = [temp, el_no*sim_settings.fixed.elmt]; + end + if no_els>no_complete_els + temp(end+1) = params.geo.L(i); + end + + %ensure you don't repeat the last point twice (if L=multiple of sim_settings.fixed.elmt) + if (temp(end) == temp(end-1)) + temp=temp(1:end-1); + end + + % calculate shortened length of the last element of this segment + shortL = temp(end)-temp(end-1); + + % if the length of this last element is less than a threshold value, then + if (shortL sim_settings.fixed.elmt_shortL_vw) && sim_settings.visco_elastic_log + fprintf(fileIn,'%d %s %d %s\n',params.mesh.nbElemBySeg(e),' nel domain ',e, 'Eh Area Gamma'); + elseif (params.geo.L(e)<=sim_settings.fixed.elmt_shortL_vw) || ~sim_settings.visco_elastic_log + fprintf(fileIn,'%d %s %d %s\n',params.mesh.nbElemBySeg(e),' nel domain ',e, 'Eh Area'); + else + error('\n Unrecognised wall type') + end + + % Print individual values for each element in this segment + x_temp = params.mesh.x_elem{e}; + % cycle through elements + for j=1:params.mesh.nbElemBySeg(e) + + % identify distances (x values) + l_start = x_temp(j); + l_end = x_temp(j+1); + + % print mesh settings + fprintf(fileIn,'%3.4f %3.4f %d %d %s\n', l_start, l_end, params.mesh.p_orderV(e), params.mesh.q_orderV(e), '# x_prox x_dist p q'); + + % print area + fprintf(fileIn,'%s %s %s %s\n','Area = PI*', Radius,'*',Radius); + + % print Eh + fprintf(fileIn,'%s %s\n','Eh = ', Eh); %If prescribed with x-varying Area and Eh + + % print gamma if this segment is visco-elastic + if (params.geo.L(e)>sim_settings.fixed.elmt_shortL_vw) && sim_settings.visco_elastic_log + fprintf(fileIn,'%s %s\n','Gamma = ', Gamma); %Visco-elastic coefficient + end + end +end + +%% Boundary Conditions + +% header +fprintf(fileIn,'%s\n','Boundary conditions'); + +% cycle through each segment (domain) +for i=1:params.geo.nbSeg + + %--- Inlet Boundary Conditions + + if i==1 + %- Domain 1 : Specify inlet as reflective flow + fprintf(fileIn,'%s \t%s\n','F 0',' # Domain 1'); %Frequency input (sum of harmonics in bcs file (F 0 or F 3)) + fprintf(fileIn,'%s\n','F 0'); + + else + %- all other domains: specify which segments they are connected to + + % properties of inlet + inNode = params.geo.node1(i); + deg = params.geo.GEO.degree(inNode); + inConnect = params.geo.GEO.EdgesByNode(inNode,:); + + % switch according to the type of junction at the inlet + switch deg + + case 1 %no connectivity at inlet + disp(['there is a problem at segment ',num2str(i)]); + return; + + case 2 %junction + ij = find(not(inConnect([1 2]) == i)); + fprintf(fileIn,'%s %d %d \t %s%d\n','J',inConnect(ij),inConnect(ij), ' # Domain ',i); + fprintf(fileIn,'%s %d %d\n','J',inConnect(ij),inConnect(ij)); + + case 3 %bifurcation + ib = find(not(inConnect == i)); % the segments which join to the current segment + % determine type of bifurcation + if (params.geo.GEO.BifType(inNode)<0) + BifType = 'B'; + else + BifType = 'C'; + end + fprintf(fileIn,'%s %d %d \t %s%d\n',BifType,inConnect(ib(1)),inConnect(ib(2)), ' # Domain ',i); + fprintf(fileIn,'%s %d %d\n',BifType,inConnect(ib(1)),inConnect(ib(2))); + end + end + + %--- Outlet Boundary Conditions + + % properties of outlet + outNode = params.geo.node2(i); + deg = params.geo.GEO.degree(outNode); + outConnect = params.geo.GEO.EdgesByNode(outNode,:); + + % switch according to the type of junction at the outlet + switch deg + + case 1 %outlet WK + % varies according to whether the terminal boundary conditions absorb reflections (purely reistance), or reflect (windkessel) + + % imaginary part + if strcmp(outlet_wk_type, 'W') + fprintf(fileIn,'%s %1.4e\n', outlet_wk_type, params.outlet.C_WK(i)); %WK Compliance + else + fprintf(fileIn,'%s %1.4e\n',outlet_wk_type, params.outlet.Z_WK(i)); % R = Z0 + end + + % real part + if (params.outlet.R1_FIXED == 1) + fprintf(fileIn,'%s %1.4e %1.4f\n','W',params.outlet.R_WK_tot(i), params.outlet.r_WK(i)); %WK Resistance - R1 value fixed + else + fprintf(fileIn,'%s %1.4e\n','W',params.outlet.R_WK_tot(i)); %WK Resistance - R1 = Z0 + end + + % resistance for absorbing terminal + if strcmp(outlet_wk_type, 'R') + fprintf(fileIn,'%s %1.4e\n','R',params.outlet.Z_WK(i)); % R = Z0 + end + + case 2 %junction + ij = find(not(outConnect([1 2]) == i)); + fprintf(fileIn,'%s %d %d\n','J',outConnect(ij),outConnect(ij)); + fprintf(fileIn,'%s %d %d\n','J',outConnect(ij),outConnect(ij)); + + case 3 %bifurcation + ib = find(not(outConnect == i)); % the segments which join to the current segment + % determine type of bifurcation + if (params.geo.GEO.BifType(outNode)<0) + BifType = 'B'; + else + BifType = 'C'; + end + fprintf(fileIn,'%s %d %d\n',BifType,outConnect(ib(1)),outConnect(ib(2))); + fprintf(fileIn,'%s %d %d\n',BifType,outConnect(ib(1)),outConnect(ib(2))); + end +end + +%% Initial conditions + +% header +fprintf(fileIn,'%s\n','Initial condition'); + +% cycle through each segment (domain) +for e=1:params.geo.nbSeg + + % Make string for radius + Radius = ['(',num2str(params.mesh.Rad_coef(e,1)),'*x+',num2str(params.mesh.Rad_coef(e,2)),')']; + + % Make string for Eh + Eh = [num2str(0.1),'*(',num2str(params.phys.wall.Eh_k1),'*exp(',num2str(params.phys.wall.Eh_k2),'*100*',Radius,') +',num2str(params.phys.wall.Eh_k3),')*',Radius]; + + % print initial area + %if strcmp(outlet_wk_type, 'W') + fprintf(fileIn,'%s %s %s %s %s %s %s %s %s %s %s\n','a = PI*',Radius,'*',Radius,'*(1-3/4*',Radius,'*',num2str(params.outlet.Pdiastolic),'/(',Eh,'))^2'); + %else + % fprintf(fileIn_cond,'%s\n','a = Ao'); + %end + + % print initial velocity + fprintf(fileIn,'%s\n','u = 0'); + +end + +%% History points + +% header +fprintf(fileIn,'%s\n','History Pts'); +fprintf(fileIn,'%d %s\n',length(sim_settings.fixed.artery_output),' #Number of Domains with history Points'); + +%- Outputs at inlet, middle and outlet of some segment +locs = cell(length(sim_settings.fixed.artery_output),1); +for seg_no_el = 1 : length(sim_settings.fixed.artery_output) + curr_seg_no = sim_settings.fixed.artery_output(seg_no_el); + temp = [0, params.geo.L(curr_seg_no)./2, params.geo.L(curr_seg_no)]; + % Add additional points every 2 cm along arterial segments in path from asc aorta to digital + if sum(sim_settings.fixed.Path_dig == curr_seg_no) ~= 0 ... + || sum(sim_settings.fixed.Path_ankle == curr_seg_no) ~= 0 ... + || sum(sim_settings.fixed.Path_brain == curr_seg_no) ~= 0 + temp = [temp, 0.04:0.04:params.geo.L(curr_seg_no)]; + end + % 3/4 of way along brachial arteries + if curr_seg_no == 7 || curr_seg_no == 21 + temp = [temp, 0.75*params.geo.L(curr_seg_no)]; + end + locs{seg_no_el} = unique(temp); clear temp +end + +% cycle through each segment at which to write output measurements +for seg_no_el=1:length(sim_settings.fixed.artery_output) + + % print to file + fprintf(fileIn,'%d %d\n',length(locs{seg_no_el}), sim_settings.fixed.artery_output(seg_no_el)); + format_spec = [repmat('%1.4f ', [1,length(locs{seg_no_el})-1]), '%1.4f\n']; + fprintf(fileIn,format_spec,locs{seg_no_el}); + +end + +fprintf(fileIn,'\n \n \n %s %s\n','oneDbio -a -R', up.paths.OutputFile); + +%% Close file +fclose(fileIn); + +end + +function [GEO] = DefineGeometry(GEO) +% GEO contains the variables +% GEO.N : number of nodes in network +% GEO.E : number of edges in network +% GEO.NodesAtEdges (E x 2): Start and end nodes for each edge + +% The function constructs the following geometry matrices: +% GEO.B (NxE) : Incidence matrix +% GEO.EdgesByNode (N x 3): All edges connected to each node +% GEO.degree (1xN) : Degree of each node +% GEO.BifType (1xN) : Type of bifurcation for each node + +%--- Incidence Matrix B +GEO.B = zeros(GEO.N, GEO.E); +GEO.BifType = zeros(GEO.N, 1); + +for (i = 1:GEO.E) + %start of node + GEO.B(GEO.NodesAtEdges(i,1),i) = -1; + %end of node + GEO.B(GEO.NodesAtEdges(i,2),i) = 1; +end + + +%-- EdgesByNodes & degree of nodes +GEO.EdgesByNode(1:GEO.N,1:3) = 0; + +for i=1:GEO.N + % Get the degree of node i + GEO.degree(i) = sum(abs(GEO.B(i,:))); + if (GEO.degree(i)==3) + GEO.BifType(i) = sum(GEO.B(i,:)); + end + % Get the edges connected to the internal node i + clear e Y; + s=1; + for j=1:GEO.E + if abs(GEO.B(i,j))>0 + e(s)=j; + s=s+1; + end + end + GEO.EdgesByNode(i,:) = [e zeros(1,4-s)]; +end + +end","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/export_pwdb.m",".m","103371","1994","function export_pwdb(pwdb_no) +% EXPORT_PWDB exports the pulse wave database in several formats for +% further research. +% +% export_pwdb +% +% Inputs: the 'collated_data.mat', 'haemodynamic_params.mat', +% 'pulse_wave_vels.mat', 'pulse_wave_inds.mat' and +% 'system_chars' files produced by +% 'extract_pwdb_simulation_data.m' and 'pwdb_pwa.m'. +% +% Outputs: - A range of files containing the database in various +% formats, stored in the 'exported_data' folder (within +% the 'processed_data' folder): +% - Matlab format (both a single file and multiple, smaller, files) +% - CSV format +% - WFDB (waveform database) format, as used in PhysioNet databases +% +% Accompanying Article: +% This code is provided to facilitate reproduction of the Pulse Wave +% Database described in: +% Charlton P.H. et al. Modelling arterial pulse waves in healthy +% ageing: in silico evaluation of haemodynamics and +% pulse wave indices, ~~ under review ~~ +% DOI: ~~ tbc ~~ +% Further information on the pwdb Pulse Wave Database is provided in +% this article and at the project website: +% https://peterhcharlton.github.io/pwdb +% +% Author: Peter H. Charlton +% +% Licence: +% Permission is hereby granted, free of charge, to any person obtaining a copy +% of this software and associated documentation files (the ""Software""), to deal +% in the Software without restriction, including without limitation the rights +% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +% copies of the Software, and to permit persons to whom the Software is +% furnished to do so, subject to the following conditions: +% +% The above copyright notice and this permission notice shall be included in all +% copies or substantial portions of the Software. +% +% THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +% SOFTWARE. +% +% Copyright (C) 2019 King's College London +% +% v.1.0 Contributed to by: Marie Willemet, Jordi Alastruey, and Peter H. Charlton + +fprintf('\n --- Exporting PWDB in different formats ---') + +% Setup paths with current simulation paths +PATHS = setup_paths_for_post_processing(pwdb_no); + +% create folders in which to store exported data +create_folders(PATHS) + +% load collated data +load(PATHS.collated_data) + +% Create files containing PWs +create_pw_files(PATHS, collated_data); + +% Create files containing model configs +create_model_config_file(PATHS, collated_data); + +% Create files containing model variations +create_model_variation_file(PATHS, collated_data); + +% Create files containing haemodynamic params +create_haemod_param_file(PATHS); + +% Create files containing model geometry +create_model_geometry_files(PATHS, collated_data); + +% Create file containing pulse onset times +create_pulse_onsets_file(PATHS, collated_data); + +% Create files containing pulse wave indices +pw_inds = create_pw_ind_file(PATHS, collated_data); + +% Creat Matlab file containing all data +create_mat_file_w_all_data(PATHS, collated_data, pw_inds); + +fprintf('\n --- Finished exporting PWDB ---') + +end + +function create_folders(PATHS) + +folders_to_make = {PATHS.exported_data, PATHS.exported_data_mat, PATHS.exported_data_csv, PATHS.exported_data_wfdb, PATHS.exported_data_geo}; +for s = 1 : length(folders_to_make) + if ~exist(folders_to_make{s}, 'dir') + mkdir(folders_to_make{s}) + end +end + +end + +function create_pw_files(PATHS, collated_data) + +fprintf('\n - Creating Pulse Wave Files') +%% Setting up + +% settings +sites = {'AorticRoot', 'ThorAorta', 'AbdAorta', 'IliacBif', 'Carotid', 'SupTemporal', 'SupMidCerebral', 'Brachial', 'Radial', 'Digital', 'CommonIliac', 'Femoral', 'AntTibial'}; +site_domain_no = [1, 18, 39, 41, 15, 87, 72, 21, 22, 112, 44, 46, 49]; +site_dist_prop = [0, 1, 0, 1, 0.5, 1, 1, 0.75, 1, 1, 0.5, 0.5, 1]; +signals = {'P', 'U', 'A', 'PPG'}; % omit 'Q' as it's U.*A + +% identify domains which are available +domains = extractfield(collated_data(1).output_data, 'domain_no'); +[~,rel_els,~] = intersect(site_domain_no, domains); +site_domain_no = site_domain_no(rel_els); +sites = sites(rel_els); +site_dist_prop = site_dist_prop(rel_els); + +%% Creating pulse wave files (WFDB) +% - WFDB: one PW file per subject +fprintf(': WFDB') +up.dataset_name = PATHS.pwdb_filename_prefix; +fs = collated_data(1).output_data(1).fs; + +cd(PATHS.exported_data_wfdb) +% cycle through each subject +no_subjs = length(collated_data); +file_names = cell(no_subjs,1); +for subj_no = 1 : no_subjs + sig_names = cell(0); + + % setup command + file_names{subj_no} = [up.dataset_name, sprintf('%.4d', subj_no)]; + + % Extract signals data + data_mat = nan(2000, 1000); max_no_samps = 0; no_cols = 0; + for site_no = 1 : length(sites) + + curr_site = sites{site_no}; + + % Identify site-specific info + curr_domain_no = site_domain_no(site_no); + curr_domain_el = find(domains == curr_domain_no); + curr_site_dist_prop = site_dist_prop(site_no); + + % Identify the relevant data for this simulation at this site + rel_wave_data = collated_data(subj_no).output_data(curr_domain_el); + seg_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(curr_domain_no); + dists = extractfield(rel_wave_data, 'distances'); + [~,rel_dist_el] = min(abs(curr_site_dist_prop*seg_length-dists)); clear dists + + % Extract each signal at this site + for signal_no = 1 : length(signals) + if strcmp(signals{signal_no}, 'P') + factor = 133.33; + else + factor = 1; + end + curr_sig = signals{signal_no}; + eval(['curr_sig_data = rel_wave_data.' curr_sig '(:,rel_dist_el)/factor;']) + sig_names{end+1} = [curr_site '_' curr_sig]; + data_mat(1:length(curr_sig_data),no_cols+1) = curr_sig_data; + max_no_samps = max(max_no_samps, length(curr_sig_data)); + no_cols = no_cols+1; + clear factor curr_sig curr_sig_data + end + clear signal_no rel_wave_data seg_length rel_dist_el curr_domain_no curr_domain_el curr_site_dist_prop curr_site + + end + clear site_no + + % Get rid of excess NaNs in data_mat + data_mat = data_mat(:,1:no_cols); clear no_cols + data_mat = data_mat(1:max_no_samps,:); clear max_no_samps + +% % Get rid of last sample if this was a nan in some recordings +% if sum(isnan(data_mat(end,:))) > 0 +% data_mat = data_mat(1:end-1,:); +% end +% if sum(sum(isnan(data_mat))) +% error('There are still some nans') +% end + + % Create signals file + descrip = [': ' num2str(collated_data(subj_no).input_data.sim_settings.age) ' : male']; + units = ''; + for sig_no = 1 : length(sig_names) + signal_names(sig_no,1) = {[sig_names{sig_no} ', ' ]}; + if ~isempty(strfind(sig_names{sig_no}, '_PPG')) + rel_unit = 'au'; + elseif ~isempty(strfind(sig_names{sig_no}, '_P')) + rel_unit = 'mmHg'; + elseif ~isempty(strfind(sig_names{sig_no}, '_A')) + rel_unit = 'm2'; + elseif ~isempty(strfind(sig_names{sig_no}, '_Q')) + rel_unit = 'm3_per_sec'; + elseif ~isempty(strfind(sig_names{sig_no}, '_U')) + rel_unit = 'm_per_s'; + end + units = [units, rel_unit, '/']; clear rel_unit + end + clear sig_no + units = units(1:end-1); + % convert this subject's data into WFDB format + mat2wfdb(data_mat, file_names{subj_no}, fs, [], units, descrip, [], signal_names); + clear data_mat units descrip signal_names sig_names type subtype + +end +clear no_subjs subj_no fs + +% create a RECORDS file +file_name = 'RECORDS'; +file_path = [PATHS.exported_data_wfdb, file_name]; +fid = fopen(file_path, 'w'); +formatSpec = '%s\r\n'; +for line_no = 1 : length(file_names) + fprintf(fid, formatSpec, file_names{line_no}); +end + +% create a DBS file +file_name = 'DBS'; +file_path = [PATHS.exported_data_wfdb, file_name]; +fid = fopen(file_path, 'w'); +fprintf(fid, [up.dataset_name, '\t', 'Preliminary Pulse Wave DataBase Dataset']); + +fclose all; + + +%% Creating pulse wave files (CSV and Mat) +% - Mat and CSV format: one PW file per site +fprintf(', CSV and Mat') + +% Cycle through each arterial site +for site_no = 1 : length(sites) + + % Identify site-specific info + curr_domain_no = site_domain_no(site_no); + curr_domain_el = find(domains == curr_domain_no); + curr_site_dist_prop = site_dist_prop(site_no); + + %% Extract PWs at this site from all the simulations + + % Cycle through each simulation + for sim_no = 1 : length(collated_data) + + % Identify the relevant data for this simulation at this site + rel_wave_data = collated_data(sim_no).output_data(curr_domain_el); + seg_length = collated_data(sim_no).input_data.sim_settings.network_spec.length(curr_domain_no); + dists = extractfield(rel_wave_data, 'distances'); + [~,rel_dist_el] = min(abs(curr_site_dist_prop*seg_length-dists)); clear dists + + % Extract each signal + for signal_no = 1 : length(signals) + if strcmp(signals{signal_no}, 'P') + factor = 133.33; + else + factor = 1; + end + curr_sig = signals{signal_no}; + + % store signal + eval(['PWs.' curr_sig '{sim_no} = rel_wave_data.' curr_sig '(:,rel_dist_el)/factor;']) + + % calculate pulse onset time + rel_row = find(domains == 1); + aortic_root_onset = collated_data(sim_no).output_data(rel_row).start_sample(1); + if strcmp(curr_sig, 'PPG') + temp_onset_time = (rel_wave_data.PPG_start_sample(rel_dist_el)-aortic_root_onset)/rel_wave_data.fs; + else + temp_onset_time = (rel_wave_data.start_sample(rel_dist_el)-aortic_root_onset)/rel_wave_data.fs; + end + % if the time is negative then add on the duration of a cardiac cycle + if temp_onset_time < 0 + cardiac_cycle_duration = length(rel_wave_data.P(:,1))/rel_wave_data.fs; + temp_onset_time = temp_onset_time + cardiac_cycle_duration; + end + eval(['PWs.onset_times.' curr_sig '(sim_no,1) = temp_onset_time;']); clear temp_onset_time + + clear factor curr_sig + end + clear signal_no rel_wave_data seg_length rel_dist_el + end + clear sim_no curr_site_dist_prop + + %% Store PWs for this site for all simulations (CSV and Mat) + + % Create filename for this site + filename = ['PWs_' sites{site_no}]; + + % Store as CSV and MAT + file_types = {'csv','mat'}; + sig_names = fieldnames(PWs); + sig_names = sig_names(~strcmp(sig_names, 'onset_times')); + sig_names = sig_names(~strcmp(sig_names, 'fs')); + sig_names = sig_names(~strcmp(sig_names, 'units')); + for type_no = 1 : length(file_types) + curr_type = file_types{type_no}; + eval(['filepath = [PATHS.exported_data_' curr_type ', filename, ''.'', curr_type];']); + switch curr_type + case 'csv' + + % Create CSV file for each signal + for sig_no = 1 : length(sig_names) + curr_sig = sig_names{sig_no}; + curr_filepath = [filepath(1:end-4), '_', curr_sig, filepath(end-3:end)]; + + % Extract data + max_no_samps = max(cellfun(@length, PWs.P)); + data_mat = nan(length(PWs.P),max_no_samps); + for subj_no = 1 : length(PWs.P) + eval(['data_mat(subj_no,1:length(PWs.P{subj_no})) = PWs.' curr_sig '{subj_no};']); + end + clear subj_no max_no_samps + + % Add in subject numbers + temp = 1 :length(collated_data); + data_mat = [temp(:), data_mat]; clear temp + + % Generate header line + header_line = 'Subject Number, '; + for col_no = 1 : (size(data_mat,2)-1) + curr_col = ['pt' num2str(col_no)]; + header_line = [header_line, curr_col, ', ']; + end + clear col_no curr_col + header_line = header_line(1:end-2); + + % Write header line to file + fid = fopen(curr_filepath,'w'); + up.csv.new_line = '\n'; + fprintf(fid,[header_line, up.csv.new_line]); clear header_line + fclose(fid); clear fid + + % Write to CSV + dlmwrite(curr_filepath, data_mat, '-append'); + clear data_mat curr_filepath curr_sig header_line curr_col col_no + + end + clear sig_no curr_sig + + case 'mat' + + % Save to Mat file + PWs.fs = collated_data(1).output_data(1).fs; + PWs.units.P = 'mmHg'; + PWs.units.U = 'm/s'; + PWs.units.A = 'm3'; + PWs.units.PPG = 'au'; + save(filepath, 'PWs'); + end + clear curr_type + end + clear type_no + +end +clear site_no curr_domain_el curr_domain_no + +end + +function sig_header = find_sig_header(curr_sig) + +switch curr_sig + case 'P' + sig_header = 'Pressure [mmHg]'; + case 'Q' + sig_header = 'Flow rate [m3/s]'; + case 'U' + sig_header = 'Flow velocity [m/s]'; + case 'A' + sig_header = 'Luminal area [m2]'; + case 'PPG' + sig_header = 'Photoplethysmogram [unitless]'; +end +end + +function pw_inds = create_pw_ind_file(PATHS, collated_data) + +fprintf('\n - Creating pulse wave indices file: ') + +% Load data +load(PATHS.pulse_wave_inds) + +% setup +sites = {'AorticRoot', 'ThorAorta', 'AbdAorta', 'IliacBif', 'Carotid', 'SupTemporal', 'SupMidCerebral', 'Brachial', 'Radial', 'Digital', 'CommonIliac', 'Femoral', 'AntTibial'}; +site_domain_no = [1, 18, 39, 41, 15, 87, 72, 21, 22, 112, 44, 46, 49]; +site_dist_prop = [0, 1, 0, 1, 0.5, 1, 1, 0.75, 1, 1, 0.5, 0.5, 1]; +site_central_log = [1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 0, 0]; +domain_nos = extractfield(collated_data(1).output_data, 'domain_no'); + +% identify domains which are available +domains = extractfield(collated_data(1).output_data, 'domain_no'); +[~,rel_els,~] = intersect(site_domain_no, domains); +site_domain_no = site_domain_no(rel_els); +sites = sites(rel_els); +site_dist_prop = site_dist_prop(rel_els); +site_central_log = site_central_log(rel_els); + +% Identify parameters, and extract data +params_at_each_site = {'SBP', 'DBP', 'MBP', 'PP', 'Qmax', 'Qmin', 'Qmean', 'Qtotal', 'Umax', 'Umin', 'Umean', 'Amax', 'Amin', 'Amean', 'P1in', 'P2in', 'P1pk', 'P2pk', 'Psys', 'Pms', 'PPGa', 'PPGb', 'PPGc', 'PPGd', 'PPGe', 'PPGsys', 'PPGdia', 'PPGdic', 'PPGms', 'AI', 'AP', 'RI', 'SI', 'AGI_mod', 'PTT','VP1in','VP2in','VP1pk','VP2pk','UP1in','UP2in','UP1pk','UP2pk'}; +params = {'subj_no', 'age'}; +for site_no = 1 : length(sites) + fprintf([sites{site_no}, ' ']); + domain_el = find(domain_nos == site_domain_no(site_no)); + % cycle through each parameter + for site_param_no = 1 : length(params_at_each_site) + % skip if these params are only to be calculated for aortic root + if ~strcmp(sites{site_no}, 'AorticRoot') + if sum(strcmp(params_at_each_site{site_param_no}, {'VP1in','VP2in','VP1pk','VP2pk','UP1in','UP2in','UP1pk','UP2pk'})) + continue + end + end + % skip if this is the PPG at a non-peripheral site + if site_central_log(site_no) == 1 + if length(params_at_each_site{site_param_no})>2 && strcmp(params_at_each_site{site_param_no}(1:3), 'PPG') + continue + end + if strcmp(params_at_each_site{site_param_no}(1:2), 'RI') || ... + strcmp(params_at_each_site{site_param_no}(1:2), 'SI') || ... + (length(params_at_each_site{site_param_no})>6 && strcmp(params_at_each_site{site_param_no}, 'AGI_mod')) + continue + end + end + + % note down this parameter's name + params{end+1} = [sites{site_no}, '_', params_at_each_site{site_param_no}, '_V']; + params{end+1} = [sites{site_no}, '_', params_at_each_site{site_param_no}, '_T']; + % extract data for it + for subj_no = 1 : length(collated_data) + param_data(subj_no, 1) = subj_no; + param_data(subj_no, 2) = collated_data(subj_no).input_data.sim_settings.age; + switch params_at_each_site{site_param_no} + case 'SBP' + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + wav = collated_data(subj_no).output_data(domain_el).P(:,rel_dist_el); + [~,el] = max(wav); + v = wav(el)/133.33; + t = (el-1)/collated_data(subj_no).output_data(domain_el).fs; + case 'DBP' + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + wav = collated_data(subj_no).output_data(domain_el).P(:,rel_dist_el); + v = min(wav)/133.33; + t = -1; + case 'MBP' + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + wav = collated_data(subj_no).output_data(domain_el).P(:,rel_dist_el); + v = mean(wav)/133.33; + t = -1; + case 'PP' + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + wav = collated_data(subj_no).output_data(domain_el).P(:,rel_dist_el); + v = (max(wav)-min(wav))/133.33; + t = -1; + case 'Qmax' + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + wav = collated_data(subj_no).output_data(domain_el).U(:,rel_dist_el).*collated_data(subj_no).output_data(domain_el).A(:,rel_dist_el); + [~,el] = max(wav); + v = wav(el); + t = (el-1)/collated_data(subj_no).output_data(domain_el).fs; + case 'Qmin' + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + wav = collated_data(subj_no).output_data(domain_el).U(:,rel_dist_el).*collated_data(subj_no).output_data(domain_el).A(:,rel_dist_el); + [~,el] = min(wav); + v = wav(el); + t = (el-1)/collated_data(subj_no).output_data(domain_el).fs; + case 'Qmean' + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + wav = collated_data(subj_no).output_data(domain_el).U(:,rel_dist_el).*collated_data(subj_no).output_data(domain_el).A(:,rel_dist_el); + v = mean(wav); + t = -1; + case 'Qtotal' + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + wav = collated_data(subj_no).output_data(domain_el).U(:,rel_dist_el).*collated_data(subj_no).output_data(domain_el).A(:,rel_dist_el); + v = sum(wav)/collated_data(subj_no).output_data(domain_el).fs; + t = -1; + case 'Umax' + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + wav = collated_data(subj_no).output_data(domain_el).U(:,rel_dist_el); + [~,el] = max(wav); + v = wav(el); + t = (el-1)/collated_data(subj_no).output_data(domain_el).fs; + case 'Umin' + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + wav = collated_data(subj_no).output_data(domain_el).U(:,rel_dist_el); + [~,el] = min(wav); + v = wav(el); + t = (el-1)/collated_data(subj_no).output_data(domain_el).fs; + case 'Umean' + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + wav = collated_data(subj_no).output_data(domain_el).U(:,rel_dist_el); + v = mean(wav); + t = -1; + case 'Amax' + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + wav = collated_data(subj_no).output_data(domain_el).A(:,rel_dist_el); + [~,el] = max(wav); + v = wav(el); + t = (el-1)/collated_data(subj_no).output_data(domain_el).fs; + case 'Amin' + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + wav = collated_data(subj_no).output_data(domain_el).A(:,rel_dist_el); + [~,el] = min(wav); + v = wav(el); + t = -1; + case 'Amean' + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + wav = collated_data(subj_no).output_data(domain_el).A(:,rel_dist_el); + v = mean(wav); + t = -1; + case 'VP1in' + % find Q waveform + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + wav = collated_data(subj_no).output_data(domain_el).A(:,rel_dist_el).*collated_data(subj_no).output_data(domain_el).U(:,rel_dist_el); + % find P1in point + pwa_pt = 'p1in'; pwa_sig = 'P'; + t = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + samp_no = (t*collated_data(subj_no).output_data(domain_el).fs)+1; + % find volume ejected up to P1 + try v = sum(wav(1:samp_no)); catch, v = nan; end + t = -1; + case 'VP2in' + % find Q waveform + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + wav = collated_data(subj_no).output_data(domain_el).A(:,rel_dist_el).*collated_data(subj_no).output_data(domain_el).U(:,rel_dist_el); + % find P2in point + pwa_pt = 'p2in'; pwa_sig = 'P'; + t = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + samp_no = (t*collated_data(subj_no).output_data(domain_el).fs)+1; + % find volume ejected up to P1 + try v = sum(wav(1:samp_no)); catch, v = nan; end + t = -1; + case 'VP1pk' + % find Q waveform + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + wav = collated_data(subj_no).output_data(domain_el).A(:,rel_dist_el).*collated_data(subj_no).output_data(domain_el).U(:,rel_dist_el); + % find P1pk point + pwa_pt = 'p1pk'; pwa_sig = 'P'; + t = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + samp_no = (t*collated_data(subj_no).output_data(domain_el).fs)+1; + % find volume ejected up to P1 + try v = sum(wav(1:samp_no)); catch, v = nan; end + t = -1; + case 'VP2pk' + % find Q waveform + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + wav = collated_data(subj_no).output_data(domain_el).A(:,rel_dist_el).*collated_data(subj_no).output_data(domain_el).U(:,rel_dist_el); + % find P2pk point + pwa_pt = 'p2pk'; pwa_sig = 'P'; + t = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + samp_no = (t*collated_data(subj_no).output_data(domain_el).fs)+1; + % find volume ejected up to P1 + try v = sum(wav(1:samp_no)); catch, v = nan; end + t = -1; + case 'UP1in' + % find U waveform + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + wav = collated_data(subj_no).output_data(domain_el).U(:,rel_dist_el); + % find P1in point + pwa_pt = 'p1in'; pwa_sig = 'P'; + t = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + samp_no = (t*collated_data(subj_no).output_data(domain_el).fs)+1; + % find U at this point + try, v = wav(samp_no); catch v = nan; end + t = -1; + case 'UP2in' + % find U waveform + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + wav = collated_data(subj_no).output_data(domain_el).U(:,rel_dist_el); + % find P2in point + pwa_pt = 'p2in'; pwa_sig = 'P'; + t = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + samp_no = (t*collated_data(subj_no).output_data(domain_el).fs)+1; + % find U at this point + try, v = wav(samp_no); catch v = nan; end + t = -1; + case 'UP1pk' + % find U waveform + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + wav = collated_data(subj_no).output_data(domain_el).U(:,rel_dist_el); + % find P1pk point + pwa_pt = 'p1pk'; pwa_sig = 'P'; + t = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + samp_no = (t*collated_data(subj_no).output_data(domain_el).fs)+1; + % find U at this point + try, v = wav(samp_no); catch v = nan; end + t = -1; + case 'UP2pk' + % find U waveform + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + wav = collated_data(subj_no).output_data(domain_el).U(:,rel_dist_el); + % find P2pk point + pwa_pt = 'p2pk'; pwa_sig = 'P'; + t = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + samp_no = (t*collated_data(subj_no).output_data(domain_el).fs)+1; + % find U at this point + try, v = wav(samp_no); catch v = nan; end + t = -1; + case 'P1in' + pwa_pt = 'p1in'; pwa_sig = 'P'; + t = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + v = find_pw_point_value(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + case 'P2in' + pwa_pt = 'p2in'; pwa_sig = 'P'; + t = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + v = find_pw_point_value(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + case 'P1pk' + pwa_pt = 'p1pk'; pwa_sig = 'P'; + t = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + v = find_pw_point_value(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + case 'P2pk' + pwa_pt = 'p2pk'; pwa_sig = 'P'; + t = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + v = find_pw_point_value(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + case 'Psys' + pwa_pt = 's'; pwa_sig = 'P'; + t = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + v = find_pw_point_value(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + case 'Pms' + pwa_pt = 'ms'; pwa_sig = 'P'; + t = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + rel_cv_ind = 'ms'; + rel_row = find(strcmp(pulse_wave_inds(1).cv_ind_names, rel_cv_ind)); + eval(['v = pulse_wave_inds(subj_no).' pwa_sig '_pwa(domain_el).cv_inds(rel_row,rel_dist_el);']) + v = v/133.33; + case 'PPGms' + pwa_pt = 'ms'; pwa_sig = 'PPG'; + t = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + rel_cv_ind = 'ms'; + rel_row = find(strcmp(pulse_wave_inds(1).cv_ind_names, rel_cv_ind)); + eval(['v = pulse_wave_inds(subj_no).' pwa_sig '_pwa(domain_el).cv_inds(rel_row,rel_dist_el);']) + case 'Pdic' + pwa_pt = 'dic'; pwa_sig = 'P'; + t = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + v = find_pw_point_value(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + case 'PPGa' + pwa_pt = 'a'; pwa_sig = 'PPG'; + t = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + rel_cv_ind = 'a_div_amp'; + rel_row = find(strcmp(pulse_wave_inds(1).cv_ind_names, rel_cv_ind)); + eval(['v = pulse_wave_inds(subj_no).' pwa_sig '_pwa(domain_el).cv_inds(rel_row,rel_dist_el);']) + case 'PPGb' + pwa_pt = 'b'; pwa_sig = 'PPG'; + t = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + rel_cv_ind = 'b_div_amp'; + rel_row = find(strcmp(pulse_wave_inds(1).cv_ind_names, rel_cv_ind)); + eval(['v = pulse_wave_inds(subj_no).' pwa_sig '_pwa(domain_el).cv_inds(rel_row,rel_dist_el);']) + case 'PPGc' + pwa_pt = 'c'; pwa_sig = 'PPG'; + t = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + rel_cv_ind = 'c_div_amp'; + rel_row = find(strcmp(pulse_wave_inds(1).cv_ind_names, rel_cv_ind)); + eval(['v = pulse_wave_inds(subj_no).' pwa_sig '_pwa(domain_el).cv_inds(rel_row,rel_dist_el);']) + case 'PPGd' + pwa_pt = 'd'; pwa_sig = 'PPG'; + t = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + rel_cv_ind = 'd_div_amp'; + rel_row = find(strcmp(pulse_wave_inds(1).cv_ind_names, rel_cv_ind)); + eval(['v = pulse_wave_inds(subj_no).' pwa_sig '_pwa(domain_el).cv_inds(rel_row,rel_dist_el);']) + case 'PPGe' + pwa_pt = 'e'; pwa_sig = 'PPG'; + t = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + rel_cv_ind = 'e_div_amp'; + rel_row = find(strcmp(pulse_wave_inds(1).cv_ind_names, rel_cv_ind)); + eval(['v = pulse_wave_inds(subj_no).' pwa_sig '_pwa(domain_el).cv_inds(rel_row,rel_dist_el);']) + case 'PPGsys' + pwa_pt = 's'; pwa_sig = 'PPG'; + t = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + v = find_pw_point_value(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + case 'PPGdic' + pwa_pt = 'dic'; pwa_sig = 'PPG'; + t = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + v = find_pw_point_value(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + case 'PPGdia' + pwa_pt = 'dia'; pwa_sig = 'PPG'; + t = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + v = find_pw_point_value(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig); + case 'AI' + pwa_sig = 'P'; + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + rel_cv_ind = 'AI'; + rel_row = find(strcmp(pulse_wave_inds(1).cv_ind_names, rel_cv_ind)); + eval(['v = pulse_wave_inds(subj_no).' pwa_sig '_pwa(domain_el).cv_inds(rel_row,rel_dist_el);']) + t = -1; + case 'AP' + pwa_sig = 'P'; + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + rel_cv_ind = 'AP'; + rel_row = find(strcmp(pulse_wave_inds(1).cv_ind_names, rel_cv_ind)); + eval(['v = pulse_wave_inds(subj_no).' pwa_sig '_pwa(domain_el).cv_inds(rel_row,rel_dist_el);']) + v = v/133.33; + t = -1; + case 'RI' + pwa_sig = 'PPG'; + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + rel_cv_ind = 'RI'; + rel_row = find(strcmp(pulse_wave_inds(1).cv_ind_names, rel_cv_ind)); + eval(['v = pulse_wave_inds(subj_no).' pwa_sig '_pwa(domain_el).cv_inds(rel_row,rel_dist_el);']) + t = -1; + case 'SI' + pwa_sig = 'PPG'; + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + rel_cv_ind = 'SI'; + rel_row = find(strcmp(pulse_wave_inds(1).cv_ind_names, rel_cv_ind)); + eval(['v = pulse_wave_inds(subj_no).' pwa_sig '_pwa(domain_el).cv_inds(rel_row,rel_dist_el);']) + t = -1; + case 'AGI_mod' + pwa_sig = 'PPG'; + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + rel_cv_ind = 'AGI_mod'; + rel_row = find(strcmp(pulse_wave_inds(1).cv_ind_names, rel_cv_ind)); + eval(['v = pulse_wave_inds(subj_no).' pwa_sig '_pwa(domain_el).cv_inds(rel_row,rel_dist_el);']) + t = -1; + case 'PTT' + desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); + [~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + arrival_v = collated_data(subj_no).output_data(domain_el).start_sample(rel_dist_el); + start_v = collated_data(subj_no).output_data(1).start_sample(1); + v = (arrival_v - start_v)/collated_data(subj_no).output_data(1).fs; + t = -1; + end + + % store value + param_data(subj_no,size(params,2)-1) = v; + if t~=-1 + param_data(subj_no,size(params,2)) = t; + elseif subj_no == length(collated_data) + params = params(1:end-1); + params{end} = params{end}(1:end-2); + end + clear v pwa_sig desired_length rel_dist_el arrival_v start_v v t rel_cv_ind rel_row wav el + + end + end +end + +% Make header line +header_line = 'Subject Number, Age, '; +for param_no = 3 : length(params) + curr_param = params{param_no}; + % Make Header + header_line = [header_line, curr_param, ', ']; +end +clear param_no curr_param label units abbr graph_title +header_line = header_line(1:end-2); + +% Write header line to file +curr_filename = [PATHS.exported_data, PATHS.pwdb_filename_prefix, '_pw_indices.csv']; +fid = fopen(curr_filename,'w'); +up.csv.new_line = '\n'; +fprintf(fid,[header_line, up.csv.new_line]); clear header_line +fclose(fid); clear fid + +% Write parameter data to file +dlmwrite(curr_filename, param_data, '-append'); + +% Output results (to save in single Matlab file +pw_inds = array2table(param_data, 'VariableNames',params); + +end + +function create_model_config_file(PATHS, collated_data) + +fprintf('\n - Creating model configurations file') + +% Setup +params.vars = {'subject_ID', 'base', 'base_age'}; +params.sim_settings = {'age', 'hr', 'sv', 't_pf', 'reg_vol', 'dbp', 'mbp', 'mu', 'alpha', 'p_drop', 'pvc', 'p_out', 'rho', 'lvet', 'pvr', 'gamma_b0', 'gamma_b1'}; +params.network_spec = {'k1', 'k2', 'k3'}; +params.all = [params.vars, params.sim_settings, params.network_spec]; + +% Check names of gamma variables (this is required for the ppwdb) +if ~sum(strcmp(fieldnames(collated_data(1).input_data.sim_settings), 'gamma_b0')) + do_alternative_gamma = true; +else + do_alternative_gamma = false; +end + +% identify baseline simulation for baseline age and for each age +[base, base_age] = deal(false(length(collated_data),1)); +baseline_age = 25; +for sim_no = 1 : length(collated_data) + if sum(abs(collated_data(sim_no).input_data.sim_settings.variations.params)) == 0 + base_age(sim_no) = true; + if collated_data(sim_no).input_data.sim_settings.age == baseline_age + base(sim_no) = true; + end + end +end +subject_ID = 1:length(collated_data); + +param_data = nan(length(collated_data),length(params.all)); + +for subj_no = 1 : length(collated_data) + + param_no_counter = 0; + + % Insert data for each parameter stored as a variable + for param_no = 1 : length(params.vars) + param_no_counter = param_no_counter+1; + + curr_param_name = params.vars{param_no}; + + eval(['curr_param_val = ' curr_param_name '(subj_no);']) + + param_data(subj_no,param_no_counter) = curr_param_val; + end + + % Extract this subject's input data + rel_input_data = collated_data(subj_no).input_data; + + % Extract data for each parameter in ""sim_settings"" + for param_no = 1 : length(params.sim_settings) + param_no_counter = param_no_counter+1; + + curr_param_name = params.sim_settings{param_no}; + + % load gamma from a different location + if do_alternative_gamma & length(curr_param_name)>5 & strcmp(curr_param_name(1:5), 'gamma') + curr_param_name = strrep(curr_param_name, 'g', 'G'); + eval(['curr_param_val = rel_input_data.sim_settings.fixed.wall.' curr_param_name ';']) + else % for all other parameters + eval(['curr_param_val = rel_input_data.sim_settings.' curr_param_name ';']) + end + + param_data(subj_no,param_no_counter) = curr_param_val; clear curr_param_val + end + + % Extract data for each parameter in ""network_spec"" + for param_no = 1 : length(params.network_spec) + curr_param_name = params.network_spec{param_no}; + switch curr_param_name + case 'k1' + curr_param_val = rel_input_data.sim_settings.network_spec.k(1); + case 'k2' + curr_param_val = rel_input_data.sim_settings.network_spec.k(2); + case 'k3' + curr_param_val = rel_input_data.sim_settings.network_spec.k(3); + end + param_no_counter = param_no_counter+1; + param_data(subj_no,param_no_counter) = curr_param_val; + end + clear param_no_counter param_no curr_param_name +end + +% Change units of some variables +% - Pa to mmHg +rel_param_no = find(strcmp(params.all, 'dbp')); +param_data(:,rel_param_no) = param_data(:,rel_param_no)/133.33; +rel_param_no = find(strcmp(params.all, 'p_out')); +param_data(:,rel_param_no) = param_data(:,rel_param_no)/133.33; + +% Change names of some variables +rel_param_no = find(strcmp(params.all, 't_pf')); +params.all{rel_param_no} = 'pft'; +rel_param_no = find(strcmp(params.all, 'reg_vol')); +params.all{rel_param_no} = 'rfv'; +rel_param_no = find(strcmp(params.all, 'gamma_b0')); +params.all{rel_param_no} = 'b0'; +rel_param_no = find(strcmp(params.all, 'gamma_b1')); +params.all{rel_param_no} = 'b1'; +rel_param_no = find(strcmp(params.all, 'rho')); +params.all{rel_param_no} = 'density'; +rel_param_no = find(strcmp(params.all, 'mu')); +params.all{rel_param_no} = 'viscosity'; + +% Make header line +header_line = 'Subject Number, '; +for param_no = 2 : length(params.all) + curr_param = params.all{param_no}; + if length(curr_param)>=4 && strcmp(curr_param(1:4), 'base') + header_line = [header_line, curr_param, ', ']; + else + [label, units, abbr, graph_title] = make_param_label(curr_param); + header_line = [header_line, curr_param, ' [' units, '], ']; + end +end +clear param_no curr_param label units abbr graph_title +header_line = header_line(1:end-2); + +% Write header line to file +curr_filename = PATHS.exported_data_model_configs; +fid = fopen(curr_filename,'w'); +up.csv.new_line = '\n'; +fprintf(fid,[header_line, up.csv.new_line]); clear header_line +fclose(fid); clear fid + +% Write parameter data to file +dlmwrite(curr_filename, param_data, '-append'); +clear param_data curr_filename + +end + +function create_pulse_onsets_file(PATHS, collated_data) + +fprintf('\n - Creating Onsets File') +%% Setting up + +% settings +sites = {'AorticRoot', 'ThorAorta', 'AbdAorta', 'IliacBif', 'Carotid', 'SupTemporal', 'SupMidCerebral', 'Brachial', 'Radial', 'Digital', 'CommonIliac', 'Femoral', 'AntTibial'}; +site_domain_no = [1, 18, 39, 41, 15, 87, 72, 21, 22, 112, 44, 46, 49]; +site_dist_prop = [0, 1, 0, 1, 0.5, 1, 1, 0.75, 1, 1, 0.5, 0.5, 1]; +signals = {'P', 'U', 'A', 'PPG'}; % omit 'Q' as it's U.*A + +% identify domains which are available +domains = extractfield(collated_data(1).output_data, 'domain_no'); +[~,rel_els,~] = intersect(site_domain_no, domains); +site_domain_no = site_domain_no(rel_els); +sites = sites(rel_els); +site_dist_prop = site_dist_prop(rel_els); + +%% Creating pulse onsets file (CSV) +up.dataset_name = PATHS.pwdb_filename_prefix; +fs = collated_data(1).output_data(1).fs; + +% Cycle through each arterial site +for site_no = 1 : length(sites) + + % Identify site-specific info + curr_site = sites{site_no}; + curr_domain_no = site_domain_no(site_no); + curr_domain_el = find(domains == curr_domain_no); + curr_site_dist_prop = site_dist_prop(site_no); + + %% Extract PWs at this site from all the simulations + + % Cycle through each simulation + for sim_no = 1 : length(collated_data) + + % Identify the relevant data for this simulation at this site + rel_wave_data = collated_data(sim_no).output_data(curr_domain_el); + seg_length = collated_data(sim_no).input_data.sim_settings.network_spec.length(curr_domain_no); + dists = extractfield(rel_wave_data, 'distances'); + [~,rel_dist_el] = min(abs(curr_site_dist_prop*seg_length-dists)); clear dists + + % Extract each signal + for signal_no = 1 : length(signals) + curr_sig = signals{signal_no}; + + % calculate pulse onset time + rel_row = find(domains == 1); + aortic_root_onset = collated_data(sim_no).output_data(rel_row).start_sample(1); + if strcmp(curr_sig, 'PPG') + temp_onset_time = (rel_wave_data.PPG_start_sample(rel_dist_el)-aortic_root_onset)/rel_wave_data.fs; + else + temp_onset_time = (rel_wave_data.start_sample(rel_dist_el)-aortic_root_onset)/rel_wave_data.fs; + end + % if the time is negative then add on the duration of a cardiac cycle + if temp_onset_time < 0 + cardiac_cycle_duration = length(rel_wave_data.P(:,1))/rel_wave_data.fs; + temp_onset_time = temp_onset_time + cardiac_cycle_duration; + end + eval(['onset_times.' curr_site '_' curr_sig '(sim_no,1) = temp_onset_time;']); + clear temp_onset_time aortic_root_onset curr_sig + end + clear signal_no rel_wave_data seg_length rel_dist_el + end + clear sim_no curr_site_dist_pro + + + +end +clear site_no curr_domain_el curr_domain_no + +% Make header line and extract data +col_names = fieldnames(onset_times); +header_line = 'Subject Number, '; +data_mat = nan(length(collated_data),length(col_names)+1); +data_mat(:,1) = 1:length(collated_data); +for col_no = 1 : length(col_names) + curr_col = col_names{col_no}; + header_line = [header_line, curr_col, ', ']; + eval(['data_mat(:,col_no+1) = onset_times.' curr_col ';']); +end +clear col_no curr_col +header_line = header_line(1:end-2); + +% Write header line to file +curr_filename = PATHS.exported_data_onset_times; +fid = fopen(curr_filename,'w'); +up.csv.new_line = '\n'; +fprintf(fid,[header_line, up.csv.new_line]); clear header_line +fclose(fid); clear fid + +% Write parameter data to file +dlmwrite(curr_filename, data_mat, '-append'); +clear param_data curr_filename + +end + +function create_model_geometry_files(PATHS, collated_data) + +fprintf('\n - Creating model geometry files: ') + +% Setup +params.vars = {'subject_ID'}; +params.a = 1; +params.sim_settings = {'age', 'hr', 'sv', 't_pf', 'reg_vol', 'dbp', 'mbp', 'mu', 'alpha', 'p_drop', 'pvc', 'p_out', 'rho', 'lvet', 'pvr'}; +params.network_spec = {'seg_no', 'inlet_node', 'outlet_node', 'length', 'inlet_radius', 'outlet_radius', 'c', 'r_sum'}; +params.all = [params.network_spec]; + +% Load data +load(PATHS.peripheral_boundarys) + +subject_ID = 1:length(collated_data); + +% cycle through each virtual subject +for sim_no = 1 : length(collated_data) + + if rem(sim_no,10) == 0 + fprintf([num2str(sim_no), ', ']) + end + + % Insert data for each parameter for each segment + param_no_counter = 0; + param_data = nan(length(collated_data(1).input_data.sim_settings.network_spec.seg_no),length(params.all)); + for param_no = 1 : length(params.network_spec) + param_no_counter = param_no_counter+1; + curr_param_name = params.network_spec{param_no}; + if ~strcmp(curr_param_name, 'c') && ~strcmp(curr_param_name, 'r_sum') + eval(['curr_param_val = collated_data(sim_no).input_data.sim_settings.network_spec.' curr_param_name ';']) + else + % For windkessel boundary characteristics + eval(['curr_param_val = peripheral_chars.' curr_param_name '(sim_no,:);']) + curr_param_val(isnan(curr_param_val)) = 0; + end + param_data(:,param_no_counter) = curr_param_val; clear curr_param_val + end + clear param_no_counter param_no curr_param_name + + % Make header line + header_line = ''; + for param_no = 1 : length(params.all) + curr_param = params.all{param_no}; + curr_param = strrep(curr_param, 'c', 'peripheral_c'); + curr_param = strrep(curr_param, 'r_sum', 'peripheral_r'); + % Make Header + header_line = [header_line, curr_param, ', ']; + end + clear param_no curr_param + header_line = header_line(1:end-2); + + % Write header line to file + curr_filename = [PATHS.exported_data_geo, PATHS.pwdb_filename_prefix, '_geo_' sprintf('%.4d', sim_no) '.csv']; + fid = fopen(curr_filename,'w'); + up.csv.new_line = '\n'; + fprintf(fid,[header_line, up.csv.new_line]); clear header_line + fclose(fid); clear fid + + % Write parameter data to file + dlmwrite(curr_filename, param_data, '-append'); + clear param_data curr_filename + +end + +end + +function create_model_variation_file(PATHS, collated_data) + +fprintf('\n - Creating model variations file') + +% Setup +params = collated_data(1).input_data.sim_settings.variations.param_names; +variations = nan(length(collated_data),length(params)); +for subj_no = 1 : length(collated_data) + variations(subj_no, :) = collated_data(subj_no).input_data.sim_settings.variations.params; + ages(subj_no,1) = collated_data(subj_no).input_data.sim_settings.age; +end +rel_params = sum(abs(variations))>0; +params = params(rel_params); +variations = variations(:,rel_params); clear rel_params subj_no + +subjs = 1:length(collated_data); subjs = subjs(:); +data_mat = [subjs, ages, variations]; clear variations ages subjs + +% Make header line +header_line = 'Subject Number, Age, '; +for param_no = 1 : length(params) + curr_param = params{param_no}; + % Make Header + header_line = [header_line, curr_param, ', ']; +end +clear param_no curr_param params +header_line = header_line(1:end-2); + +% Rename some variables +header_line = strrep(header_line, 'reg_vol', 'RFV'); +header_line = strrep(header_line, 't_pf', 'PFT'); +header_line = upper(header_line); + +% Write header line to file +curr_filename = [PATHS.exported_data, PATHS.pwdb_filename_prefix, '_model_variations.csv']; +fid = fopen(curr_filename,'w'); +up.csv.new_line = '\n'; +fprintf(fid,[header_line, up.csv.new_line]); clear header_line +fclose(fid); clear fid + +% Write parameter data to file +dlmwrite(curr_filename, data_mat, '-append'); +clear param_data curr_filename + +end + +function v = find_pw_point_time(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig) + +% identify distance along segment +desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); +[~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + +% identify the sample corresponding to this fiducial point +rel_row = find(strcmp(pulse_wave_inds(1).fid_pt_names, pwa_pt)); +eval(['rel_el = pulse_wave_inds(subj_no).' pwa_sig '_pwa(domain_el).fid_pts(rel_row,rel_dist_el);']) + +% calculate the time of this fiducial point +fs = collated_data(subj_no).output_data.fs; +v = (rel_el-1)/fs; + +end + +function v = find_pw_point_value(collated_data, pulse_wave_inds, subj_no, site_domain_no, site_no, site_dist_prop, domain_el, pwa_pt, pwa_sig) + +% identify distance along segment +desired_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(site_domain_no(site_no))*site_dist_prop(site_no); +[~, rel_dist_el] = min(abs(collated_data(subj_no).output_data(domain_el).distances-desired_length)); + +% identify the sample corresponding to this fiducial point +rel_row = find(strcmp(pulse_wave_inds(1).fid_pt_names, pwa_pt)); +eval(['rel_el = pulse_wave_inds(subj_no).' pwa_sig '_pwa(domain_el).fid_pts(rel_row,rel_dist_el);']) + +% Extract the value of the signal at this point +if ~isnan(rel_el) + switch pwa_sig + case 'PPG' + v = collated_data(subj_no).output_data(domain_el).PPG(rel_el,rel_dist_el); + case 'P' + v = collated_data(subj_no).output_data(domain_el).P(rel_el,rel_dist_el)/133.33; + end +else + v = nan; +end + +end + +function create_haemod_param_file(PATHS) + +fprintf('\n - Creating haemodynamic parameters file') + +% Load data +load(PATHS.haemodynamic_params) + +% setup +params = {'subj_no', 'age', 'HR', 'SV', 'CO', 'LVET', 'dPdt', 'PFT', 'RFV', 'SBP_a', 'DBP_a', 'MBP_a', 'PP_a', 'SBP_b', 'DBP_b', 'MBP_b', 'PP_b', 'PP_amp', 'AP', 'AIx', 'Tr', 'PWV_a', 'PWV_cf', 'PWV_br', 'PWV_fa', 'dia_asc_a', 'dia_desc_thor_a', 'dia_abd_a', 'dia_car', 'len_prox_a', 'MBP_drop_finger', 'MBP_drop_ankle', 'svr'}; + +% Make header line +header_line = 'Subject Number, '; +for param_no = 2 : length(params) + curr_param = params{param_no}; + [label, units, abbr, graph_title] = make_param_label(curr_param); + abbr = strrep(abbr, '{', ''); + abbr = strrep(abbr, '}', ''); + header_line = [header_line, abbr, ' [' units, '], ']; +end +clear param_no curr_param label units abbr graph_title +header_line = header_line(1:end-2); + +% Write header line to file +curr_filename = [PATHS.exported_data, PATHS.pwdb_filename_prefix, '_haemod_params.csv']; +fid = fopen(curr_filename,'w'); +up.csv.new_line = '\n'; +fprintf(fid,[header_line, up.csv.new_line]); clear header_line +fclose(fid); clear fid + +% Extract parameter data +params_mat = 1:length(haemodynamic_params); params_mat = params_mat(:); +for param_no = 2 : length(params) + curr_param = params{param_no}; + curr_param = strrep(curr_param, 'AP', 'AP_a'); + curr_param = strrep(curr_param, 'AIx', 'AI_a'); + curr_param = strrep(curr_param, 'Tr', 'Tr_a'); + eval(['params_mat(:,end+1) = extractfield(haemodynamic_params, ''' curr_param ''');']) +end + +% Write parameter data to file +dlmwrite(curr_filename, params_mat, '-append'); clear params_mat curr_filename + +end + +function data = assess_phys_plausibility(data) + +%% Extract data required to assess physiological plausibility + +p_data = proc_data(data); + +%% Assess physiological plausibility + +% Compare simulated PW characteristics to literature ones +[implaus_sims, all_implaus_sims, res] = compare_simulated_vs_literature(p_data); + +%% Store results +data.plausibility.implaus_sims = implaus_sims; +data.plausibility.all_implaus_sims = all_implaus_sims; +data.plausibility.plausibility_log = false(length(p_data.age),1); +data.plausibility.plausibility_log(setxor(1:length(p_data.age), all_implaus_sims.els)) = true; + +end + +function p_data = proc_data(data) +% Extract pulse wave indices +p_data.SBP_a = data.pw_inds.AorticRoot_SBP_V; +p_data.PP_a = data.pw_inds.AorticRoot_PP; +p_data.SBP_b = data.pw_inds.Brachial_SBP_V; +p_data.PP_b = data.pw_inds.Brachial_PP; +p_data.DBP_b = data.pw_inds.Brachial_DBP; +p_data.MBP_b = data.pw_inds.Brachial_MBP; + +% Extract haemodynamic parameters +p_data.PP_amp = extractfield(data.haemods, 'PP_amp'); +p_data.Tr_a = extractfield(data.haemods, 'Tr_a'); +p_data.AI_a = extractfield(data.haemods, 'AI_a'); +p_data.AI_c = extractfield(data.haemods, 'AI_c'); +p_data.AP_a = extractfield(data.haemods, 'AP_a'); +p_data.AP_c = extractfield(data.haemods, 'AP_c'); +p_data.HR = extractfield(data.haemods, 'HR'); +p_data.SV = extractfield(data.haemods, 'SV'); +p_data.CO = extractfield(data.haemods, 'CO'); +p_data.LVET = extractfield(data.haemods, 'LVET'); +p_data.PWV = extractfield(data.haemods, 'PWV_a'); +p_data.DIA = extractfield(data.haemods, 'dia_asc_a'); +if sum(strcmp(fieldnames(data.haemods), 'c')) + p_data.C = extractfield(data.haemods, 'c'); +end + +% Extract configuration +p_data.age = data.config.age; +p_data.variations = data.config.variations; +end + +function [implaus_sims, all_implaus_sims, res] = compare_simulated_vs_literature(p_data) + +fprintf('\n - Compare simulated vs literature characteristics') + +% Simulated characteristics +params = {'AP_a', 'SBP_b', 'DBP_b', 'PP_b', 'MBP_b', 'SBP_a', 'PP_a', 'PP_amp', 'AI_a', 'Tr_a'}; +params = {'SBP_b', 'DBP_b', 'PP_b', 'MBP_b', 'SBP_a', 'PP_a', 'PP_amp'}; + +%% Extract literature values of each characteristic +req_ages = unique(p_data.age(:)); +all_implaus_sims.els = []; +all_implaus_sims.params = zeros(length(p_data.age),length(params)); +for param_no = 1 : length(params) + + curr_param = params{param_no}; + + % Extract literature values of this parameter + literature_data.age = 15:10:85; + switch curr_param + case 'SBP_b' % taken from McEniery2005 (male data, Table 1) + literature_data.male.mean = [123, 124, 123, 125, 125, 126, 127, 130]; + literature_data.male.sd = [10,10,9,9,9,9,9,8]; + literature_data.male.n = [172,178,183,258,429,430,280,39]; + literature_data.female.mean = [113,115,115,118,122,126,127,128]; + literature_data.female.sd = [10,10,12,11,11,10,10,10]; + literature_data.female.n = [133,101,165,301,495,509,290,38]; + case 'DBP_b' % taken from McEniery2005 (male data, Table 1) + literature_data.male.mean = [73,75,77,79,79,78,76,75]; + literature_data.male.sd = [8,10,9,9,9,9,9,8]; + literature_data.male.n = [172,178,183,258,429,430,280,39]; + literature_data.female.mean = [72,73,74,75,75,74,72,70]; + literature_data.female.sd = [8,8,9,8,7,7,8,9]; + literature_data.female.n = [133,101,165,301,495,509,290,38]; + case 'PP_b' % taken from McEniery2005 (male data, Table 1) + literature_data.male.mean = [50,49,47,46,46,49,51,55]; + literature_data.male.sd = [9,9,8,7,8,8,8,9]; + literature_data.male.n = [172,178,183,258,429,430,280,39]; + literature_data.female.mean = [41,43,41,43,46,51,54,57]; + literature_data.female.sd = [8,7,9,9,9,8,9,11]; + literature_data.female.n = [133,101,165,301,495,509,290,38]; + case 'MBP_b' % taken from McEniery2005 (male data, Table 1) + literature_data.male.mean = [88,89,92,95,95,94,93,92]; + literature_data.male.sd = [8,8,8,7,7,7,7,8]; + literature_data.male.n = [172,178,183,258,429,430,280,39]; + literature_data.female.mean = [86,86,88,90,93,93,92,90]; + literature_data.female.sd = [8,8,9,9,8,8,8,8]; + literature_data.female.n = [133,101,165,301,495,509,290,38]; + case 'SBP_a' % taken from McEniery2005 (male data, Table 1) + literature_data.male.mean = [103,105,109,113,115,117,118,120]; + literature_data.male.sd = [8,8,9,9,9,9,9,8]; + literature_data.male.n = [172,178,183,258,429,430,280,39]; + literature_data.female.mean = [98,101,105,109,115,118,119,120]; + literature_data.female.sd = [9,9,11,11,11,10,9,11]; + literature_data.female.n = [133,101,165,301,495,509,290,38]; + case 'PP_a' % taken from McEniery2005 (male data, Table 1) + literature_data.male.mean = [29,30,31,34,35,39,42,45]; + literature_data.male.sd = [5,6,6,6,7,7,7,9]; + literature_data.male.n = [172,178,183,258,429,430,280,39]; + literature_data.female.mean = [25,27,30,33,38,43,56,49]; + literature_data.female.sd = [6,7,8,8,8,8,8,12]; + literature_data.female.n = [133,101,165,301,495,509,290,38]; + case 'PP_amp' % taken from McEniery2005 (male data, Table 1) + literature_data.male.mean = [1.72, 1.7 , 1.50, 1.39, 1.33, 1.26, 1.24, 1.25]; + literature_data.male.sd = [0.11, 0.14, 0.18, 0.15, 0.16, 0.13, 0.12, 0.15]; + literature_data.male.n = [172,178,183,258,429,430,280,39]; + literature_data.female.mean = [1.67,1.59,1.41,1.29,1.22,1.21,1.19,1.18]; + literature_data.female.sd = [0.15,0.2,0.18,0.15,0.11,0.10,0.10,0.11]; + literature_data.female.n = [133,101,165,301,495,509,290,38]; + case 'AP_a' % taken from McEniery2005 (male data, Table 1) + literature_data.male.mean = [-1,1,4,7,9,11,13,14]; + literature_data.male.sd = [3,4,5,4,5,5,5,5]; + literature_data.male.n = [172,178,183,258,429,430,280,39]; + literature_data.female.mean = [1,3,6,10,13,15,16,18]; + literature_data.female.sd = [3,4,5,5,5,5,5,7]; + literature_data.female.n = [133,101,165,301,495,509,290,38]; + case 'AI_a' % taken from McEniery2005 (male data, Table 1) + literature_data.male.mean = [-2,2,12,19,24,28,30,30]; + literature_data.male.sd = [8,11,13,10,10,9,9,10]; + literature_data.male.n = [172,178,183,258,429,430,280,39]; + literature_data.female.mean = [5,9,20,28,33,34,35,37]; + literature_data.female.sd = [10,14,12,10,9,9,9,10]; + literature_data.female.n = [133,101,165,301,495,509,290,38]; + case 'Tr' % taken from McEniery2005 (male data, Table 1) + literature_data.male.mean = [150,154,151,148,143,141,136,133]; + literature_data.male.sd = [17,21,21,16,15,12,12,16]; + literature_data.male.n = [172,178,183,258,429,430,280,39]; + literature_data.female.mean = [145,143,140,136,133,131,129,125]; + literature_data.female.sd = [16,13,16,14,15,14,12,12]; + literature_data.female.n = [133,101,165,301,495,509,290,38]; + end + + [literature_data.overall_mean, literature_data.overall_sd] = calc_overall_stats(literature_data); + + interp_literature_data.mean = interp1(literature_data.age, literature_data.overall_mean, req_ages); + interp_literature_data.sd = interp1(literature_data.age, literature_data.overall_sd, req_ages); + interp_literature_data.age = req_ages; + + % store literature values + eval(['literature.' curr_param ' = interp_literature_data;']); + + % Extract simulated values + simulated_data.age = unique(p_data.age(:)'); + param_implaus_els_high = []; + param_implaus_els_low = []; + + for age_no = 1 : length(interp_literature_data.age) + curr_age = p_data.age(age_no); + + % 99% ranges + rel_lit_el = find(interp_literature_data.age == curr_age); + max_val = interp_literature_data.mean(rel_lit_el)+ 2.575*interp_literature_data.sd(rel_lit_el); + min_val = interp_literature_data.mean(rel_lit_el)- 2.575*interp_literature_data.sd(rel_lit_el); + clear rel_lit_el + + % Relevant simulated values + rel_els = find(p_data.age == curr_age); + eval(['param_data = p_data.' curr_param ';']); + rel_vals = param_data(rel_els); clear param_data curr_age + + % simulations outside plausible range + if ~exist('implaus_sims', 'var') || ~sum(strcmp(fieldnames(implaus_sims), curr_param)) + eval(['implaus_sims.' curr_param '.low_els = [];']); + eval(['implaus_sims.' curr_param '.low_vars = [];']); + eval(['implaus_sims.' curr_param '.high_els = [];']); + eval(['implaus_sims.' curr_param '.high_vars = [];']); + end + + % simulations in which the value of this parameter is lower than expected + curr_implaus_els = rel_els(rel_vals < min_val); + eval(['implaus_sims.' curr_param '.low_els = [implaus_sims.' curr_param '.low_els; curr_implaus_els];']); + curr_implaus_vars = p_data.variations.params(curr_implaus_els, [1:3,7:9]); + eval(['implaus_sims.' curr_param '.low_vars = [implaus_sims.' curr_param '.low_vars; curr_implaus_vars];']); + param_implaus_els_low = [param_implaus_els_low; curr_implaus_els]; + all_implaus_sims.params(curr_implaus_els,param_no) = -1; + + % simulations in which the value of this parameter is higher than expected + curr_implaus_els = rel_els(rel_vals > max_val); + eval(['implaus_sims.' curr_param '.high_els = [implaus_sims.' curr_param '.high_els; curr_implaus_els];']); + curr_implaus_vars = p_data.variations.params(curr_implaus_els, [1:3,7:9]); + eval(['implaus_sims.' curr_param '.high_vars = [implaus_sims.' curr_param '.high_vars; curr_implaus_vars];']); + param_implaus_els_high = [param_implaus_els_high; curr_implaus_els]; + all_implaus_sims.params(curr_implaus_els,param_no) = 1; + + clear rel_vals max_val min_val curr_implaus_els curr_age rel_els + end + fprintf(['\n ' curr_param ': ' num2str(length(param_implaus_els_low)) ' implausibly low; ']); + fprintf([num2str(length(param_implaus_els_high)) ' implausibly high.']); + all_implaus_sims.els = [all_implaus_sims.els; param_implaus_els_low; param_implaus_els_high]; + + clear age_no + + clear literature_data interp_literature_data +end +implaus_sims.var_names = p_data.variations.param_names([1:3,7:9]); + +all_implaus_sims.els = unique(all_implaus_sims.els); +all_implaus_sims.vars = p_data.variations.params(all_implaus_sims.els, [1:3,7:9]); +all_implaus_sims.var_names = p_data.variations.param_names([1:3,7:9]); +all_implaus_sims.age = p_data.age(all_implaus_sims.els); +all_implaus_sims.params = all_implaus_sims.params(all_implaus_sims.els,:); + +%% Calculate Results + +% Summary of implausible subjects +res.no_implaus_sims = length(all_implaus_sims.els); +res.no_implaus_sims_due_to_PP = sum(sum(abs(all_implaus_sims.params(:,[3,6])),2)~=0); +high_PP_els = sum(all_implaus_sims.params(:,[3,6]),2)>0; +res.no_implaus_sims_due_to_PP_high = sum(high_PP_els); +low_PP_els = sum(all_implaus_sims.params(:,[3,6]),2)<0; +res.no_implaus_sims_due_to_PP_low = sum(low_PP_els); +rel_els = sum(abs(all_implaus_sims.params(:,[3,6])),2)~=0; +other_els = logical(1-rel_els); +high_PPamp_els = sum(all_implaus_sims.params(other_els,[7]),2)>0; +res.no_implaus_sims_due_to_high_PP_amp = sum(high_PPamp_els); +res.prop_implaus_25 = mean(all_implaus_sims.age==25); +res.prop_implaus_75 = mean(all_implaus_sims.age==75); +rel_col = strcmp(implaus_sims.var_names, 'pwv'); +res.prop_implaus_high_PWV = mean(all_implaus_sims.vars(:,rel_col)>0); +res.prop_implaus_low_PWV = mean(all_implaus_sims.vars(:,rel_col)<0); + +do_check = 0; +if do_check + % High PP + rel_data = all_implaus_sims.vars(high_PP_els,:); n = 1; subplot(3,2,n), histogram(rel_data(:,n)), xlabel(implaus_sims.var_names(n)); n=2; subplot(3,2,n), histogram(rel_data(:,n)), xlabel(implaus_sims.var_names(n)); n=3; subplot(3,2,n), histogram(rel_data(:,n)), xlabel(implaus_sims.var_names(n)); n=4; subplot(3,2,n), histogram(rel_data(:,n)), xlabel(implaus_sims.var_names(n)); n=5; subplot(3,2,n), histogram(rel_data(:,n)), xlabel(implaus_sims.var_names(n)); n=6; subplot(3,2,n), histogram(rel_data(:,n)), xlabel(implaus_sims.var_names(n)); + % Low PP + rel_data = all_implaus_sims.vars(low_PP_els,:); n = 1; subplot(3,2,n), histogram(rel_data(:,n)), xlabel(implaus_sims.var_names(n)); n=2; subplot(3,2,n), histogram(rel_data(:,n)), xlabel(implaus_sims.var_names(n)); n=3; subplot(3,2,n), histogram(rel_data(:,n)), xlabel(implaus_sims.var_names(n)); n=4; subplot(3,2,n), histogram(rel_data(:,n)), xlabel(implaus_sims.var_names(n)); n=5; subplot(3,2,n), histogram(rel_data(:,n)), xlabel(implaus_sims.var_names(n)); n=6; subplot(3,2,n), histogram(rel_data(:,n)), xlabel(implaus_sims.var_names(n)); + % Normal PP and High PPamp + rel_col = strcmp(params, 'PP_amp'); + temp_els = sum(all_implaus_sims.params(:,[3,6]),2)==0 & all_implaus_sims.params(:,rel_col) == 1; + rel_data = all_implaus_sims.vars(temp_els,:); n = 1; subplot(3,2,n), histogram(rel_data(:,n)), xlabel(implaus_sims.var_names(n)); n=2; subplot(3,2,n), histogram(rel_data(:,n)), xlabel(implaus_sims.var_names(n)); n=3; subplot(3,2,n), histogram(rel_data(:,n)), xlabel(implaus_sims.var_names(n)); n=4; subplot(3,2,n), histogram(rel_data(:,n)), xlabel(implaus_sims.var_names(n)); n=5; subplot(3,2,n), histogram(rel_data(:,n)), xlabel(implaus_sims.var_names(n)); n=6; subplot(3,2,n), histogram(rel_data(:,n)), xlabel(implaus_sims.var_names(n)); + % Normal PP, High PPamp and low PWV + rel_ppamp_col = strcmp(params, 'PP_amp'); + rel_pwv_col = strcmp(implaus_sims.var_names, 'pwv'); + temp_els = sum(all_implaus_sims.params(:,[3,6]),2)==0 & all_implaus_sims.params(:,rel_ppamp_col) == 1 & all_implaus_sims.vars(:,rel_pwv_col) == -1; + rel_data = all_implaus_sims.vars(temp_els,:); n = 1; subplot(3,2,n), histogram(rel_data(:,n)), xlabel(implaus_sims.var_names(n)); n=2; subplot(3,2,n), histogram(rel_data(:,n)), xlabel(implaus_sims.var_names(n)); n=3; subplot(3,2,n), histogram(rel_data(:,n)), xlabel(implaus_sims.var_names(n)); n=4; subplot(3,2,n), histogram(rel_data(:,n)), xlabel(implaus_sims.var_names(n)); n=5; subplot(3,2,n), histogram(rel_data(:,n)), xlabel(implaus_sims.var_names(n)); n=6; subplot(3,2,n), histogram(rel_data(:,n)), xlabel(implaus_sims.var_names(n)); +end + +end + +function [overall_mean, overall_sd] = calc_overall_stats(literature_data) + +for age_no = 1 : length(literature_data.age) + + % From https://www.statstodo.com/CombineMeansSDs_Pgm.php + + curr_data = literature_data.female; + sum_x_f = curr_data.mean(age_no)*curr_data.n(age_no); + sum_xsq_f = (curr_data.sd(age_no)^2)*(curr_data.n(age_no)-1)+(sum_x_f^2/curr_data.n(age_no)); + curr_data = literature_data.male; + sum_x_m = curr_data.mean(age_no)*curr_data.n(age_no); + sum_xsq_m = (curr_data.sd(age_no)^2)*(curr_data.n(age_no)-1)+(sum_x_m^2/curr_data.n(age_no)); + tn = literature_data.male.n(age_no) + literature_data.female.n(age_no); + tx = sum_x_f + sum_x_m; + txx = sum_xsq_m + sum_xsq_f; + overall_mean(age_no) = tx/tn; + overall_sd(age_no) = sqrt((txx-(tx^2)/tn)/(tn-1)); + + clear curr_data sum_x_f sum_xsq_f sum_x_m sum_xsq_m tn tx txx + +end + + +end + +function create_mat_file_w_all_data(PATHS, collated_data, pw_inds) + +fprintf('\n - Collating data in single Matlab file') + +% Load peripheral Windkessel boundary conditions +load(PATHS.peripheral_boundarys) + +% Load haemodynamic parameters +load(PATHS.haemodynamic_params) + +% Load system characteristics +if exist(PATHS.system_chars, 'file') + load(PATHS.system_chars) +end + +% settings +sites = {'AorticRoot', 'ThorAorta', 'AbdAorta', 'IliacBif', 'Carotid', 'SupTemporal', 'SupMidCerebral', 'Brachial', 'Radial', 'Digital', 'CommonIliac', 'Femoral', 'AntTibial'}; +site_domain_no = [1, 18, 39, 41, 15, 87, 72, 21, 22, 112, 44, 46, 49]; +site_dist_prop = [0, 1, 0, 1, 0.5, 1, 1, 0.75, 1, 1, 0.5, 0.5, 1]; +signals = {'P', 'U', 'A', 'PPG'}; + +% identify domains which are available +domains = extractfield(collated_data(1).output_data, 'domain_no'); +[~,rel_els,~] = intersect(site_domain_no, domains); +site_domain_no = site_domain_no(rel_els); +sites = sites(rel_els); +site_dist_prop = site_dist_prop(rel_els); + +% Check names of gamma variables (this is required for the ppwdb) +if ~sum(strcmp(fieldnames(collated_data(1).input_data.sim_settings), 'gamma_b0')) + do_alternative_gamma = true; +else + do_alternative_gamma = false; +end + +% waves along arterial paths +do_path = 1; +if do_path == 1 + % choose arterial paths + if ~do_alternative_gamma + path_names = {'aorta_finger', 'aorta_foot', 'aorta_brain', 'aorta_r_subclavian'}; + else + path_names = {'aorta_finger', 'aorta_foot'}; + end + for s = 1 : length(path_names) + arterial_paths(s).name = path_names{s}; + end + clear path_names s + + % add segment data for each path + for path_name_no = 1 : length(arterial_paths) + curr_path_name = arterial_paths(path_name_no).name; + switch curr_path_name + case 'aorta_finger' + arterial_paths(path_name_no).seg_names = {'asc_aorta', 'aortic_arch1', 'aortic_arch2','subclavian','brachial','radial','palmar','digital'}; + arterial_paths(path_name_no).doms = [1,2,14,19,21,22,108,112]; + case 'aorta_foot' + arterial_paths(path_name_no).seg_names = {'asc_aorta', 'aortic_arch1', 'aortic_arch2','desc_thor_aorta1','desc_thor_aorta2','abd_aorta1','abd_aorta2','abd_aorta3','abd_aorta4','abd_aorta5','common_iliac','external_iliac','femoral','ant_tibial'}; + arterial_paths(path_name_no).doms = [1,2,14,18,27,28,35,37,39,41,42,44,46,49]; + case 'aorta_brain' + arterial_paths(path_name_no).seg_names = {'asc_aorta', 'aortic_arch1', 'carotid','int_carotid1','int_carotid2','int_carotid_dist1','int_carotid_dist2','mid_cerebral','sup_mid_cerebral'}; + arterial_paths(path_name_no).doms = [1,2,15,16,79,65,96,71,72]; + case 'aorta_r_subclavian' + arterial_paths(path_name_no).seg_names = {'asc_aorta', 'brachiocephalic', 'subclavian'}; + arterial_paths(path_name_no).doms = [1,3,4]; + end + end +end + +data.config.baseline_sim_for_all = false(length(collated_data),1); +data.config.baseline_sim_for_age = false(length(collated_data),1); + +% Cycle through each simulation +for sim_no = 1 : length(collated_data) + + %% Extract model input parameters for this simulation + input_vars = {'hr', 'sv', 'lvet', 't_pf', 'reg_vol', 'dbp', 'mbp', 'pvr', 'pvc', 'p_out', 'len', 'dia', 'pwv', 'age'}; + for input_var_no = 1 : length(input_vars) + + % rename variable + curr_var_name = strrep(input_vars{input_var_no}, 't_pf', 'pft'); + curr_var_name = strrep(curr_var_name, 'reg_vol', 'rfv'); + + try + eval(['data.config.' curr_var_name '(sim_no,1) = collated_data(sim_no).input_data.sim_settings.' input_vars{input_var_no} ';']); + catch + rel_col = find(strcmp(collated_data(sim_no).input_data.sim_settings.variations.param_names,input_vars{input_var_no})); + eval(['data.config.' curr_var_name '(sim_no,1) = collated_data(sim_no).input_data.sim_settings.variations.params(rel_col);']); + end + if ~strcmp(input_vars{input_var_no}, 'age') + if strcmp(input_vars{input_var_no}, 'pvr') + rel_col = find(strcmp(collated_data(sim_no).input_data.sim_settings.variations.param_names,'mbp')); + else + rel_col = find(strcmp(collated_data(sim_no).input_data.sim_settings.variations.param_names,input_vars{input_var_no})); + end + eval(['data.config.' curr_var_name '_SD(sim_no,1) = collated_data(sim_no).input_data.sim_settings.variations.params(rel_col);']); + end + end + clear input_var_no input_vars rel_col + + % Note down whether this is a baseline simulation + if sum(collated_data(sim_no).input_data.sim_settings.variations.params ~= 0) == 0 + data.config.baseline_sim_for_age(sim_no) = true; + if collated_data(sim_no).input_data.sim_settings.age == 25 + data.config.baseline_sim_for_all(sim_no) = true; + end + end + + %% Extract Simulated Waves + + % Add in Waves along paths + if do_path + % cycle through each path + for path_name_no = 1 : length(arterial_paths) + curr_path_name = arterial_paths(path_name_no).name; + + % Extract data for this path + running_dist = 0; counter_no = 0; + domains = extractfield(collated_data(sim_no).output_data, 'domain_no'); + for site_no = 1 : length(arterial_paths(path_name_no).seg_names) + curr_domain_no = arterial_paths(path_name_no).doms(site_no); + curr_domain_el = find(domains == curr_domain_no); + rel_wave_data = collated_data(sim_no).output_data(curr_domain_el); + seg_length = collated_data(sim_no).input_data.sim_settings.network_spec.length(curr_domain_no); + + for dist_el = 1:length(rel_wave_data.distances) + curr_dist = running_dist + rel_wave_data.distances(dist_el); +% if site_no > 1 && rel_wave_data.distances(dist_el) == 0 +% continue +% end + counter_no = counter_no+1; + eval(['curr_seg_name = ''path' num2str(counter_no) '_' arterial_paths(path_name_no).seg_names{site_no} ''';']); + signals2 = {'P', 'U', 'A'}; + for signal_no = 1 : length(signals2) + if strcmp(signals2{signal_no}, 'P') + factor = 133.33; + else + factor = 1; + end + curr_sig = signals2{signal_no}; + + eval(['data.path_waves.' curr_path_name '(sim_no).' curr_sig '{counter_no} = rel_wave_data.' curr_sig '(:,dist_el)/factor;']) + clear factor + end + eval(['data.path_waves.' curr_path_name '(sim_no).dist(counter_no,1) = curr_dist;']); + eval(['data.path_waves.' curr_path_name '(sim_no).artery{counter_no,1} = arterial_paths(path_name_no).seg_names{site_no};']); + eval(['data.path_waves.' curr_path_name '(sim_no).segment_no{counter_no,1} = arterial_paths(path_name_no).doms(site_no);']); + eval(['data.path_waves.' curr_path_name '(sim_no).artery_dist(counter_no,1) = rel_wave_data.distances(dist_el);']); + + % calculate pulse onset time + rel_row = find(domains == 1); + aortic_root_onset = collated_data(sim_no).output_data(rel_row).start_sample(1); clear rel_row + if strcmp(curr_sig, 'PPG') + temp_onset_time = (rel_wave_data.PPG_start_sample(dist_el)-aortic_root_onset)/rel_wave_data.fs; + else + temp_onset_time = (rel_wave_data.start_sample(dist_el)-aortic_root_onset)/rel_wave_data.fs; + end + % if the time is negative then add on the duration of a cardiac cycle + if temp_onset_time < 0 + cardiac_cycle_duration = length(rel_wave_data.P(:,1))/rel_wave_data.fs; + temp_onset_time = temp_onset_time + cardiac_cycle_duration; + end + % store pulse onset time + eval(['data.path_waves.' curr_path_name '(sim_no).onset_time(counter_no,1) = temp_onset_time;']); + clear aortic_root_onset + + end + running_dist = running_dist + seg_length; + clear signal_no curr_sig rel_wave_data seg_length curr_domain_el curr_domain_no + end + clear site_no + end + end + + % Add in Waves at each selected site + domains = extractfield(collated_data(sim_no).output_data, 'domain_no'); + for site_no = 1 : length(sites) + curr_domain_no = site_domain_no(site_no); + curr_domain_el = find(domains == curr_domain_no); + rel_wave_data = collated_data(sim_no).output_data(curr_domain_el); + seg_length = collated_data(sim_no).input_data.sim_settings.network_spec.length(curr_domain_no); + [~, rel_dist_el] = min(abs(rel_wave_data.distances - (site_dist_prop(site_no)*seg_length))); + for signal_no = 1 : length(signals) + if strcmp(signals{signal_no}, 'P') + factor = 133.33; + else + factor = 1; + end + curr_sig = signals{signal_no}; + + eval(['data.waves.' curr_sig '_' sites{site_no} '{sim_no} = rel_wave_data.' curr_sig '(:,rel_dist_el)/factor;']) + clear factor + + % calculate pulse onset time + rel_row = find(domains == 1); + aortic_root_onset = collated_data(sim_no).output_data(rel_row).start_sample(1); clear rel_row + if strcmp(curr_sig, 'PPG') + temp_onset_time = (rel_wave_data.PPG_start_sample(rel_dist_el)-aortic_root_onset)/rel_wave_data.fs; + else + temp_onset_time = (rel_wave_data.start_sample(rel_dist_el)-aortic_root_onset)/rel_wave_data.fs; + end + % if the time is negative then add on the duration of a cardiac cycle + if temp_onset_time < 0 + cardiac_cycle_duration = length(rel_wave_data.P(:,1))/rel_wave_data.fs; + temp_onset_time = temp_onset_time + cardiac_cycle_duration; + end + % store pulse onset time + eval(['data.waves.onset_times.' curr_sig '_' sites{site_no} '(sim_no,1) = temp_onset_time;']) + clear aortic_root_onset + end + clear signal_no curr_sig rel_wave_data seg_length curr_domain_el curr_domain_no + end + clear site_no + + %% Extract variation for this simulation + a = collated_data(sim_no).input_data.sim_settings.variations.param_names; + req_order = {'hr', 'sv', 'lvet', 't_pf', 'reg_vol', 'len', 'dia', 'pwv', 'mbp', 'pvc'}; + curr_params = a; + req_els = nan(length(curr_params),1); + counter = length(intersect(a,req_order))+1; + for param_no = 1 : length(curr_params) + curr_param = curr_params{param_no}; + if sum(strcmp(req_order, curr_param)) + position = find(strcmp(req_order, curr_param)); + req_els(position) = param_no; + else + position = counter; + req_els(position) = param_no; + counter = counter+1; + end + end + clear req_order var_no + + data.config.variations.params(sim_no,:) = collated_data(sim_no).input_data.sim_settings.variations.params(req_els); + current_names = collated_data(sim_no).input_data.sim_settings.variations.param_names(req_els); + if sum(strcmp(fieldnames(data.config.variations), 'param_names')) & ~isequal(current_names, data.config.variations.param_names) + error('check this') + elseif sim_no == 1 + data.config.variations.param_names = current_names; + end + + %% Extract desired PWVs + vars = {'pwv_aorta', 'pwv_leg', 'pwv_arm'}; + mod_names = {'pwv_cf', 'pwv_fa', 'pwv_br'}; + for var_no = 1 : length(vars) + eval(['data.config.desired_chars.' mod_names{var_no} '(sim_no,1) = collated_data(sim_no).input_data.sim_settings.desired_' vars{var_no} ';']); + end + clear var_no vars + + %% Extract desired aortic geometry + % Diameters using values measured from the simulated waves + domain_nos = extractfield(collated_data(1).output_data, 'domain_no'); + % - asc aorta + rel_domain_nos = find(collated_data(sim_no).input_data.sim_settings.network_spec.asc_aorta); + [~,domain_els,~] = intersect(domain_nos, rel_domain_nos); + for s = 1 : length(domain_els) + curr_domain_el = domain_els(s); + ave_areas(s,1) = mean([max(collated_data(sim_no).output_data(curr_domain_el).A(:,1)), max(collated_data(sim_no).output_data(curr_domain_el).A(:,end))]); + end + lengths = collated_data(sim_no).input_data.sim_settings.network_spec.length(rel_domain_nos); + data.config.desired_chars.dia_asc_a(sim_no,1) = 1000*2*(sum(lengths.*sqrt(ave_areas./pi)))/sum(lengths); + clear ave_areas lengths + % - desc thor aorta + rel_domain_nos = find(collated_data(sim_no).input_data.sim_settings.network_spec.desc_thor_aorta); + [~,domain_els,~] = intersect(domain_nos, rel_domain_nos); + for s = 1 : length(domain_els) + curr_domain_el = domain_els(s); + ave_areas(s,1) = mean([max(collated_data(sim_no).output_data(curr_domain_el).A(:,1)), max(collated_data(sim_no).output_data(curr_domain_el).A(:,end))]); + end + lengths = collated_data(sim_no).input_data.sim_settings.network_spec.length(rel_domain_nos); + data.config.desired_chars.dia_desc_thor_a(sim_no,1) = 1000*2*(sum(lengths.*sqrt(ave_areas./pi)))/sum(lengths); + clear ave_areas lengths + % - abd aorta + rel_domain_nos = find(collated_data(sim_no).input_data.sim_settings.network_spec.abd_aorta); + [~,domain_els,~] = intersect(domain_nos, rel_domain_nos); + for s = 1 : length(domain_els) + curr_domain_el = domain_els(s); + ave_areas(s,1) = mean([max(collated_data(sim_no).output_data(curr_domain_el).A(:,1)), max(collated_data(sim_no).output_data(curr_domain_el).A(:,end))]); + end + lengths = collated_data(sim_no).input_data.sim_settings.network_spec.length(rel_domain_nos); + data.config.desired_chars.dia_abd_a(sim_no,1) = 1000*2*(sum(lengths.*sqrt(ave_areas./pi)))/sum(lengths); + clear ave_areas lengths + % - carotid + rel_domain_nos = find(collated_data(sim_no).input_data.sim_settings.network_spec.both_carotid); + [~,domain_els,~] = intersect(domain_nos, rel_domain_nos); + for s = 1 : length(domain_els) + curr_domain_el = domain_els(s); + ave_areas(s,1) = mean([mean(collated_data(sim_no).output_data(curr_domain_el).A(:,1)), mean(collated_data(sim_no).output_data(curr_domain_el).A(:,end))]); + end + lengths = collated_data(sim_no).input_data.sim_settings.network_spec.length(rel_domain_nos); + data.config.desired_chars.dia_car(sim_no,1) = 1000*2*(sum(lengths.*sqrt(ave_areas./pi)))/sum(lengths); + clear ave_areas lengths + + rel_els = collated_data(sim_no).input_data.sim_settings.network_spec.proximal_aorta; + data.config.desired_chars.len_prox_a(sim_no,1) = 1000*sum( collated_data(sim_no).input_data.sim_settings.network_spec.length(rel_els) ); + + %% Store arterial network properties + data.config.network.segment_name = collated_data(sim_no).input_data.sim_settings.network_spec.segment_name; + data.config.network.inlet_node(sim_no,:) = collated_data(sim_no).input_data.sim_settings.network_spec.inlet_node; + data.config.network.outlet_node(sim_no,:) = collated_data(sim_no).input_data.sim_settings.network_spec.outlet_node; + data.config.network.length(sim_no,:) = collated_data(sim_no).input_data.sim_settings.network_spec.length; + data.config.network.inlet_radius(sim_no,:) = collated_data(sim_no).input_data.sim_settings.network_spec.inlet_radius; + data.config.network.outlet_radius(sim_no,:) = collated_data(sim_no).input_data.sim_settings.network_spec.outlet_radius; + data.config.constants.k(sim_no,:) = collated_data(sim_no).input_data.sim_settings.network_spec.k; + + %% Store other simulation properties + data.config.constants.rho(sim_no,:) = collated_data(sim_no).input_data.sim_settings.rho; + if ~do_alternative_gamma + data.config.constants.gamma_b0(sim_no,1) = collated_data(sim_no).input_data.sim_settings.gamma_b0; + data.config.constants.gamma_b1(sim_no,1) = collated_data(sim_no).input_data.sim_settings.gamma_b1; + else + data.config.constants.gamma_b0(sim_no,1) = collated_data(sim_no).input_data.sim_settings.fixed.wall.Gamma_b0; + data.config.constants.gamma_b1(sim_no,1) = collated_data(sim_no).input_data.sim_settings.fixed.wall.Gamma_b1; + end + data.config.constants.mu(sim_no,1) = collated_data(sim_no).input_data.sim_settings.mu; + data.config.constants.alpha(sim_no,1) = collated_data(sim_no).input_data.sim_settings.alpha; + data.config.constants.p_drop(sim_no,1) = collated_data(sim_no).input_data.sim_settings.p_drop; + + %% Extract system chars + if exist('system_chars', 'var') + rel_vars = system_chars.Properties.VariableNames; + for var_no = 1 : length(rel_vars) + eval(['data.config.system_chars.' rel_vars{var_no} ' = system_chars.' rel_vars{var_no} '(sim_no);']) + end + end +end +clear sim_no + +% rename variables +data.config.variations.param_names = strrep(data.config.variations.param_names, 'reg_vol', 'rfv'); +data.config.variations.param_names = strrep(data.config.variations.param_names, 't_pf', 'pft'); + +% Add in haemodynamic params +data.haemods = haemodynamic_params; +data.waves.fs = collated_data(1).output_data.fs; +data.path_waves.fs = collated_data(1).output_data.fs; +data.waves.units.P = 'mmHg'; +data.waves.units.U = 'm/s'; +data.waves.units.A = 'm3'; +data.path_waves.units = data.waves.units; +%data.waves.units.Q = 'm3/s'; +data.waves.units.PPG = 'au'; +data.path_waves.units.dist = 'm'; + +% Add in peripheral boundary conditions +data.config.network.wk_c = peripheral_chars.c; +data.config.network.wk_r = peripheral_chars.r_sum; + +% system chars units +if exist('system_chars', 'var') + data.config.system_chars.units.pvr = 'Pa s /m3'; + data.config.system_chars.units.pvc = 'm3 /Pa'; + data.config.system_chars.units.pvc_iw = 'm3 /Pa'; + data.config.system_chars.units.ac = 'm3 /Pa'; + data.config.system_chars.units.c = 'm3 /Pa'; + data.config.system_chars.units.tau = 's'; +end + +% Add in pulse wave indices +data.pw_inds = pw_inds; + +%% Assess physiological plausibility of each virtual subject + +data = assess_phys_plausibility(data); + +%% Save files + +orig_data = data; clear data + +% - create variable for ""aorta_finger"" path waves +data = rmfield(orig_data, 'waves'); +if sum(strcmp(fieldnames(data.path_waves), 'aorta_finger')) + if sum(strcmp(fieldnames(data.path_waves), 'aorta_r_subclavian')), rmfield(data.path_waves, 'aorta_r_subclavian'); end + if sum(strcmp(fieldnames(data.path_waves), 'aorta_foot')), rmfield(data.path_waves, 'aorta_foot'); end + if sum(strcmp(fieldnames(data.path_waves), 'aorta_brain')), rmfield(data.path_waves, 'aorta_brain'); end + % save + a = whos('data'); + if a.bytes > 1.8e9, save(PATHS.exported_data_mat_pwdb_data_w_aorta_finger_path, 'data', '-v7.3'); + else save(PATHS.exported_data_mat_pwdb_data_w_aorta_finger_path, 'data'), end + clear data +end + +% - create variable for ""aorta_foot_p"" path waves +data = rmfield(orig_data, 'waves'); +if sum(strcmp(fieldnames(data.path_waves), 'aorta_foot')) + if sum(strcmp(fieldnames(data.path_waves), 'aorta_r_subclavian')), rmfield(data.path_waves, 'aorta_r_subclavian'); end + if sum(strcmp(fieldnames(data.path_waves), 'aorta_finger')), rmfield(data.path_waves, 'aorta_finger'); end + if sum(strcmp(fieldnames(data.path_waves), 'aorta_brain')), rmfield(data.path_waves, 'aorta_brain'); end + data.path_waves.aorta_foot = rmfield(data.path_waves.aorta_foot, {'U', 'A'}); + % save + a = whos('data'); + if a.bytes > 1.8e9, save(PATHS.exported_data_mat_pwdb_data_w_aorta_foot_path_p, 'data', '-v7.3'); + else save(PATHS.exported_data_mat_pwdb_data_w_aorta_foot_path_p, 'data'), end + clear data +end + +% - create variable for ""aorta_foot_u"" path waves +data = rmfield(orig_data, 'waves'); +if sum(strcmp(fieldnames(data.path_waves), 'aorta_foot')) + if sum(strcmp(fieldnames(data.path_waves), 'aorta_r_subclavian')), rmfield(data.path_waves, 'aorta_r_subclavian'); end + if sum(strcmp(fieldnames(data.path_waves), 'aorta_finger')), rmfield(data.path_waves, 'aorta_finger'); end + if sum(strcmp(fieldnames(data.path_waves), 'aorta_brain')), rmfield(data.path_waves, 'aorta_brain'); end + data.path_waves.aorta_foot = rmfield(data.path_waves.aorta_foot, {'P', 'A'}); + % save + a = whos('data'); + if a.bytes > 1.8e9, save(PATHS.exported_data_mat_pwdb_data_w_aorta_foot_path_u, 'data', '-v7.3'); + else save(PATHS.exported_data_mat_pwdb_data_w_aorta_foot_path_u, 'data'), end + clear data +end + +% - create variable for ""aorta_foot_a"" path waves +data = rmfield(orig_data, 'waves'); +if sum(strcmp(fieldnames(data.path_waves), 'aorta_foot')) + if sum(strcmp(fieldnames(data.path_waves), 'aorta_r_subclavian')), rmfield(data.path_waves, 'aorta_r_subclavian'); end + if sum(strcmp(fieldnames(data.path_waves), 'aorta_finger')), rmfield(data.path_waves, 'aorta_finger'); end + if sum(strcmp(fieldnames(data.path_waves), 'aorta_brain')), rmfield(data.path_waves, 'aorta_brain'); end + data.path_waves.aorta_foot = rmfield(data.path_waves.aorta_foot, {'U', 'P'}); + % save + a = whos('data'); + if a.bytes > 1.8e9, save(PATHS.exported_data_mat_pwdb_data_w_aorta_foot_path_a, 'data', '-v7.3'); + else save(PATHS.exported_data_mat_pwdb_data_w_aorta_foot_path_a, 'data'), end + clear data +end + +% - create variable for ""aorta_brain"" path waves +data = rmfield(orig_data, 'waves'); +if sum(strcmp(fieldnames(data.path_waves), 'aorta_brain')) + if sum(strcmp(fieldnames(data.path_waves), 'aorta_r_subclavian')), rmfield(data.path_waves, 'aorta_r_subclavian'); end + if sum(strcmp(fieldnames(data.path_waves), 'aorta_foot')), rmfield(data.path_waves, 'aorta_foot'); end + if sum(strcmp(fieldnames(data.path_waves), 'aorta_finger')), rmfield(data.path_waves, 'aorta_finger'); end + % save + a = whos('data'); + if a.bytes > 1.8e9, save(PATHS.exported_data_mat_pwdb_data_w_aorta_brain_path, 'data', '-v7.3'); + else save(PATHS.exported_data_mat_pwdb_data_w_aorta_brain_path, 'data'), end + clear data +end + +% - create variable for ""aorta_rsubclavian"" path waves +data = rmfield(orig_data, 'waves'); +if sum(strcmp(fieldnames(data.path_waves), 'aorta_r_subclavian')) + if sum(strcmp(fieldnames(data.path_waves), 'aorta_finger')), rmfield(data.path_waves, 'aorta_finger'); end + if sum(strcmp(fieldnames(data.path_waves), 'aorta_foot')), rmfield(data.path_waves, 'aorta_foot'); end + if sum(strcmp(fieldnames(data.path_waves), 'aorta_brain')), rmfield(data.path_waves, 'aorta_brain'); end + % save + a = whos('data'); + if a.bytes > 1.8e9, save(PATHS.exported_data_mat_pwdb_data_w_aorta_rsubclavian_path, 'data', '-v7.3'); + else save(PATHS.exported_data_mat_pwdb_data_w_aorta_rsubclavian_path, 'data'), end + clear data +end + +% data without the arterial path waves +data = rmfield(orig_data, 'path_waves'); +save(PATHS.exported_data_mat_pwdb_data, 'data') + +end + +function PrintFigs(h, paper_size, savepath) +set(h,'PaperUnits','inches'); +set(h,'PaperSize', [paper_size(1), paper_size(2)]); +set(h,'PaperPosition',[0 0 paper_size(1) paper_size(2)]); +set(gcf,'color','w'); +print(h,'-dpdf',savepath) +%print(h,'-dpng',savepath) + +% if you want .eps illustrations, then do as follows: +up.eps_figs = 0; +if up.eps_figs + % you need to download 'export_fig' from: + % http://uk.mathworks.com/matlabcentral/fileexchange/23629-export-fig + export_fig_dir_path = 'C:\Documents\Google Drive\Work\Projects\PhD\Github\phd\Tools\Other Scripts\export_fig\altmany-export_fig-76bd7fa\'; + addpath(export_fig_dir_path) + export_fig(savepath, '-eps') +end +close all; + +% save +fid = fopen([savepath, '.txt'], 'w'); +p = mfilename('fullpath'); +p = strrep(p, '\', '\\'); +fprintf(fid, ['Figures generated by:\n\n ' p '.m \n\n on ' datestr(today)]); +fclose all; + +end + +","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/create_pwdb_input_files.m",".m","13340","320","function create_pwdb_input_files +% CALCULATE_PWDB_INPUT_FILES creates a set of Nektar1D input files for each +% virtual subject in the Pulse Wave DataBase. +% +% create_pwdb_input_files +% +% Inputs: a single file called ""inputs.mat"", which contains the +% parameters variable required by Nektar1D input files. This +% file can be created using the +% ""calculate_pwdb_input_parameters.m"" script. +% +% +% Outputs: - input files for Nektar simulations +% - shell script files to make it easier to run a batch of +% simulations +% +% Accompanying Article: +% This code is provided to facilitate reproduction of the Pulse Wave +% Database described in: +% Charlton P.H. et al. Modelling arterial pulse waves in healthy +% ageing: in silico evaluation of haemodynamics and +% pulse wave indices, ~~ under review ~~ +% DOI: ~~ tbc ~~ +% Further information on the pwdb Pulse Wave Database is provided in +% this article and at the project website: +% https://peterhcharlton.github.io/pwdb +% +% Author: Peter H. Charlton +% +% Licence: +% Permission is hereby granted, free of charge, to any person obtaining a copy +% of this software and associated documentation files (the ""Software""), to deal +% in the Software without restriction, including without limitation the rights +% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +% copies of the Software, and to permit persons to whom the Software is +% furnished to do so, subject to the following conditions: +% +% The above copyright notice and this permission notice shall be included in all +% copies or substantial portions of the Software. +% +% THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +% SOFTWARE. +% +% Copyright (C) 2019 King's College London +% +% v.1.0 Contributed to by: Marie Willemet, Jordi Alastruey, and Peter H. Charlton + +fprintf('\n --- Creating Input Files ---') + +%% Settings +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%%%% SETTINGS TO CHANGE: This function specifies where to save the outputs %%%% +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +up = setup_up; +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +%% Create input files +up = WriteInput_DB_pc(up); + +%% Copy input files from temporary folder to Ubuntu shared folder +CopyInputFiles(up); + +end + +function up = setup_up + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% This line specifies the location of the input parameters file %% +% This should be the same as in calculate_pwdb_input_parameters.m % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +up.paths.savefolder = '/Users/petercharlton/Documents/Data/Nektar1D/ageing_sims/'; % (needs to have a slash at the end) +%up.paths.savefolder = '/home/pc13/Documents/Data/Nektar1D/ageing_sims/'; +up.paths.input_parameters_filepath = [up.paths.savefolder, 'inputs.mat']; % input parameters file + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% These lines specify where to store temporary files created %% +% to run the simulations % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% (i) Computer running Matlab +up.paths.Matlab_computer_PathRoot = '/Users/petercharlton/Desktop/temp/pwdb_files/'; % This is where the input files will be stored temporarily before being copied to the shared folder +up.paths.Matlab_computer_shared_folder = '/Users/petercharlton/Documents/VM-share/'; % This is a shared folder which the input files are copied into (from the perspective of the Matlab computer) +%up.paths.Matlab_computer_PathRoot = '/home/pc13/Documents/Data/Nektar1D/temp/pwdb_files/'; % This is where the input files will be stored temporarily before being copied to the shared folder +%up.paths.Matlab_computer_shared_folder = '/home/pc13/Documents/Data/Nektar1D/VM-share/'; % This is a shared folder which the input files are copied into (from the perspective of the Matlab computer) +% (ii) Computer running Nektar1D (Ubuntu) +up.paths.Nektar_computer_shared_folder = '/media/sf_VM-share/'; % This is the shared folder (from the perspective of the computer used to run the simulations). +up.paths.Nektar_computer_sim_folder = '/home/pc13/Documents/sim/'; % This is the folder in which the output files from the simulations will be stored temporarily before being copied back to the shared folder. +%up.paths.Nektar_computer_shared_folder = '/home/pc13/Documents/Data/Nektar1D/VM-share/'; % This is the shared folder (from the perspective of the computer used to run the simulations). +%up.paths.Nektar_computer_sim_folder = '/media/pc13/6050B1A350B18078/Users/pc13/Simulation_data/'; + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% This line specifies how many command files to create for % +% running the simulations. It should be at least one, and (to % +% run the simulations more quickly) the number of cores which % +% will be used to run the simulations. % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +up.no_launch_files = 2; + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%%%%%%%%%%% The rest of this function can be left alone %%%%%%%% + +fprintf('\n - Setting up universal parameters') + +%- file names +% used to run shell scripts to launch the simulations +up.paths.command_file = 'command_list'; +up.paths.launch_file = 'launch_sims'; +% used to record which simulations ran successfully +up.paths.FileNameResults_success = 'Nektar_Success'; % Where successful simulation names are listed during simulations +up.paths.FileNameResults_error = 'Nektar_Error'; % Where unsuccessful simulation names are listed during simulations + +% - make folders if they don't already exist +if ~exist(up.paths.Matlab_computer_PathRoot) + mkdir(up.paths.Matlab_computer_PathRoot) +end + +end + +function up = WriteInput_DB_pc(up) + +%% Setup +fclose all; + +% add directory of this file (and subdirectories) to path +filepath = fileparts(mfilename('fullpath')); +addpath(genpath(filepath)); clear filepath + +% load virtual database parameters +load(up.paths.input_parameters_filepath); + +% clear temporary folder +clear_temp_folder(up); + +%% Create the input files for each simulation +fprintf('\n - Creating Input Files') + +% Open command cloud file ready to write instructions (in temporary folder) +for file_no = 1 : up.no_launch_files + command_file_names{file_no} = [up.paths.Matlab_computer_PathRoot, up.paths.command_file, num2str(file_no), '.txt']; + fidCommand(file_no) = fopen(command_file_names{file_no},'w'); +end + +for sim_no = 1 : length(parameters.age) + + fprintf(['\n Simulation: ' num2str(sim_no)]) + + % Identify settings for this simulation + curr_sim_setting = identify_sim_settings(parameters, inflow, sim_no); + + % Create Nektar input files (in temporary folder) + FileName = create_input_files_for_a_simulation(curr_sim_setting, up); + + % Write commandLine into file + current_command_file_no = rem(sim_no, up.no_launch_files); + if current_command_file_no == 0 + current_command_file_no = up.no_launch_files; + end + curr_error_filename = [up.paths.FileNameResults_error, num2str(current_command_file_no)]; + curr_success_filename = [up.paths.FileNameResults_success, num2str(current_command_file_no)]; + %commandLine = ['oneDbio -L -R ', FileName, '.in && echo ''', FileName,''' >> ', curr_success_filename,'.txt || echo ''', FileName,''' >> ', curr_error_filename, '.txt']; clear curr_sim_setting + % extra output files + commandLine = ['oneDbio -O -L -d -t -R -s -m ', FileName, '.in && echo ''', FileName,''' >> ', curr_success_filename,'.txt || echo ''', FileName,''' >> ', curr_error_filename, '.txt']; clear curr_sim_setting + fprintf(fidCommand(current_command_file_no), [commandLine,'\n']); + + clear FileName curr_sim_setting commandLine + +end + +% Finish command cloud file +for file_no = 1 : length(fidCommand) + fclose(fidCommand(file_no)); +end +clear fidCommand +fclose all; + +fprintf(['\n All input files copied to ',strrep(up.paths.Matlab_computer_PathRoot, '\', '\\')]) + +%% Create launch file +WriteLaunchFile(up, command_file_names) + +up.vdb_up = parameters.fixed; + +end + +function clear_temp_folder(up) + +fprintf('\n - Clearing temporary folder ') + +% delete any files in the temporary VDB folder +files = dir(up.paths.Matlab_computer_shared_folder); +if ~isempty(files) + file_names = extractfield(files, 'name'); + file_dirs = cell2mat(extractfield(files, 'isdir')); clear files + files_to_delete = file_names(~file_dirs); clear file_dirs file_names + for file_no = 1 : length(files_to_delete) + curr_filename = [up.paths.Matlab_computer_shared_folder, files_to_delete{file_no}]; + delete(curr_filename); + end + clear file_no files_to_delete +end + +% Make folders to store files in +folder_path = up.paths.Matlab_computer_shared_folder; +if ~exist(folder_path, 'dir') + mkdir(folder_path); +end + +end + +function sim_settings = identify_sim_settings(parameters, inflow, sim_no) + +% copy across fixed parameters +sim_settings.fixed = parameters.fixed; + +% copy across network spec for this simulation +sim_settings.network_spec = parameters.network_spec{sim_no}; + +% copy across wk params +sim_settings.wk_params = parameters.wk_params; + +% copy across variations information +sim_settings.variations.params = parameters.variations.params(sim_no,:); +sim_settings.variations.param_names = parameters.variations.param_names; + +% copy across remaining parameters +parameters = rmfield(parameters, {'fixed', 'network_spec', 'variations', 'wk_params'}); + +model_params.names = fieldnames(parameters); +for param_no = 1 : length(model_params.names) + curr_param = model_params.names{param_no}; + eval(['sim_settings.' curr_param ' = parameters.' curr_param '(sim_no);']); +end + +% copy across inflow waveform +sim_settings.inflow = inflow{sim_no}; + +sim_settings.filename = ['sim_' num2str(sim_no)]; + +end + +function WriteLaunchFile(up, command_file_names) + +fprintf('\n - Writing Launch Files') + +if nargin == 1 + launch_file_names{1} = up.paths.launch_file; + filepath{1} = [up.paths.Matlab_computer_PathRoot, launch_file_names{file_no}]; +else + for file_no = 1 : length(command_file_names) + launch_file_names{file_no} = [up.paths.launch_file, num2str(file_no)]; + filepath{file_no} = [up.paths.Matlab_computer_PathRoot, launch_file_names{file_no}]; + end +end +newline_char = '\n'; + +% create starter file +starterfile_path = [up.paths.Matlab_computer_PathRoot, 'launch_starter']; +fid = fopen(starterfile_path, 'wt'); +file_text = ['mkdir -p ' up.paths.Nektar_computer_sim_folder, newline_char, ... + 'cd ' up.paths.Nektar_computer_sim_folder, newline_char, ... + 'rm *.*', newline_char, ... + 'cp ' up.paths.Nektar_computer_shared_folder '*.* .', newline_char, ... + 'echo Finished operations']; +fprintf(fid, file_text); +fclose(fid); + +% create finisher file +finisherfile_path = [up.paths.Matlab_computer_PathRoot, 'launch_finisher']; +fid = fopen(finisherfile_path, 'wt'); +file_text = ['cd ' up.paths.Nektar_computer_sim_folder, newline_char, ... + 'cp *.* /media/sf_VM-share/.', newline_char, ... + 'echo Finished operations']; +fprintf(fid, file_text); +fclose(fid); + +% create individual run files + +for file_no = 1 : length(launch_file_names) + + fid = fopen(filepath{file_no}, 'wt'); + + file_text = ['echo Launching file ', num2str(file_no), newline_char, ... + 'cd ', up.paths.Nektar_computer_sim_folder, newline_char, ... + ['chmod u+x ' up.paths.command_file, num2str(file_no), '.txt'], newline_char, ... + ['./' up.paths.command_file, num2str(file_no) '.txt'], newline_char, ... + 'echo Finished operations']; + + fprintf(fid, file_text); + + fclose(fid); + +end + +end + +function CopyInputFiles(up) + +fprintf('\n - Copying Input Files to Virtual Box Shared Folder') + +% Identify input files to be copied +current_folder = up.paths.Matlab_computer_PathRoot; +input_files = dir(current_folder); +exc = cell2mat(extractfield(input_files, 'isdir')); +input_files = extractfield(input_files, 'name'); +input_files = input_files(~exc); clear exc + +% Copy each input file +for input_file_no = 1 : length(input_files) + curr_file_name = input_files{input_file_no}; + copyfile([current_folder, curr_file_name], [up.paths.Matlab_computer_shared_folder, curr_file_name]); +end + +end","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/analyse_pwdb.m",".m","112469","2883","function analyse_pwdb(pwdb_no) +% ANALYSE_PWDB analyses the Pulse Wave Database, producing results figures +% and tables. +% +% analyse_pwdb +% +% Inputs: - 'pwdb_data.mat', which is produced by 'export_pwdb.m'. +% - [optional] the '...path.mat' files produced by the +% same script +% +% Outputs: - Figures and Tables containing the results of the analyses. +% +% Accompanying Article: +% This code is provided to facilitate reproduction of the Pulse Wave +% Database described in: +% Charlton P.H. et al. Modelling arterial pulse waves in healthy +% ageing: in silico evaluation of haemodynamics and +% pulse wave indices, ~~ under review ~~ +% DOI: ~~ tbc ~~ +% Further information on the pwdb Pulse Wave Database is provided in +% this article and at the project website: +% https://peterhcharlton.github.io/pwdb +% +% Author: Peter H. Charlton +% +% Licence: +% Permission is hereby granted, free of charge, to any person obtaining a copy +% of this software and associated documentation files (the ""Software""), to deal +% in the Software without restriction, including without limitation the rights +% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +% copies of the Software, and to permit persons to whom the Software is +% furnished to do so, subject to the following conditions: +% +% The above copyright notice and this permission notice shall be included in all +% copies or substantial portions of the Software. +% +% THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +% SOFTWARE. +% +% Copyright (C) 2019 King's College London +% +% Contributed to by: Marie Willemet, Jordi Alastruey, and Peter H. Charlton +% v.1.0 + +fprintf('\n --- Analysing PWDB ---') + +%% Settings +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% SETTINGS TO CHANGE: This function specifies where to save the outputs % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +PATHS = setup_paths_for_post_processing(pwdb_no); +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% create folders in which to store results +create_folders(PATHS) + +% Make table of haemodynamic characteristics +make_haem_characteristics_table(PATHS); + +% Make demo PPG analysis plot +make_demo_ppg_analysis_plot(PATHS); + +% Compare simulated characteristics with prescribed characteristics +make_simulated_vs_prescribed_figure(PATHS); + +% Make wave speed figure +make_wave_speed_figure(PATHS); + +% Compare simulated characteristics with those from literature +make_simulated_vs_literature_figure(PATHS); + +% Make figure of baseline waves of 25-year old at common measurement sites +make_baseline_waves_figure(PATHS, pwdb_no); + +% Make pressure-area plots to investigate hysteresis +make_pressure_area_plots(PATHS); + +% Make plot of how gamma changes with arterial diameter +make_gamma_plots(PATHS); + +% Make plots of how 25-year old waves vary with changes in initial params +make_initial_parameters_waves_figure(PATHS); + +% Make figures of changes in wave shape with parameters +make_parameters_waves_figure(PATHS); + +% Make figure +make_wrist_ppg_parameters_figure(PATHS); + +% Make figure of PPG estimation +make_ppg_estimation_figure(PATHS); + +% Make figure of changes in wave shape with age (comparing to literature) +make_changes_in_waves_age_figure(PATHS); + +% Compare simulated characteristics when parameters are varied individually +make_parameters_characteristics_figure(PATHS); + +% Perform sensitivity analyses +make_sensitivity_analysis_figures(PATHS); + +% Make comparison of waves with Mynard's +comparison_w_mynard_waves_figure(PATHS); + +% Make figure showing pulse waves along particular paths +make_pw_along_path_figure(PATHS); + +fprintf('\n --- Finished analysing PWDB ---') + +end + +function create_folders(PATHS) + +folders_to_make = {PATHS.Analysis_tables, PATHS.Analysis_figures}; +for s = 1 : length(folders_to_make) + if ~exist(folders_to_make{s}, 'dir') + mkdir(folders_to_make{s}) + end +end + +end + +function make_demo_ppg_analysis_plot(PATHS) + +fprintf('\n - Making BP and PPG PW analysis demo plots') + +% load collated data +load(PATHS.exported_data_mat_pwdb_data) + +% Setup figure for Pressure and Flow vel +fig_settings.sig_types = {'P', 'PPG'}; +fig_settings.req_sites = {'Radial'}; +baseline_sim_no = find(data.config.baseline_sim_for_all); + +% cycle through different signals +for sig_type_no = 1 : length(fig_settings.sig_types) + curr_sig_type = fig_settings.sig_types{sig_type_no}; + + % cycle through different sites + for req_site_no = 1 : length(fig_settings.req_sites) + + % extract relevant signal at this site + curr_site = fig_settings.req_sites{req_site_no}; + eval(['rel_sig.v = data.waves.' curr_sig_type '_' curr_site '{baseline_sim_no};']) + rel_sig.fs = data.waves.fs; + rel_sig.t = [0:length(rel_sig.v)-1]/rel_sig.fs; + + % convert to friendly units if needed + if sum(strcmp(curr_sig_type, {'P', 'Pe'})) + rel_sig.v = rel_sig.v/133.33; % Pa to mmHg + rel_sig.units = 'mmHg'; + elseif strcmp(curr_sig_type, 'A') + rel_sig.v = rel_sig.v*1000*1000; % m^2 to mm^2 + rel_sig.units = 'mm^2'; + elseif strcmp(curr_sig_type, 'PPG') + rel_sig.units = 'au'; + end + + % Make plot + options.save_folder = PATHS.Analysis_figures; + options.do_demo_plot = false; + options.do_plot = 1; options.plot_third_deriv = 0; + options.save_file = ['demo_' curr_sig_type '_' curr_site '_']; + PulseAnalyse6(rel_sig, options); + close all + + end + +end + +end + +function make_haem_characteristics_table(PATHS) + +fprintf('\n - Making table of haemodynamic characteristics') + +%% load parameters +load(PATHS.exported_data_mat_pwdb_data) + +%% Skip if this doesn't have all the required ages +if ~isequal(unique(data.pw_inds.age(:)'), 25:10:75) + return +end + +%% extract haemodynamic parameters + +% select which parameters to extract +cardiac_params = {'HR', 'SV', 'CO', 'LVET', 'dPdt', 'PFT', 'RFV'}; +arterial_params = {'SBP_a', 'DBP_a', 'MBP_a', 'PP_a', 'SBP_b', 'DBP_b', 'MBP_b', 'PP_b', 'SBP_f', 'DBP_f', 'MBP_f', 'PP_f', 'PP_amp', 'AP_a', 'AI_a', 'Tr_a', 'PWV_a', 'PWV_cf', 'PWV_br', 'PWV_fa', 'dia_asc_a', 'dia_desc_thor_a', 'dia_abd_a', 'len_prox_a', 'MBP_drop_finger', 'MBP_drop_ankle', 'AGI_mod', 'RI', 'SI', 'IAD'}; +vascular_params = {'svr'}; +if sum(strcmp(fieldnames(data.haemods), 'pvc')) + vascular_params = [vascular_params, {'pvc','tau'}]; +end +params = { 'age', cardiac_params{:}, arterial_params{:}, vascular_params{:}}; + +% extract each of the parameters in turn +for param_no = 1 : length(params) + eval(['table_data.' params{param_no} ' = extractfield(data.haemods, ''' params{param_no} ''');']) +end +if sum(strcmp(fieldnames(data.haemods), 'pvc')) + % change units + table_data.pvc = 10e9*table_data.pvc; +end + + +% rename some of the variables +vars.old = {'AI_a', 'AP_a', 'Tr_a', 'pvc'}; +vars.new = {'AIx', 'AP', 'Tr', 'pvc_adj'}; +for var_no = 1 : length(vars.old) + if strcmp(fieldnames(table_data), vars.old{var_no}) + eval(['table_data.' vars.new{var_no} ' = table_data.' vars.old{var_no} ';']); + eval(['table_data = rmfield(table_data, ''' vars.old{var_no} ''');']); + if sum(strcmp(arterial_params, vars.old{var_no})) + arterial_params{strcmp(arterial_params, vars.old{var_no})} = vars.new{var_no}; + else + vascular_params{strcmp(vascular_params, vars.old{var_no})} = vars.new{var_no}; + end + end +end +clear vars var_no + +%% Find out how many physiologically plausible subjects in each age group +ages = unique(data.config.age); +no_subjs.all = sum(data.plausibility.plausibility_log); +for age_no = 1 : length(ages) + curr_age = ages(age_no); + temp_no_subjs = sum(data.plausibility.plausibility_log(data.config.age == curr_age)); + eval(['no_subjs.age' num2str(curr_age) ' = temp_no_subjs;']); + clear temp_no_subjs curr_age +end +clear age_no + +%% Create Table + +for s = 1 :2 + + if s == 1, do_range = false; else, do_range = true; end + csv_text = ['Haemodynamic Characteristic, All Subjects, 25, 35, 45, 55, 65, 75',newline]; + csv_text = [csv_text, 'n, ', num2str(no_subjs.all), ', ', num2str(no_subjs.age25), ', ', num2str(no_subjs.age35), ', ', num2str(no_subjs.age45), ', ', num2str(no_subjs.age55), ', ', num2str(no_subjs.age65), ', ', num2str(no_subjs.age75), newline]; + table_text = ['\\textbf{Cardiac} & & & & & & & \\\\', newline]; + csv_text = [csv_text, 'Cardiac , , , , , , ,', newline]; + [table_text, csv_text] = add_params_table_text(table_text, csv_text, cardiac_params, table_data, data.plausibility.plausibility_log, do_range); + table_text = [table_text, '\\hline', newline]; + table_text = [table_text, '\\textbf{Arterial} & & & & & & & \\\\', newline]; + csv_text = [csv_text, 'Arterial , , , , , , ,', newline]; + [table_text, csv_text] = add_params_table_text(table_text, csv_text, arterial_params, table_data, data.plausibility.plausibility_log, do_range); + table_text = [table_text, '\\hline', newline]; + table_text = [table_text, '\\textbf{Vascular Beds} & & & & & & & \\\\', newline]; + csv_text = [csv_text, 'Vascular Beds , , , , , , ,', newline]; + [table_text, csv_text] = add_params_table_text(table_text, csv_text, vascular_params, table_data, data.plausibility.plausibility_log, do_range); + + if ~do_range + fid = fopen(PATHS.characteristics_table, 'w'); + fid2 = fopen([PATHS.characteristics_table,'.csv'], 'w'); + else + fid = fopen(PATHS.characteristics_table_range, 'w'); + fid2 = fopen([PATHS.characteristics_table_range, '.csv'], 'w'); + end + fprintf(fid, table_text); + fprintf(fid2, csv_text); + fclose(fid); + fclose(fid2); +end + +end + +function [table_text, csv_text] = add_params_table_text(table_text, csv_text, curr_params, table_data, plausibility_log, do_range) + +if nargin<4 + do_range = false; +end + +for param_no = 1 : length(curr_params) + + curr_param = curr_params{param_no}; + + if strcmp(curr_param(1:2), 'EX') + continue + end + + % Make label + label = make_param_label(curr_param); + table_line = ['- ', label]; + + % Calculate stats + eval(['rel_vals.v = table_data.' curr_param ';']) + rel_vals.age = table_data.age; + + % - all subjects + rel_els = ~isnan(rel_vals.v) & plausibility_log(:)'; + mean_val = mean(rel_vals.v(rel_els)); + std_val = std(rel_vals.v(rel_els)); + range_val = range(rel_vals.v(rel_els)); + if strcmp(curr_param, 'dPdt') + mean_val = round(mean_val); + std_val = round(std_val); + end + if sum(strcmp(curr_param, {'PP_amp', 'CO', 'tau', 'RI', 'SI', 'AGI_mod'})) + if ~do_range + table_line = [table_line, ' & ' num2str(mean_val, '%.2f') ' $\\pm$ ' num2str(std_val, '%.2f') ]; + else + table_line = [table_line, ' & ' num2str(mean_val, '%.2f') ' $($' num2str(range_val, '%.2f') '$)$' ]; + end + else + if ~do_range + table_line = [table_line, ' & ' num2str(mean_val, '%.1f') ' $\\pm$ ' num2str(std_val, '%.1f') ]; + else + table_line = [table_line, ' & ' num2str(mean_val, '%.1f') ' $($' num2str(range_val, '%.1f') '$)$' ]; + end + end + + + % - individual ages + ages = unique(rel_vals.age); + for age_no = 1 : length(ages) + curr_age = ages(age_no); + rel_els = find(rel_vals.age == curr_age & ~isnan(rel_vals.v) & plausibility_log(:)'); + mean_val = mean(rel_vals.v(rel_els)); + std_val = std(rel_vals.v(rel_els)); + if strcmp(curr_param, 'dPdt') + mean_val = round(mean_val); + std_val = round(std_val); + end + if length(rel_els) ~= 2 + range_val = range(rel_vals.v(rel_els)); + else + range_val = rel_vals.v(rel_els(2)) - rel_vals.v(rel_els(1)); + end + if sum(strcmp(curr_param, {'PP_amp', 'CO', 'tau', 'RI', 'SI', 'AGI_mod'})) + if ~do_range + table_line = [table_line, ' & ' num2str(mean_val, '%.2f') ' $\\pm$ ' num2str(std_val, '%.2f') ]; + else + table_line = [table_line, ' & ' num2str(mean_val, '%.2f') ' $($' num2str(range_val, '%.2f') '$)$' ]; + end + else + if ~do_range + table_line = [table_line, ' & ' num2str(mean_val, '%.1f') ' $\\pm$ ' num2str(std_val, '%.1f') ]; + else + table_line = [table_line, ' & ' num2str(mean_val, '%.1f') ' $($' num2str(range_val, '%.1f') '$)$' ]; + end + end + end + table_line = [table_line, '\\\\', newline]; + + table_text = [table_text, table_line]; + + % create csv line + csv_line = strrep(table_line, ' &', ','); + csv_line = strrep(csv_line, '$\\pm$', '+/-'); + csv_line = strrep(csv_line, ', systolic', ''); + csv_line = strrep(csv_line, ', diastolic', ''); + csv_line = strrep(csv_line, ', mean', ''); + csv_line = strrep(csv_line, ', pulse pressure', ''); + csv_line = strrep(csv_line, '\\\\', ''); + %csv_line = strrep(csv_line, '\\%', '%%'); + csv_line = strrep(csv_line, '\\hspace{4.1cm}', ' '); + csv_line = strrep(csv_line, '\\hspace{4.5cm}', ' '); + csv_line = strrep(csv_line, '\\hspace{4.43cm}', ' '); + csv_line = strrep(csv_line, '\\hspace{2.7cm}', ' '); + csv_text = [csv_text, csv_line]; + clear table_line csv_line + +end + +end + +function make_simulated_vs_prescribed_figure(PATHS) + +fprintf('\n - Making simulated vs prescribed figure') + +only_baseline_sims = true; + +% Load data +load(PATHS.exported_data_mat_pwdb_data) +ages = data.config.age; + +% Prescribed characteristics +cardiac_params = {'HR', 'SV', 'LVET', 'PFT', 'RFV'}; +arterial_params = {'MBP', 'PWV_cf', 'PWV_br', 'PWV_fa', 'dia_asc_a', 'dia_desc_thor_a', 'dia_abd_a', 'dia_car', 'len_prox_a'}; +params = {cardiac_params{:}, arterial_params{:}}; +for param_no = 1 : length(params) + eval(['prescribed.' params{param_no} ' = nan(length(data.config.age),1);']) + eval(['simulated.' params{param_no} ' = nan(length(data.config.age),1);']) +end + +%% Extract prescribed and simulated values of each characteristic +for sim_no = 1 : length(data.config.age) + for param_no = 1 : length(params) + + curr_param = params{param_no}; + + % Extract simulated value of this parameter + if sum(strcmp(fieldnames(data.haemods), params{param_no})) + % if this parameter has already been extracted in the table_data + eval(['simulated.' curr_param '(sim_no) = data.haemods(sim_no).' curr_param ';']) + end + + % Extract prescribed value of this parameter + if sum(strcmp(lower(fieldnames(data.config)), lower(params{param_no}))) + eval(['prescribed.' curr_param '(sim_no) = data.config.' lower(curr_param) '(sim_no);']) + rel_cols = find(~strcmp(lower(data.config.variations.param_names), lower(params{param_no}))); + eval(['prescribed.' curr_param '_rel(sim_no) = sum(abs(data.config.variations.params(sim_no,rel_cols)))==0;']) + %eval(['prescribed.' curr_param '_base(sim_no) = sum(abs(data.config.variations.params(sim_no)))==0;']) + else + eval(['prescribed.' curr_param '(sim_no) = data.config.desired_chars.' lower(curr_param) '(sim_no);']) + rel_param_name = strrep(curr_param, 'PWV_cf', 'pwv'); + rel_param_name = strrep(rel_param_name, 'PWV_br', 'pwv'); + rel_param_name = strrep(rel_param_name, 'PWV_fa', 'pwv'); + rel_param_name = strrep(rel_param_name, 'dia_asc_a', 'dia'); + rel_param_name = strrep(rel_param_name, 'dia_desc_thor_a', 'dia'); + rel_param_name = strrep(rel_param_name, 'dia_abd_a', 'dia'); + rel_param_name = strrep(rel_param_name, 'dia_car', 'dia'); + rel_param_name = strrep(rel_param_name, 'len_prox_a', 'len'); + rel_cols = find(~strcmp(data.config.variations.param_names, rel_param_name)); + eval(['prescribed.' curr_param '_rel(sim_no) = sum(abs(data.config.variations.params(sim_no,rel_cols)))==0;']) + %eval(['prescribed.' curr_param '_base(sim_no) = sum(abs(data.config.variations.params(sim_no,:)))==0;']) + end + + end +end + +%% Make plots of simulated characteristics + +ftsize = 20; lwidth = 2; +paper_size = [500,350]; + +for param_no = 1 : length(params) + + % extract data for this param + curr_param = params{param_no}; + [~, units] = make_param_label(curr_param); + eval(['rel_data.p = prescribed.' curr_param ';']); + eval(['rel_data.p_rel = prescribed.' curr_param '_rel;']); + eval(['rel_data.s = simulated.' curr_param ';']); + + % find mean and std of parameter at each age + unique_ages = unique(data.config.age); + for age_no = 1 : length(unique_ages) + if only_baseline_sims + rel_els = ages == unique_ages(age_no) & rel_data.p_rel(:); + else + rel_els = ages == unique_ages(age_no); + end + rel_data.p_mean(age_no) = mean(rel_data.p(rel_els)); + rel_data.p_std(age_no) = std(rel_data.p(rel_els)); + rel_data.s_mean(age_no) = mean(rel_data.s(rel_els)); + rel_data.s_std(age_no) = std(rel_data.s(rel_els)); + end + + % make prescribed change with age plot + plot(unique_ages, rel_data.p_mean, 'o-k', 'LineWidth', lwidth, 'MarkerSize', 7, 'MarkerFaceColor', 'k', 'MarkerEdgeColor', 'k'), hold on + plot(unique_ages, rel_data.p_mean - rel_data.p_std, '--k', 'LineWidth', lwidth) + plot(unique_ages, rel_data.p_mean + rel_data.p_std, '--k', 'LineWidth', lwidth) + + temp.min = min(rel_data.p(:)); + temp.max = max(rel_data.p(:)); + temp.range = temp.max-temp.min; + lims = [floor(temp.min-0.1*temp.range), ceil(temp.max+0.1*temp.range)]; clear temp + if length(unique(lims)) == 1 + lims = [lims(1)-1 lims(2)+1]; + end + + % tidy-up + xlim([min(unique_ages)-5, max(unique_ages)+5]) + ylim(lims) + xlabel('Age [yrs]', 'FontSize', ftsize) + set(gca, 'FontSize', ftsize) + title([strrep(curr_param,'_', ' '), ' [', units,']'], 'FontSize', ftsize) + + % save + PrintFigs(gcf, paper_size/70, [PATHS.Analysis_figures, 'pres_', curr_param]) + +end + +%% Make plots of prescribed vs simulated characteristics + +ftsize = 20; lwidth = 2; +paper_size = [1200,350]; +only_baseline_sims = false; + +for param_no = 1 : length(params) + + % extract data for this param + curr_param = params{param_no}; + [~, units] = make_param_label(curr_param); + eval(['rel_data.p = prescribed.' curr_param ';']); + eval(['rel_data.p_rel = prescribed.' curr_param '_rel;']); + eval(['rel_data.s = simulated.' curr_param ';']); + + % make scatter plot + figure('Position', [20,20,paper_size]) + subplot(1,3,1) + plot([0,10000],[0,10000], '--k'), hold on % line of identity + plot(rel_data.p, rel_data.s, 'xk', 'LineWidth', lwidth, 'MarkerSize', 13) + + % tidy-up + temp.min = min([rel_data.p(:); rel_data.s(:)]); + temp.max = max([rel_data.p(:); rel_data.s(:)]); + temp.range = temp.max-temp.min; + lims = [floor(temp.min-0.1*temp.range), ceil(temp.max+0.1*temp.range)]; clear temp + if length(unique(lims)) == 1 + lims = [lims(1)-1 lims(2)+1]; + end + xlim(lims) + ylim(lims) + xlabel('Prescribed', 'Color', 'b', 'FontSize', ftsize) + ylabel('Simulated', 'Color', 'r', 'FontSize', ftsize) + set(gca, 'FontSize', ftsize) + title([strrep(curr_param,'_', ' '), ' [', units,']'], 'FontSize', ftsize) + + % find mean and std of parameter at each age + unique_ages = unique(ages); + for age_no = 1 : length(unique_ages) + if only_baseline_sims + rel_els = ages == unique_ages(age_no) & rel_data.p_rel(:); + else + rel_els = ages == unique_ages(age_no); + end + rel_data.p_mean(age_no) = mean(rel_data.p(rel_els)); + rel_data.p_std(age_no) = std(rel_data.p(rel_els)); + rel_data.s_mean(age_no) = mean(rel_data.s(rel_els)); + rel_data.s_std(age_no) = std(rel_data.s(rel_els)); + end + + % make prescribed change with age plot + subplot(1,3,2) + plot(unique_ages, rel_data.p_mean, 'o-b', 'LineWidth', lwidth, 'MarkerSize', 7, 'MarkerFaceColor', 'b', 'MarkerEdgeColor', 'b'), hold on + plot(unique_ages, rel_data.p_mean - rel_data.p_std, '--b', 'LineWidth', lwidth) + plot(unique_ages, rel_data.p_mean + rel_data.p_std, '--b', 'LineWidth', lwidth) + + % tidy-up + xlim([min(unique_ages)-5, max(unique_ages)+5]) + ylim(lims) + xlabel('Age [yrs]', 'FontSize', ftsize) + ylabel([strrep(curr_param,'_', ' '), ' [', units,']'], 'FontSize', ftsize) + set(gca, 'FontSize', ftsize) + title('Prescribed', 'Color', 'b', 'FontSize', ftsize) + + % make simulated change with age plot + subplot(1,3,3) + plot(unique_ages, rel_data.s_mean, 'o-r', 'LineWidth', lwidth, 'LineWidth', lwidth, 'MarkerSize', 7, 'MarkerFaceColor', 'r', 'MarkerEdgeColor', 'r'), hold on + plot(unique_ages, rel_data.s_mean - rel_data.s_std, '--r', 'LineWidth', lwidth) + plot(unique_ages, rel_data.s_mean + rel_data.s_std, '--r', 'LineWidth', lwidth) + + % tidy-up + xlim([min(unique_ages)-5, max(unique_ages)+5]) + ylim(lims) + xlabel('Age [yrs]', 'FontSize', ftsize) + ylabel([strrep(curr_param,'_', ' '), ' [', units,']'], 'FontSize', ftsize) + set(gca, 'FontSize', ftsize) + title('Simulated', 'Color', 'r', 'FontSize', ftsize) + + % save + PrintFigs(gcf, paper_size/70, [PATHS.Analysis_figures, 'sim_vs_pres_', curr_param]) + +end + + +end + +function make_baseline_waves_figure(PATHS, sim_no) + +% load data +load(PATHS.exported_data_mat_pwdb_data) + +% Setup figure for Pressure and Flow vel +paper_size = [350, 600]; +figure('Position', [20,20,paper_size]) +fig_settings.lwidth = 2; +fig_settings.ftsize = 12; +fig_settings.req_sites = {'Carotid', 'AorticRoot', 'Brachial', 'Radial', 'Digital', 'Femoral', 'AntTibial'}; +fig_settings.sig_types = {'P', 'U'}; +fig_settings.colors = {'r', 'r'}; +fig_settings.ylims = {[60,125], [-0.15, 0.75]}; + +% Plot +plot_baseline_signals(fig_settings, data) + +% Save figure +PrintFigs(gcf, paper_size/70, PATHS.baseline_waves_fig_a) + +% Setup figure for PPG and Area +figure('Position', [20,20,paper_size]) +fig_settings.req_sites = {'SupTemporal', 'Carotid', 'Brachial', 'Radial', 'Digital', 'Femoral', 'AntTibial'}; +fig_settings.sig_types = {'A', 'PPG'}; +fig_settings.colors = {'b', 'b'}; +fig_settings.ylims = {'auto', [0, 1.1]}; + +% Plot +plot_baseline_signals(fig_settings, data) + +% Save figure +PrintFigs(gcf, paper_size/70, PATHS.baseline_waves_fig_b) + +end + +function make_simulated_vs_literature_figure(PATHS) + +fprintf('\n - Making simulated vs literature figure') + +only_baseline_sims = true; + +% Load data +load(PATHS.exported_data_mat_pwdb_data) +ages = data.config.age; + +% Simulated characteristics +cardiac_params = {'CO'}; +arterial_params = {'DBP_a', 'AP_a', 'SBP_b', 'DBP_b', 'PP_b', 'MBP_b', 'SBP_a', 'PP_a', 'PP_amp', 'AI_a', 'Tr_a'}; +params = {cardiac_params{:}, arterial_params{:}}; + +%% Extract literature values of each characteristic +for param_no = 1 : length(params) + + curr_param = params{param_no}; + + % Extract literature values of this parameter + switch curr_param + case 'CO' % Taken from Le2016 (male data, Table 2) + literature_data.age = 25:10:65; + literature_data.mean = [6.6, 6.2, 5.8, 5.4, 5.0]; + literature_data.sd = [8.5-4.65, 8.1-4.25, 7.7-3.85, 7.3-3.45, 6.9-3.05]./(2*1.96); + case 'SBP_b' % taken from McEniery2005 (male data, Table 1) + literature_data.age = 15:10:85; + literature_data.mean = [123, 124, 123, 125, 125, 126, 127, 130]; + literature_data.sd = [10,10,9,9,9,9,9,8]; + case 'DBP_a' % taken from McEniery2005 (male data, Table 1) + %%%%%%%%%%%%%% THIS IS BRACHIAL RATHER THAN AORTIC DATA %%%%%%% + literature_data.age = 15:10:85; + literature_data.mean = [73,75,77,79,79,78,76,75]; + literature_data.sd = [8,10,9,9,9,9,9,8]; + case 'DBP_b' % taken from McEniery2005 (male data, Table 1) + literature_data.age = 15:10:85; + literature_data.mean = [73,75,77,79,79,78,76,75]; + literature_data.sd = [8,10,9,9,9,9,9,8]; + case 'PP_b' % taken from McEniery2005 (male data, Table 1) + literature_data.age = 15:10:85; + literature_data.mean = [50,49,47,46,46,49,51,55]; + literature_data.sd = [9,9,8,7,8,8,8,9]; + case 'MBP_b' % taken from McEniery2005 (male data, Table 1) + literature_data.age = 15:10:85; + literature_data.mean = [88,89,92,95,95,94,93,92]; + literature_data.sd = [8,8,8,7,7,7,7,8]; + case 'SBP_a' % taken from McEniery2005 (male data, Table 1) + literature_data.age = 15:10:85; + literature_data.mean = [103,105,109,113,115,117,118,120]; + literature_data.sd = [8,8,9,9,9,9,9,8]; + case 'PP_a' % taken from McEniery2005 (male data, Table 1) + literature_data.age = 15:10:85; + literature_data.mean = [29,30,31,34,35,39,42,45]; + literature_data.sd = [5,6,6,6,7,7,7,9]; + case 'PP_amp' % taken from McEniery2005 (male data, Table 1) + literature_data.age = 15:10:85; + literature_data.mean = [1.72, 1.7 , 1.50, 1.39, 1.33, 1.26, 1.24, 1.25]; + literature_data.sd = [0.11, 0.14, 0.18, 0.15, 0.16, 0.13, 0.12, 0.15]; + case 'AP_a' % taken from McEniery2005 (male data, Table 1) + % This is aortic rather than carotid data + literature_data.age = 15:10:85; + literature_data.mean = [-1,1,4,7,9,11,13,14]; + literature_data.sd = [3,4,5,4,5,5,5,5]; + case 'AI_a' % taken from McEniery2005 (male data, Table 1) + % This is aortic rather than carotid data + literature_data.age = 15:10:85; + literature_data.mean = [-2,2,12,19,24,28,30,30]; + literature_data.sd = [8,11,13,10,10,9,9,10]; + case 'Tr_a' % taken from McEniery2005 (male data, Table 1) + literature_data.age = 15:10:85; + literature_data.mean = [150,154,151,148,143,141,136,133]; + literature_data.sd = [17,21,21,16,15,12,12,16]; + end + + % store literature values + eval(['literature.' curr_param ' = literature_data;']); + + % Extract simulated values + simulated_data.age = unique(data.config.age(:)'); + for age_no = 1 : length(simulated_data.age) + curr_age = simulated_data.age(age_no); + rel_els = data.config.age == curr_age & data.plausibility.plausibility_log; + param_data = extractfield(data.haemods, curr_param); + rel_vals = param_data(rel_els); clear param_data rel_els curr_age + %%%%%%%%%%%%% THIS IS IGNORING NANs %%%%%%%%%%%%%%%% + simulated_data.mean(age_no) = mean(rel_vals(~isnan(rel_vals))); + simulated_data.sd(age_no) = std(rel_vals(~isnan(rel_vals))); + clear rel_vals + end + clear age_no + + % store simualted values + eval(['simulated.' curr_param ' = simulated_data;']); + + clear literature_data simulated_data +end + +%% Make plots of literature vs simulated characteristics +up.ylim_offset = 0.1; +req_color = [0,0,0]; +age_ticks = 20:10:80; +ftsize = 22; lwidth = 2; + +for param_no = 1 : length(params) + + curr_param = params{param_no}; + eval(['literature_data = literature.' curr_param ';']) + eval(['simulated_data = simulated.' curr_param ';']) + + paper_size = [900,400]; + figure('Position', [100,100,paper_size]) + subplot('Position', [0.12,0.16,0.38,0.72]) + + % Find ylims + temp(1) = min([literature_data.mean-literature_data.sd, simulated_data.mean-simulated_data.sd]); + temp(2) = max([literature_data.mean+literature_data.sd, simulated_data.mean+simulated_data.sd]); + rel_ylims(1) = temp(1) - 0.1*(range(temp)); + rel_ylims(2) = temp(2) + 0.1*(range(temp)); + + % - Literature + + % plot SD + no_sd = 1; + plot_sds(literature_data.age, literature_data.mean, literature_data.sd, no_sd, req_color, up); + hold on + + % plot mean value + plot(literature_data.age, literature_data.mean, 'LineWidth', lwidth, 'Color', req_color), hold on, + + % tidy up + [~, unit, abbr, ~, graph_title_no_units] = make_param_label(curr_param); + unit = strrep(unit, '%%', '%'); + abbr = strrep(abbr, 'PP_{amp}', 'abc'); + temp = strfind(abbr, '_'); + if ~isempty(temp), abbr = abbr(1:temp-1); end + abbr = strrep(abbr, 'abc', 'PP_{amp}'); + xlabel('Age [years]', 'FontSize', ftsize) + ylab = ylabel([abbr, ' [', unit, ']'], 'FontSize', ftsize); + set(ylab, 'Units', 'Normalized', 'Position', [-0.15, 0.5, 0]); + set(gca, 'FontSize', ftsize, 'XTick', age_ticks) + ylim(rel_ylims); + xlim([20,80]) + grid on + box off + + % - Simulated + subplot('Position', [0.59,0.16,0.38,0.72]) + + % plot SD + no_sd = 1; + plot_sds(simulated_data.age, simulated_data.mean, simulated_data.sd, no_sd, req_color, up); + hold on + + % plot mean value + plot(simulated_data.age, simulated_data.mean, 'o-', 'LineWidth', lwidth, 'Color', req_color), hold on, + + % tidy up + xlabel('Age [years]', 'FontSize', ftsize) + set(gca, 'FontSize', ftsize, 'XTick', age_ticks) + ylim(rel_ylims); + xlim([20,80]) + grid on + box off + + % - title + str = graph_title_no_units; + dim = [0.2,0.7,0.6,0.3]; + annotation('textbox',dim,'String',str,'LineStyle', 'none', 'FontSize', ftsize+8, 'HorizontalAlignment', 'center'); + + % save + PrintFigs(gcf, paper_size/70, [PATHS.Analysis_figures, 'lit_vs_sim_', curr_param]) + +end + +end + +function make_parameters_characteristics_figure(PATHS) + +fprintf('\n - Making characteristics vs parameters figures') + + +% load data +load(PATHS.exported_data_mat_pwdb_data) + +% identify baseline simulation for baseline age +baseline_sim_no = find(data.config.baseline_sim_for_all); +baseline_age = data.config.age(baseline_sim_no); + +% for each parameter, identify simulations where only that parameter changed without anything else changing. +all_params = data.config.variations.params; +param_names = data.config.variations.param_names; + +% add age to list of parameters +param_names = [{'age'}; param_names]; +all_params = [zeros(size(all_params,1),1), all_params]; + +% find relevant simulations for each parameter +[rel_sims, param_variations] = deal(cell(length(param_names),1)); +for param_no = 1 : length(param_names) + columns_for_other_params = setxor(1:length(param_names), param_no); + temp = all_params(:,columns_for_other_params); + if ~strcmp(param_names{param_no}, 'age') + rel_sims{param_no} = find(~any(temp,2) & data.config.age == baseline_age); + else + rel_sims{param_no} = find(~any(temp,2)); + end + param_variations{param_no} = all_params(rel_sims{param_no},param_no); +end +clear temp + +%% Make plots of parameters vs characteristics + +% Simulated characteristics +cardiac_chars = {'CO'}; +arterial_chars = {'PWV_a', 'MBP_drop_finger', 'MBP_drop_ankle', 'SBP_b', 'DBP_b', 'PP_b', 'MBP_b', 'SBP_a', 'PP_a', 'AP_a', 'PP_amp', 'AI_a', 'Tr_a'}; +resultant_chars = {cardiac_chars{:}, arterial_chars{:}}; + +% cycle through input parameters +for param_no = 1 : length(param_names) + curr_param = param_names{param_no}; + + % rel sims + curr_rel_sims = rel_sims{param_no}; + + if length(curr_rel_sims) < 2 + continue + end + + % extract data for this parameter + curr_param_vals = nan(length(curr_rel_sims),1); + eval(['curr_param_vals = data.config.' curr_param '(curr_rel_sims);']); + true_val = true; + + % make plot of characteristic vs parameter + + % cycle through simulated characteristics + paper_size = [200,200,700,300]; + for res_char_no = 1 : length(resultant_chars) + curr_res_char = resultant_chars{res_char_no}; + + % extract data for this characteristic + eval(['all_char_values = extractfield(data.haemods, ''' curr_res_char ''');']); + char_values = all_char_values(curr_rel_sims); + + % sort according to param values + [new_curr_param_vals, order] = sort(curr_param_vals); + new_char_values = char_values(order); clear order char_values + + % make plot of characteristic vs parameter + up.ylim_offset = 0.1; + req_color = [0,0,0]; + age_ticks = 20:10:80; + ftsize = 22; lwidth = 2; + paper_size = [550,400]; + figure('Position', [100,100,paper_size]) + subplot('Position', [0.2,0.2,0.77,0.76]) + + plot(new_curr_param_vals, new_char_values, 'o-', 'MarkerSize', 7, 'MarkerFaceColor', req_color, 'LineWidth', lwidth, 'Color', req_color) + if range(all_char_values) == 0 + temp = 0.05*unique(all_char_values); + else + temp = 0.1*range(all_char_values); + end + ylim([min(all_char_values)-temp, max(all_char_values)+temp]) + + % tidy up + [~, unit, abbr, label] = make_param_label(curr_param); + if true_val + x_label_text = label; + else + temp = strfind(label, '['); + x_label_text = [label(1:temp-2), ' [no SDs]']; + end + xlabel(x_label_text, 'FontSize', ftsize) + [~, unit, abbr, label] = make_param_label(curr_res_char); + ylab = ylabel(label, 'FontSize', ftsize); + set(ylab, 'Units', 'Normalized', 'Position', [-0.13, 0.5, 0]); + set(gca, 'FontSize', ftsize) + grid on + + % save + PrintFigs(gcf, paper_size/70, [PATHS.Analysis_figures, 'param_', curr_param, '_vs_char_', curr_res_char]) + + clear new* + end + + clear curr_rel_sims res_char_no curr_res_param char_values true_val curr_param_vals rel_col rel_sim_no +end + +end + +function make_ppg_estimation_figure(PATHS) + +fprintf('\n - Making PPG estimation figure') + +% load data +load(PATHS.exported_data_mat_pwdb_data) + +% identify baseline simulation for baseline age +baseline_sim_no = find(data.config.baseline_sim_for_all); +baseline_age = data.config.age(data.config.baseline_sim_for_all); + + +%% Make plots of waves vs parameters + +% Setup plotting +rel_sites = {'Carotid', 'Radial', 'Digital'}; +ftsize = 24; +lwidth = 2; +offset = 0; +paper_size = [550,350]; + +% make plots for each wave measurement site +for site_no = 1 : length(rel_sites) + curr_site = rel_sites{site_no}; + artery_name = find_artery_name(curr_site); % use PPG names + + % Make figure + figure('Position', [20,20, paper_size]) + subplot('Position', [0.08,0.19,0.90,0.75]) + + leg_labels = {}; max_t = 0; + units = 'normalised'; + + % Plot each of the waves in turn (corresponding to the three ages) + colors = [0,0,0]; + + % extract data to plot + eval(['curr.ppg = data.waves.PPG_' curr_site '{baseline_sim_no};']); + eval(['curr.p = data.waves.P_' curr_site '{baseline_sim_no};']); + curr.fs = data.waves.fs; + curr.t = [0:length(curr.p)-1]/curr.fs; + + % plot + curr.p = (curr.p - min(curr.p))/range(curr.p); + curr.ppg = (curr.ppg - min(curr.ppg))/range(curr.ppg); + plot(curr.t, curr.p, '--', 'Color', colors(1,:), 'LineWidth', lwidth), hold on + plot(curr.t, curr.ppg +offset, 'Color', colors(1,:), 'LineWidth', lwidth), hold on + ylim([-0.1 1.1+offset]); + set(gca, 'YTick', []) + + % store legend label + leg_labels = {'Pressure', 'PPG'}; + max_t = max(curr.t); + + % tidy up + xlim([0, max_t]) + xlabel('Time [s]', 'FontSize', ftsize) + ylab = ylabel('Pulse Waves [norm.]', 'FontSize', ftsize); + %ylab = ylabel({curr_wave_type, ['[' units ']']}, 'FontSize', ftsize, 'Rotation', 0); + %set(ylab, 'Units', 'Normalized', 'Position', [-0.17, 0.5, 0]); + set(gca, 'FontSize', ftsize) + legend(leg_labels), clear leg_labels + dim = [0.15,0.7,0.7,0.3]; + annotation('textbox',dim,'String',artery_name,'LineStyle', 'none', 'FontSize', ftsize, 'HorizontalAlignment', 'center'); + box off + + % save + PrintFigs(gcf, paper_size/70, [PATHS.Analysis_figures, 'estimate_PPG_at_' strrep(artery_name, ' ', '_')]) + +end +clear curr_rel_sims res_char_no curr_res_param char_values true_val curr_param_vals rel_col rel_sim_no + +end + +function make_gamma_plots(PATHS) + +fprintf('\n - Making gamma plots') + +ftsize = 24; +lwidth = 2; +offset = 0.25; +paper_size = [600,400]; + +% load data +load(PATHS.exported_data_mat_pwdb_data) + +rel_sims = find(data.config.baseline_sim_for_all); + +% Make figure +figure('Position', [20,20, paper_size]) + +for sim_no = 1 : length(rel_sims) + + curr_sim_no = rel_sims(sim_no); + + % extract input data + in = data.config.constants; + r = mean([data.config.network.inlet_radius(curr_sim_no,:); data.config.network.outlet_radius(curr_sim_no,:)]); + r = sort(r); + a = pi*r.^2; + gamma = 0.001*((in.gamma_b1(curr_sim_no)./(100*2*r))+in.gamma_b0(curr_sim_no))./a; + + % plot + plot(2*r/100,gamma, 'LineWidth', lwidth), hold on, + + % tidy up + xlabel('Diameter [cm]', 'FontSize', ftsize) + ylab = ylabel('Gamma', 'FontSize', ftsize); + set(gca, 'FontSize', ftsize) + +end + +% save +PrintFigs(gcf, paper_size/70, [PATHS.Analysis_figures, 'gamma']) + +end + +function make_pressure_area_plots(PATHS) + +fprintf('\n - Making pressure-area plots') + +%% Mynard data + +% Import waves from Mynard's article +loadpath = '/Users/petercharlton/Google Drive/Work/Code/nektar/Mynard2015_data/ABME2015data.mat'; +load(loadpath); + +% Setup plotting +rel_domains = [1,15,21,22,42, 46, 49, 87]; +rel_sites = {'AorticRoot', 'Carotid', 'Brachial', 'Radial', 'CommonIliac', 'Femoral', 'AntTibial', 'SupTemporal', 'Digital'}; +ftsize = 24; +lwidth = 2; +offset = 0.25; +paper_size = [600,400]; +% +% % make plots for each measurement site +% +% for domain_no = 1 : length(rel_domains) +% curr_domain_no = rel_domains(domain_no); +% artery_name = find_artery_name(curr_domain_no); +% +% % Make figure +% figure('Position', [20,20, paper_size]) +% +% % extract relevant wave from Mynard's data +% lit_wave.t = a115lb.t; +% lit_wave.fs = 1000; +% switch curr_domain_no +% case 1 +% mynard_name = 'AoRt'; +% case 15 +% mynard_name = 'Lcar'; +% case 21 +% mynard_name = 'LBrach'; +% case 22 +% mynard_name = 'LRadI'; +% case 42 +% mynard_name = 'LInIl'; +% case 46 +% mynard_name = 'Lfem'; +% case 49 +% mynard_name = 'LATib'; +% case 87 +% mynard_name = 'LSupTemp'; +% case 112 +% mynard_name = 'AoRt'; +% end +% wave_el = find(strcmp(a115lb.monitor.name, mynard_name)); +% lit_wave.p = a115lb.tnode.p(:,wave_el)/1333.3; +% lit_wave.a = a115lb.tnode.A(:,wave_el); +% +% % Find best fit line +% f=fit(lit_wave.p,lit_wave.a,'poly1'); +% fit_line = feval(f,lit_wave.p); +% +% % plot +% plot(lit_wave.p,fit_line, '--r', 'LineWidth', lwidth), hold on, +% plot(lit_wave.p, lit_wave.a, 'b', 'LineWidth', lwidth), hold on +% +% % tidy up +% xlabel('Pressure [mmHg]', 'FontSize', ftsize) +% ylab = ylabel('Area [cm^2]', 'FontSize', ftsize); +% set(gca, 'FontSize', ftsize) +% title(artery_name, 'FontSize', ftsize+4) +% +% % legend +% legend({'Best fit line', 'Experimental'}, 'Location', 'SouthEast') +% +% % save +% PrintFigs(gcf, paper_size/70, [PATHS.ProcessedData, 'Mynard_p_a_', strrep(artery_name, ' ', '_')]) +% +% end +% clear a115lb + + + +%% Our data + +% load data +load(PATHS.exported_data_mat_pwdb_data) + +% identify baseline simulation for baseline age +baseline_sim_no = find(data.config.baseline_sim_for_all); + +% make plots for each measurement site +for site_no = 1 : length(rel_sites) + curr_site = rel_sites{site_no}; + + % Make figure + figure('Position', [20,20, paper_size]) + + % extract data to plot + eval(['wave.p = data.waves.P_' curr_site '{baseline_sim_no};']); + eval(['wave.a = data.waves.A_' curr_site '{baseline_sim_no}*(100^2);']); % convert from m2 to cm2 + + % Find best fit line + f=fit(wave.p,wave.a,'poly1'); + fit_line = feval(f,wave.p); + + % plot + plot(wave.p,fit_line, '--r', 'LineWidth', lwidth), hold on, + plot(wave.p, wave.a, 'b', 'LineWidth', lwidth), hold on + + % tidy up + xlabel('Pressure [mmHg]', 'FontSize', ftsize) + ylab = ylabel('Area [cm^2]', 'FontSize', ftsize); + set(gca, 'FontSize', ftsize) + title(curr_site, 'FontSize', ftsize+4) + + % legend + legend({'Best fit line', 'Experimental'}, 'Location', 'SouthEast') + + % save + PrintFigs(gcf, paper_size/70, [PATHS.Analysis_figures, 'Simulated_p_a_', curr_site]) + +end + +end + +function make_parameters_waves_figure(PATHS) + +fprintf('\n - Making waves vs parameters figures') + +% load data +load(PATHS.exported_data_mat_pwdb_data) + +% identify baseline simulation for baseline age +baseline_sim_no = find(data.config.baseline_sim_for_all); +baseline_age = data.config.age(baseline_sim_no); + +% for each parameter, identify simulations where only that parameter changed without anything else changing. +all_params = data.config.variations.params; +param_names = data.config.variations.param_names; + +% add age to list of parameters +param_names = [{'age'}; param_names]; +all_params = [zeros(size(all_params,1),1), all_params]; + +% find relevant simulations for each parameter +[rel_sims, param_variations] = deal(cell(length(param_names),1)); +for param_no = 1 : length(param_names) + columns_for_other_params = setxor(1:length(param_names), param_no); + temp = all_params(:,columns_for_other_params); + if ~strcmp(param_names{param_no}, 'age') + rel_sims{param_no} = find(~any(temp,2) & data.config.age == baseline_age); + else + rel_sims{param_no} = find(~any(temp,2)); + end + param_variations{param_no} = all_params(rel_sims{param_no},param_no); +end +clear temp + +%% Make plots of waves vs parameters + +% Setup plotting +wave_types = {'Q', 'A', 'PPG', 'U', 'P'}; +rel_sites.P = {'AorticRoot', 'Carotid', 'Brachial', 'Radial', 'Femoral', 'Digital', 'SupMidCerebral'}; +rel_sites.PPG = {'Digital', 'Carotid', 'Brachial', 'Radial', 'SupTemporal'}; +rel_sites.U = {'AorticRoot', 'Digital', 'Carotid', 'Brachial', 'Radial', 'Femoral'}; +rel_sites.Q = {'AorticRoot', 'Carotid', 'SupMidCerebral'}; +rel_sites.A = {'AorticRoot', 'Carotid'}; +ftsize = 20; +lwidth = 2; +plot_model_data_normalised = false; +offset = 0.25; +paper_size = [700,300]; + +% cycle through input parameters +for param_no = 1 : length(param_names) + curr_param = param_names{param_no}; + + % rel sims + curr_rel_sims = rel_sims{param_no}; + + % adjust to only give three waves for age +% if strcmp(curr_param, 'age') +% curr_rel_sims = [curr_rel_sims(1); curr_rel_sims(end)]; +% end + + if length(curr_rel_sims) < 2 & ~strcmp(curr_param, 'age') + continue + end + + % extract data for this parameter + eval(['curr_param_vals = data.config.' curr_param '(curr_rel_sims);']); + + % order from high to low + [curr_param_vals, order] =sort(curr_param_vals, 'descend'); + curr_rel_sims = curr_rel_sims(order); + + % make plot of wave vs parameter + + % make plots for each wave type and each measurement site + for wave_type_no = 1 : length(wave_types) + + curr_wave_type = wave_types{wave_type_no}; + eval(['rel_wave_sites = rel_sites.' curr_wave_type ';']) + + for site_no = 1 : length(rel_wave_sites) + curr_site = rel_wave_sites{site_no}; + + % check that this site has been exported + temp = fieldnames(data.waves); + if ~sum(~cellfun(@isempty,strfind(temp, curr_site))) + continue + end + + if strcmp(curr_wave_type, 'PPG') + artery_name = find_artery_name(curr_site); % use PPG names + else + artery_name = curr_site; + end + + %% Figure showing baseline wave + + if strcmp(curr_param, 'age') + + % Make figure + if strcmp(curr_wave_type, 'Q') && strcmp(curr_site, 'AorticRoot') + paper_size = [400,300]; + ftsize = 24; + axis_ftsize = 20; + else + paper_size = [500,300]; + ftsize = 32; + axis_ftsize = 24; + end + figure('Position', [20,20, paper_size]) + + % Plot each of the waves in turn (corresponding to the three ages) + rel_sim_no = curr_rel_sims(curr_param_vals == baseline_age); + + % extract data to plot + if strcmp(curr_wave_type, 'Q') + eval(['curr_wav.u = data.waves.U_' curr_site '{rel_sim_no};']); + eval(['curr_wav.a = data.waves.A_' curr_site '{rel_sim_no};']); + curr_wav.v = (1e6)*curr_wav.u.*curr_wav.a; + units = 'ml/s'; % converted from 'm3/s'; + elseif strcmp(curr_wave_type, 'A') + eval(['curr_wav.v = data.waves.' curr_wave_type '_' curr_site '{rel_sim_no};']); + curr_wav.v = (100*100)*curr_wav.v; + units = 'cm2'; % converted from 'm3/s'; + else + eval(['curr_wav.v = data.waves.' curr_wave_type '_' curr_site '{rel_sim_no};']); + eval(['units = data.waves.units.' curr_wave_type ';']) + end + units = strrep(units, '2', '^2'); + units = strrep(units, '3', '^3'); + curr_wav.fs = data.waves.fs; + curr_wav.t = [0:length(curr_wav.v)-1]/curr_wav.fs; + + % plot + plot(curr_wav.t, curr_wav.v, 'k', 'LineWidth', lwidth), hold on + + % tidy up + if ylim == [0 1] + ylim([-0.1 1.1]) + end + xlim([0, max(curr_wav.t)]) + xlabel('Time [s]', 'FontSize', ftsize) + ylab = ylabel([curr_wave_type, ' [' units ']'], 'FontSize', ftsize); + set(gca, 'FontSize', axis_ftsize) + box off + curr_range = range(curr_wav.v); + if ~strcmp(curr_wave_type, 'PPG') + ylim([min(curr_wav.v)-0.1*curr_range, max(curr_wav.v)+0.1*curr_range]) + else + ylim([0 1]) + end + + % annotate if aortic flow rate wave + if strcmp(curr_wave_type, 'Q') && strcmp(curr_site, 'AorticRoot') + + plot(curr_wav.t(end), curr_wav.v(end), 'ok', 'MarkerSize', 8), + + ylim([3*min(curr_wav.v), 1.2*max(curr_wav.v)]) + + % Shade areas + rel_els = 1 : (1+find(curr_wav.v(2:end)<0 & curr_wav.v(1:end-1)>=0, 1)); + patch([curr_wav.t(rel_els), flipud(curr_wav.t(rel_els))],[curr_wav.v(rel_els); zeros(length(rel_els),1)],[1,0.5,0.5], 'LineStyle', 'none') + rel_els = rel_els(end) : rel_els(end) + find(curr_wav.v(rel_els(end)+1:end-1)<0 & curr_wav.v(rel_els(end)+2:end)>=0); + patch([curr_wav.t(rel_els), flipud(curr_wav.t(rel_els))],[curr_wav.v(rel_els); zeros(length(rel_els),1)],[0.5,0.5,1], 'LineStyle', 'none') + +% % annotate parameters +% dim = [.30 .58 .1 .1]; +% str = 'SV'; +% annotation('textbox',dim,'String',str,'FitBoxToText','on', 'LineStyle', 'none', 'FontSize', ftsize-6); +% dim = [.41 .35 .1 .1]; +% str = 'RFV'; +% annotation('textbox',dim,'String',str,'FitBoxToText','on', 'LineStyle', 'none', 'FontSize', ftsize-6); +% +% annotation('doublearrow',[0.135,0.205],0.85*ones(1,2)) +% dim = [.135 .85 .1 .1]; +% str = 'PFT'; +% annotation('textbox',dim,'String',str,'FitBoxToText','on', 'LineStyle', 'none', 'FontSize', ftsize-6); +% +% dim = [.8 .35 .1 .1]; +% str = '60/HR'; +% annotation('textbox',dim,'String',str,'FitBoxToText','on', 'LineStyle', 'none', 'FontSize', ftsize-6); +% +% annotation('doublearrow',[0.135,0.395],0.25*ones(1,2)) +% dim = [.22 .24 .1 .1]; +% str = 'LVET'; +% annotation('textbox',dim,'String',str,'FitBoxToText','on', 'LineStyle', 'none', 'FontSize', ftsize-6); + + end + + % save + PrintFigs(gcf, paper_size/70, [PATHS.Analysis_figures, 'waves_', curr_wave_type, '_' artery_name, '_baseline']) + end + + if length(curr_rel_sims) < 2 & strcmp(curr_param, 'age') + continue + end + + %% Figure showing changes with parameter + + % Setup figure + paper_size = [700,300]; + ftsize = 20; + figure('Position', [20,20, paper_size]) + leg_labels = {}; max_t = 0; + + % Plot each of the waves in turn (corresponding to the three ages) + colors = linspace(0.3,0.7, length(curr_param_vals))'*ones(1,3); + colors = [0, 0, 1; 0, 0, 0; 1, 0, 0; 0.5, 0, 0; 0, 0, 0.5; 0.6, 0.6, 0.6]; + temp1 = linspace(0,1, length(curr_param_vals))'; + temp2 = linspace(0,0, length(curr_param_vals))'; + temp3 = linspace(1,0, length(curr_param_vals))'; + colors = [temp1,temp2,temp3]; + min_val = inf; max_val = -inf; + for sim_no = 1 : length(curr_param_vals) + rel_sim_no = curr_rel_sims(sim_no); + + % extract data to plot + if ~strcmp(curr_wave_type, 'Q') + eval(['curr_wav.v = data.waves.' curr_wave_type '_' curr_site '{rel_sim_no};']); + eval(['units = data.waves.units.' curr_wave_type ';']) + else + eval(['curr_wav.u = data.waves.U_' curr_site '{rel_sim_no};']); + eval(['curr_wav.a = data.waves.A_' curr_site '{rel_sim_no};']); + curr_wav.v = curr_wav.u.*curr_wav.a*1e6; + units = 'ml/s'; + end + + if plot_model_data_normalised + units = 'normalised'; + else + units = strrep(units, '2', '^2'); + units = strrep(units, '3', '^3'); + end + curr_wav.fs = data.waves.fs; + curr_wav.t = [0:length(curr_wav.v)-1]/curr_wav.fs; + + % plot + if ~plot_model_data_normalised + plot(curr_wav.t, curr_wav.v, 'Color', colors(sim_no,:), 'LineWidth', lwidth), hold on + if strcmp(curr_wave_type, 'U') || strcmp(curr_wave_type, 'Q') + plot(curr_wav.t(end), curr_wav.v(end), 'o', 'Color', colors(sim_no,:), 'LineWidth', lwidth, 'MarkerSize', 8,'HandleVisibility','off') + end + curr_min = min(curr_wav.v); + curr_max = max(curr_wav.v); + if curr_min < min_val, min_val = curr_min; end + if curr_max > max_val, max_val = curr_max; end + else + curr_wav.v = (curr_wav.v - min(curr_wav.v))/range(curr_wav.v); + plot(curr_wav.t, curr_wav.v +(offset*(param_val_no-1)), 'Color', colors(sim_no,:), 'LineWidth', lwidth), hold on + ylim([-0.1 1.1+(offset*(length(curr_param_vals)-1))]); + set(gca, 'YTick', []) + min_val = 0; max_val = 1; + end + + % store legend label + if strcmp(curr_param, 'lvet') + temp2 = round(curr_param_vals(sim_no)); + else + temp2 = curr_param_vals(sim_no); + end + if ~strcmp(curr_param, 'lvet') + leg_labels = [leg_labels, num2str(temp2, 2)]; + else + leg_labels = [leg_labels, num2str(temp2, 3)]; + end + max_t = max([max_t, max(curr_wav.t)]); + + end + + % tidy up + ylim([min_val - (0.05*(max_val-min_val)), max_val + (0.1*(max_val-min_val))]) + xlim([0, max_t]) + xlabel('Time [s]', 'FontSize', ftsize) + ylab = ylabel([curr_wave_type, ' [' units ']'], 'FontSize', ftsize); + set(gca, 'FontSize', ftsize) + leg_h = legend(leg_labels, 'Location', 'NorthEast'); + [label, units, abbr, graph_title, graph_title_no_units] = make_param_label(curr_param); + title(leg_h,[strrep(upper(strrep(curr_param, '_', ' ')), 'AGE', 'age'), ' (' units ')'],'FontWeight','Normal'); + clear temp + temp.upper_els = find(isstrprop(artery_name,'upper')); + if length(temp.upper_els)>1 + temp.artery_name = [artery_name(1:temp.upper_els(2)-1), ' ', artery_name(temp.upper_els(2):end)]; + else + temp.artery_name = artery_name; + end + title(['Changes in ' temp.artery_name, ' ', curr_wave_type ' with ' strrep(upper(strrep(curr_param, '_', ' ')), 'AGE', 'age')], 'FontSize', ftsize,'FontWeight','Normal') + clear temp leg_labels + box off + + % save + PrintFigs(gcf, paper_size/70, [PATHS.Analysis_figures, 'waves_', curr_wave_type, '_' strrep(artery_name, ' ', '_'), '_vs_', curr_param]) + + end + end + clear curr_rel_sims res_char_no curr_res_param char_values true_val curr_param_vals rel_col rel_sim_no +end + +end + +function make_wrist_ppg_parameters_figure(PATHS) + +fprintf('\n - Making PPG waves vs parameters figure') + +% load data +load(PATHS.exported_data_mat_pwdb_data) + +% identify baseline simulation for baseline age +baseline_sim_no = find(data.config.baseline_sim_for_all); +baseline_age = data.config.age(data.config.baseline_sim_for_all); + +% for each parameter, identify simulations where only that parameter changed without anything else changing. +all_params = data.config.variations.params; +param_names = data.config.variations.param_names; + +% add age to list of parameters +param_names = [{'age'}; param_names]; +all_params = [zeros(size(all_params,1),1), all_params]; + +% find relevant simulations for each parameter +[rel_sims, param_variations] = deal(cell(length(param_names),1)); +for param_no = 1 : length(param_names) + columns_for_other_params = setxor(1:length(param_names), param_no); + temp = all_params(:,columns_for_other_params); + if ~strcmp(param_names{param_no}, 'age') + rel_sims{param_no} = find(~any(temp,2) & data.config.age == baseline_age); + else + rel_sims{param_no} = find(~any(temp,2)); + end + param_variations{param_no} = all_params(rel_sims{param_no},param_no); +end +clear temp + +%% Make plots of waves vs parameters + +% Setup plotting +rel_sites = {'Radial'}; +ftsize = 10; +lwidth = 2; +offset = 0.25; +paper_size = [1000,300]; + +% Identify parameters I'm interested in +rel_param_els = ones(size(param_names)); +for s = 1 : length(param_names) + curr_param = param_names{s}; + if strcmp(curr_param, 'dbp') || ... + strcmp(curr_param, 'alpha') || ... + strcmp(curr_param, 'ht') || ... + strcmp(curr_param, 'mu') || ... + strcmp(curr_param, 'p_out') || ... + strcmp(curr_param, 'p_drop') || ... + strcmp(curr_param, 'reg_vol') || ... + strcmp(curr_param, 'rho') || ... + strcmp(curr_param, 't_pf') || ... + strcmp(curr_param, 'time_step') || ... + strcmp(curr_param, 'visco_elastic_log') || ... + strcmp(curr_param, 'age') + rel_param_els(s) = 0; + end + + % check there are variations for this parameter + curr_rel_sims = rel_sims{s}; + if length(curr_rel_sims) ==1 + rel_param_els(s) = 0; + end + clear curr_rel_sims +end + +% cycle through input parameters +done_a_plot = false; +for site_no = 1 : length(rel_sites) + counter_no = 0; + curr_site = rel_sites{site_no}; + + % make plot of wave vs parameter + figure('Position', [20,20, paper_size]) + + for param_no = 1 : length(param_names) + curr_param = param_names{param_no}; + + % skip params I'm not interested in + if ~rel_param_els(param_no) + continue + end + + % rel sims + curr_rel_sims = rel_sims{param_no}; + + if length(curr_rel_sims) < 2 + continue + end + + done_a_plot = true; + + % extract data for this parameter + eval(['curr_param_vals = data.config.' curr_param '(curr_rel_sims);']); + + % order from high to low + [curr_param_vals, order] =sort(curr_param_vals, 'descend'); + curr_rel_sims = curr_rel_sims(order); + + counter_no = counter_no+1; + subplot(2, ceil(sum(rel_param_els)/2), counter_no) + artery_name = find_artery_name(curr_site); % use PPG names + leg_labels = {}; max_t = 0; + units = data.waves.units.PPG; + + % Plot each of the waves in turn (corresponding to the three ages) + ylims = [inf, -inf]; + param_counter_no = 0; + for param_val_no = 1 : length(curr_param_vals) + rel_sim_no = curr_rel_sims(param_val_no); + + curr_param_val = curr_param_vals(param_val_no); + if curr_param_val == min(curr_param_vals) + curr_color = [0 0 1]; + elseif curr_param_val == max(curr_param_vals) + curr_color = [1,0,0]; + elseif curr_param_val == median(curr_param_vals) + curr_color = [0,0,0]; + else + continue + end + param_counter_no = param_counter_no+1; + + % extract data to plot + eval(['curr_wav.v = data.waves.PPG_' curr_site '{rel_sim_no};']); + curr_wav.fs = data.waves.fs; + curr_wav.t = [0:length(curr_wav.v)-1]/curr_wav.fs; + + % plot + plot(curr_wav.t, curr_wav.v, 'Color', curr_color, 'LineWidth', lwidth), hold on + + % store ylim info + curr_range = range(curr_wav.v); + ylims = [min([ylims(1), min(curr_wav.v)-0.1*curr_range]), ... + max([ylims(2), max(curr_wav.v)+0.1*curr_range])]; + + % store legend label + if strcmp(curr_param, 'lvet') + temp2 = round(curr_param_vals(param_val_no)); + else + temp2 = curr_param_vals(param_val_no); + end + leg_labels = [leg_labels, num2str(temp2, 2)]; + max_t = max([max_t, max(curr_wav.t)]); + + end + + % tidy up + ylim([-0.1 1.1]) + xlim([0, max_t]) + if counter_no > ceil(sum(rel_param_els)/2) + xlabel('Time [s]', 'FontSize', ftsize) + % elseif ~strcmp(curr_param, 'hr') + % set(gca, 'XTick', []) + end + % if counter_no <= length(wave_types) + % title([strrep(strrep(curr_wave_type, '_', ' '), ' WK', ''), ' [' units ']'], 'FontSize', ftsize); + % end + switch curr_param + case 'dia' + title_txt = 'Arterial Diameter'; + case 'hr' + title_txt = 'Heart Rate'; + case 'len' + title_txt = 'Aortic Length'; + case 'lvet' + title_txt = 'Duration of Systole'; + case 'mbp' + title_txt = 'Mean Blood Pressure'; + case 'pvc' + title_txt = 'Peripheral Compliance'; + case 'pwv' + title_txt = 'Arterial Stiffness'; + case 'sv' + title_txt = 'Stroke Volume'; + case 'gamma' + title_txt = 'Arterial Wall Viscosity'; + end + title(title_txt, 'FontSize', ftsize); + + % y label +% if counter_no <= ceil(sum(rel_param_els)/2) +% [label, units, abbr, graph_title] = make_param_label(curr_param); +% ylab = ylabel({abbr, ['[' units ']']}, 'FontSize', ftsize); +% set(ylab, 'Units', 'Normalized', 'Position', [-0.17, 0.5, 0]); +% end + + % tidy up + set(gca, 'FontSize', ftsize, 'YTick', []) + %legend(leg_labels, 'Location', 'NorthEast'), + clear leg_labels + box off + end + + % save + if done_a_plot + PrintFigs(gcf, paper_size/70, [PATHS.Analysis_figures, artery_name, '_ppg_waves_vs_params']) + end + + clear curr_rel_sims res_char_no curr_res_param char_values true_val curr_param_vals rel_col rel_sim_no + +end + +end + +function make_initial_parameters_waves_figure(PATHS) + +fprintf('\n - Making waves vs parameters figure') + +% load data +load(PATHS.exported_data_mat_pwdb_data) + +% identify baseline simulation for baseline age +baseline_sim_no = find(data.config.baseline_sim_for_all); +baseline_age = data.config.age(data.config.baseline_sim_for_all); + +% for each parameter, identify simulations where only that parameter changed without anything else changing. +all_params = data.config.variations.params; +param_names = data.config.variations.param_names; + +% add age to list of parameters +param_names = [{'age'}; param_names]; +all_params = [zeros(size(all_params,1),1), all_params]; + +% find relevant simulations for each parameter +[rel_sims, param_variations] = deal(cell(length(param_names),1)); +for param_no = 1 : length(param_names) + columns_for_other_params = setxor(1:length(param_names), param_no); + temp = all_params(:,columns_for_other_params); + if ~strcmp(param_names{param_no}, 'age') + rel_sims{param_no} = find(~any(temp,2) & data.config.age == baseline_age); + else + rel_sims{param_no} = find(~any(temp,2)); + end + param_variations{param_no} = all_params(rel_sims{param_no},param_no); +end +clear temp + +%% Make plots of waves vs parameters + +% Setup plotting +wave_types = {'U', 'P', 'PPG'}; +rel_sites = {'Carotid', 'Radial'}; +ftsize = 10; +lwidth = 2; +offset = 0.25; +paper_size = [400,1000]; + +% cycle through input parameters +no_rel_params = sum(cellfun(@length, param_variations)>=2); +for site_no = 1 : length(rel_sites) + counter_no = 0; + curr_site = rel_sites{site_no}; + + % make plot of wave vs parameter + figure('Position', [20,20, paper_size]) + done_plot = 0; + + for param_no = 1 : length(param_names) + curr_param = param_names{param_no}; + + % rel sims + curr_rel_sims = rel_sims{param_no}; + + if length(curr_rel_sims) < 2 + continue + end + done_plot = 1; + + % extract data for this parameter + eval(['curr_param_vals = data.config.' curr_param '(curr_rel_sims);']); + + % order from high to low + [curr_param_vals, order] =sort(curr_param_vals, 'descend'); + curr_rel_sims = curr_rel_sims(order); + + % make plots for each wave type and each measurement site + for wave_type_no = 1 : length(wave_types) + + counter_no = counter_no+1; + curr_wave_type = wave_types{wave_type_no}; + subplot(no_rel_params, length(wave_types), counter_no) + + if strcmp(curr_wave_type, 'PPG') + artery_name = find_artery_name(curr_site); % use PPG names + else + artery_name = curr_site; + end + + leg_labels = {}; max_t = 0; + + eval(['units = data.waves.units.' curr_wave_type ';']); + + % Plot each of the waves in turn (corresponding to the three ages) + colors = linspace(0.3,0.7, length(curr_param_vals))'*ones(1,3); + colors = [0, 0, 1; 0, 0, 0; 1, 0, 0; 0.5, 0, 0; 0, 0, 0.5; 0.4, 0.6, 0.4]; + ylims = [inf, -inf]; + for param_val_no = 1 : length(curr_param_vals) + rel_sim_no = curr_rel_sims(param_val_no); + + eval(['curr_wav.v = data.waves.' curr_wave_type '_' curr_site '{rel_sim_no};']); + curr_wav.fs = data.waves.fs; + curr_wav.t = [0:length(curr_wav.v)-1]/curr_wav.fs; + + % plot + plot(curr_wav.t, curr_wav.v, 'Color', colors(param_val_no,:), 'LineWidth', lwidth), hold on + if strcmp(curr_wave_type, 'U') && strcmp(curr_param, 'HR') + plot(curr_wav.t(end), curr_wav.v(end), 'o', 'Color', colors(param_val_no,:), 'LineWidth', lwidth, 'MarkerSize', 8,'HandleVisibility','off') + end + + % store ylim info + curr_range = range(curr_wav.v); + ylims = [min([ylims(1), min(curr_wav.v)-0.1*curr_range]), ... + max([ylims(2), max(curr_wav.v)+0.1*curr_range])]; + + % store legend label + if strcmp(curr_param, 'lvet') + temp2 = round(curr_param_vals(param_val_no)); + else + temp2 = curr_param_vals(param_val_no); + end + leg_labels = [leg_labels, num2str(temp2, 2)]; + max_t = max([max_t, max(curr_wav.t)]); + + end + + % tidy up + if strcmp(curr_wave_type, 'PPG') + ylim([-0.1 1.1]) + else + ylim(ylims) + if strcmp(curr_wave_type, 'U') + + end + end + xlim([0, max_t]) + set(gca, 'FontSize', ftsize-4) + if counter_no >= length(wave_types)*no_rel_params-2 + xlabel('Time [s]', 'FontSize', ftsize) + elseif ~strcmp(curr_param, 'hr') + set(gca, 'XTick', []) + end + if counter_no <= length(wave_types) + % Title + str = [curr_wave_type, ' [' units ']']; + dim = [-0.2+counter_no*0.285,0.81,0.3,0.15]; + annotation('textbox',dim,'String',str,'LineStyle', 'none', 'FontSize', ftsize, 'HorizontalAlignment', 'center'); + + end + + % y label + if rem(counter_no,length(wave_types)) == 1 + [label, units, abbr, graph_title] = make_param_label(curr_param); + abbr = strrep(abbr, '_a', ''); + abbr = strrep(abbr, 'Len', 'Length'); + abbr = strrep(abbr, 'Dia', 'Diam.'); + ylab = ylabel(abbr, 'FontSize', ftsize, 'Rotation', 0); + set(ylab, 'Units', 'Normalized', 'Position', [-0.38, 0.5, 0]); + end + + % tidy up + %legend(leg_labels, 'Location', 'NorthEast'), + clear leg_labels + box off + + end + end + + if done_plot + % save + PrintFigs(gcf, paper_size/70, [PATHS.Analysis_figures, 'waves_initial_variations_', strrep(artery_name, ' ', '_')]) + end + + clear curr_rel_sims res_char_no curr_res_param char_values true_val curr_param_vals rel_col rel_sim_no + + +end + +end + +function make_sensitivity_analysis_figures(PATHS) + +fprintf('\n - Making sensitivity analyses figures') + +% load data +load(PATHS.exported_data_mat_pwdb_data) + +% for each parameter, identify simulations where only that parameter changed without anything else changing. +all_params = data.config.variations.params; + +param_names = data.config.variations.param_names; +[rel_sims, param_variations, baseline_logs, baseline_sims, param_variations, param_values] = deal(cell(length(param_names),1)); +% cycle through each simulation input parameter +for param_no = 1 : length(param_names) + + % identify those columns which correspond to other parameters (i.e. not this one) + columns_for_other_params = setxor(1:length(param_names), param_no); + % extract variations corresponding to the other parameters + temp = all_params(:,columns_for_other_params); + % identify simulations in which none of these other parameters were varied from baseline values + rel_sims{param_no} = find(~any(temp,2)); + % skip this parameter if it was not varied at all from its baseline value + if length(rel_sims{param_no}) <= sum(data.config.baseline_sim_for_age) + continue + end + + % use all the simulations + rel_sims{param_no} = 1:length(data.config.age); + % setup variables + temp_baseline_vals = nan(length(rel_sims{param_no}),1); + temp_baseline_logs = false(length(rel_sims{param_no}),1); + % cycle through each simulation + for s = 1 : length(rel_sims{param_no}) + % identify age of this simulation + curr_sim = rel_sims{param_no}(s); + curr_age = data.config.age(curr_sim); + % extract baseline value of this parameter + temp_rel_baseline_age_sim = find(data.config.age == curr_age & data.config.baseline_sim_for_age); + eval(['temp_baseline_vals(s) = data.config.' param_names{param_no} '(temp_rel_baseline_age_sim);']); + % store the baseline simulation for this age + if temp_rel_baseline_age_sim == curr_sim + temp_baseline_logs(s) = true; + end + temp_baseline_sims(s) = temp_rel_baseline_age_sim; + end + % store details of the baseline simulations corresponding to each simulation + baseline_logs{param_no} = temp_baseline_logs; clear temp_baseline_logs + baseline_sims{param_no} = temp_baseline_sims; clear temp_baseline_sims + baseline_vals{param_no} = temp_baseline_vals; clear temp_baseline_vals + % store the variations for this parameter (in number of SDs from age-specific mean) + param_variations{param_no} = all_params(rel_sims{param_no},param_no); + % store the values of this parameter + eval(['param_values{param_no} = data.config.' param_names{param_no} '(rel_sims{param_no});']); +end + +%% sensitivity analyses + +for s = 1 : length(data.haemods) + data.haemods(s).trial = (data.haemods(s).SBP_b - data.haemods(s).DBP_b); +end +for s = 1 : length(data.haemods) + data.haemods(s).trial2 = (data.haemods(s).SBP_b - data.haemods(s).DBP_b)./(data.haemods(s).P2pk_a-data.haemods(s).DBP_a); +end +for s = 1 : length(data.haemods) + data.haemods(s).trial3 = (data.haemods(s).SBP_b - data.haemods(s).DBP_b)./(data.haemods(s).P1in_a-data.haemods(s).DBP_a); +end + +% Simulated characteristics +resultant_params = {'trial', 'trial2', 'trial3', 'CO', 'LVET', 'AP_a', 'AI_a', 'P1in_a', 'P2in_a', 'P1pk_a', 'P2pk_a', 'P1in_c', 'P2in_c', 'P1pk_c', 'P2pk_c', 'PP_a', 'SMBP_a', 'MBP_a', 'SBP_diff', 'SBP_a', 'PP_amp', 'IAD', 'SI', 'RI', 'AGI_mod', 'MBP_drop_finger', 'MBP_drop_ankle', 'SBP_b', 'DBP_b', 'PP_b', 'MBP_b', 'AP_c', 'AI_c', 'Tr_a'}; + +for do_all = 0:1 + + I = nan(length(param_names), length(resultant_params)); + for param_no = 1 : length(param_names) + % skip if this parameter wasn't varied indpendently + if length(param_variations{param_no}) <= 1 % (1 accounts for the baseline sim) + I(param_no,:) = nan; + continue + end + + % extract data for this parameter + curr_rel_sims = rel_sims{param_no}; + curr_rel_variations = param_variations{param_no}; + curr_baseline_vals = baseline_vals{param_no}; + curr_baseline_sim_nos = baseline_sims{param_no}; + curr_baseline_logs = baseline_logs{param_no}; + + % perform sensitivity analysis + for res_param_no = 1 : length(resultant_params) + + % Extract data for this resultant param + curr_res_param = resultant_params{res_param_no}; + eval(['all_values = extractfield(data.haemods, ''' curr_res_param ''');']); + all_values = all_values(:); + + % identify relevant simulations (excluding those which were physiologically implausible) + if do_all + rel_els = ~curr_baseline_logs & curr_rel_variations~=0 & ~isnan(all_values); + else + rel_els = ~curr_baseline_logs & curr_rel_variations~=0 & ~isnan(all_values) & data.plausibility.plausibility_log; + end + rel_value_sims = curr_rel_sims(rel_els); + rel_baseline_sims = curr_baseline_sim_nos(rel_els); + rel_variations = curr_rel_variations(rel_els); + + % identify param values + res_param_values = all_values(rel_value_sims); + res_param_baseline_values = all_values(rel_baseline_sims); + + % calculate index + v = rel_variations; + I(param_no,res_param_no) = 100*mean((res_param_values - res_param_baseline_values)./(abs(res_param_baseline_values).*v)); + end + end + + % Make sensitivity plots for each resultant parameter + paper_size = [200,200,700,400]; + for res_param_no = 1 : length(resultant_params) + + curr_i_vals = I(:, res_param_no); + curr_param_names = param_names; + rel_els = ~strcmp(curr_param_names, 'ht') & ~strcmp(curr_param_names, 'rho'); + curr_i_vals = curr_i_vals(rel_els); + curr_param_names = curr_param_names(rel_els); + %req_order = {'hr','sv','lvet','t_pf','reg_vol','mbp','pwv','p_out','dia','len','pvc'}; + + ref_param = resultant_params{res_param_no}; + curr_param_names = strrep(curr_param_names, 'reg_vol', 'Rvol'); + curr_param_names = strrep(curr_param_names, 'p_out', 'Pout'); + + % ignore parameters which we're not interested in + rel_no = strcmp(curr_param_names, 'dbp'); + curr_i_vals(rel_no) = nan; + + fig_done = make_sens_analysis_fig(curr_param_names, curr_i_vals, 'norm', paper_size, ref_param); + + if fig_done ==1 + if do_all + filename = [PATHS.Analysis_figures, 'sens_', ref_param, '_all']; + else + filename = [PATHS.Analysis_figures, 'sens_', ref_param, '_plausible']; + end + PrintFigs(gcf, paper_size(3:4)/70, filename) + end + + end + +end + +end + +function fig_done = make_sens_analysis_fig(model_params, i_vals, type, paper_size, ref_param) + +% exclude variables which weren't varied +rel_els = ~isnan(i_vals); +i_vals = i_vals(rel_els); +model_params = model_params(rel_els); + +if isempty(model_params) + fig_done = 0; + return +else + fig_done = 1; +end + +% re-arrange +rel_order = {'hr','sv','lvet','t_pf','Rvol','dia','len','pwv','gamma','mbp','pvc'}; +rel_order = {'hr','sv','lvet','t_pf','Rvol','dia','len','pwv','mbp','pvc'}; +rel_order = {'hr', 'sv', 'lvet', 'dia', 'pwv', 'mbp'}; +for s = 1 : length(rel_order) + order(s) = find(strcmp(model_params,rel_order{s})); +end +model_params = model_params(order); +i_vals = i_vals(order); + +% re-name +model_params = strrep(model_params, 'hr', 'Heart Rate'); +model_params = strrep(model_params, 'sv', 'Stroke Volume'); +model_params = strrep(model_params, 'lvet', 'Duration Systole'); +model_params = strrep(model_params, 't_pf', 'Time to Peak Flow'); +model_params = strrep(model_params, 'Rvol', 'Regurgitation Volume'); +model_params = strrep(model_params, 'dia', 'Large Art. Diameter'); +model_params = strrep(model_params, 'len', 'Prox. Aortic Length'); +model_params = strrep(model_params, 'pwv', 'Pulse Wave Velocity'); +model_params = strrep(model_params, 'mbp', 'Periph. Vasc. Res.'); +model_params = strrep(model_params, 'pvc', 'Periph. Vasc. Comp.'); +model_params = strrep(model_params, 'Pout', 'Outflow Pressure'); + +if strcmp(type, 'abs') + ylims = [-30, 75]; + i_vals = abs(i_vals); + ylab_txt = 'abs(I) [%]'; +else + ylims = [-100, 100]; + ylab_txt = 'I [%]'; +end + +model_params = strrep(model_params, '_', ' '); + +figure('Position', paper_size) +subplot('Position',[0.13,0.30,0.86,0.63]) +ftsize = 20; +bar(i_vals) +set(gca,'XTickLabel',model_params) +set(gca, 'FontSize', ftsize) +ylab = ylabel(ylab_txt, 'Rotation', 0, 'FontSize', ftsize); +set(ylab, 'Units', 'Normalized', 'Position', [-0.1, 0.5, 0]); +%ylim(ylims) +% [label, units, abbr, graph_title, graph_title_no_units] = make_param_label(ref_param); +% title(graph_title_no_units, 'FontSize', ftsize) +xtickangle(30); +xlim([0.5, length(model_params)+0.5]) + +% annotations +y_val = 0.73; +dim = [.65 y_val .3 .3]; +str = {'Arterial Network'}; +annotation('textbox',dim,'String',str,'FitBoxToText','on','LineStyle','none','HorizontalAlignment','center','VerticalAlignment','middle','FontSize',ftsize); + +dim = [.19 y_val .3 .3]; +str = {'Cardiac Properties'}; +annotation('textbox',dim,'String',str,'FitBoxToText','on','LineStyle','none','HorizontalAlignment','center','VerticalAlignment','middle','FontSize',ftsize); + +hold on +ylims = [min(i_vals) - 0.1*range(i_vals), max(i_vals) + 0.22*range(i_vals)]; +plot(3.5*ones(1,2), [-100 100], '--k') +ylim(ylims) + +end + +function rel_ylims = plot_sds(ages, means, sds, no_sd, req_color, up) + +do_fill = 0; + +temp1 = means - (no_sd*sds); +temp2 = means + (no_sd*sds); + +if do_fill + temp = [temp1(:)', fliplr(temp2(:)')]; + fill_vals.y = temp; + temp = [ages(:)', fliplr(ages(:)')]; + fill_vals.x = temp; + clear temp + h = fill(fill_vals.x, fill_vals.y, 'r'); hold on + h.FaceColor = req_color; + h.EdgeColor = 'none'; +else + plot(ages, temp1, '--k', 'LineWidth', 2), hold on + plot(ages, temp2, '--k', 'LineWidth', 2) +end + +min_val = min(temp1); +max_val = max(temp2); +range_val = up.ylim_offset*(max_val - min_val); +rel_ylims = [min_val-range_val, max_val+range_val]; + +end + +function make_wave_speed_figure(PATHS) + +fprintf('\n - Making wave speed figure') + +% load collated data +load(PATHS.exported_data_mat_pwdb_data) + +% Find relevant simulations: (i) baseline simulation for each age +% (ii) variations in PWV for baseline age +rel_sims.ages = find(data.config.baseline_sim_for_age); +baseline_age = data.config.age(data.config.baseline_sim_for_all); +non_pwv_cols = ~strcmp(data.config.variations.param_names, 'pwv'); non_pwv_cols = non_pwv_cols(:)'; +rel_sims.pwvs = find(data.config.baseline_sim_for_all | ... + (data.config.age == baseline_age & sum(abs(data.config.variations.params(:,non_pwv_cols)),2) == 0) ); + +% Setup figure for wave speed curves +paper_size = [800, 600]; +fig_settings.lwidth = 2; +fig_settings.ftsize = 20; +fig_settings.colors = [1,1,1]; + +% cycle through each plot type +plot_types = fieldnames(rel_sims); +for plot_no = 1 : length(plot_types) + + figure('Position', [20,20,paper_size]) + labels = {}; + + % cycle through each relevant simulation + eval(['rel_sims.curr = rel_sims.' plot_types{plot_no} ';']) + for sim_no = 1 : length(rel_sims.curr) + curr_sim_no = rel_sims.curr(sim_no); + + % calculate wave speeds + rel_network_spec.inlet_radius = data.config.network.inlet_radius(curr_sim_no,:); + rel_network_spec.outlet_radius = data.config.network.outlet_radius(curr_sim_no,:); + rel_network_spec.length = data.config.network.length(curr_sim_no,:); rel_network_spec.length = rel_network_spec.length(:); + k = data.config.constants.k(curr_sim_no,:); + rho = data.config.constants.rho(curr_sim_no); + [wave_speed, ave_radius] = calculate_theoretical_wave_speeds(rel_network_spec, k, rho); + clear k rho rel_network_spec + [ave_radius, order] = sort(ave_radius); + wave_speed.all = wave_speed.all(order); + + % plot signal + color_intensity = 0.2+0.5*(sim_no/length(rel_sims.curr)); + curr_color = color_intensity*fig_settings.colors; + plot(2*ave_radius*1000, wave_speed.all, 'o-', 'Color', curr_color, 'LineWidth', fig_settings.lwidth, 'MarkerSize', 8, 'MarkerFaceColor', curr_color, 'MarkerEdgeColor', curr_color) + hold on + + clear wave_speed ave_radius curr_color color_intensity + + if strcmp(plot_types{plot_no}, 'ages') + labels{end+1} = num2str(data.config.age(curr_sim_no)); + else + labels{end+1} = num2str(data.config.pwv_SD(curr_sim_no)); + end + + end + + % tidy up + set(gca, 'FontSize', fig_settings.ftsize) + ylab = ylabel('Wave Speed [m/s]', 'FontSize', fig_settings.ftsize); + %set(ylab, 'Units', 'Normalized', 'Position', [-0.13, 0.5, 0]); + xlab = xlabel('Diameter [mm]', 'FontSize', fig_settings.ftsize); + box off + legend(labels, 'FontSize', fig_settings.ftsize-2), clear labels + + % Save figure + PrintFigs(gcf, paper_size/70, [PATHS.wave_speed_fig, '_', plot_types{plot_no}]) + +end + + +end + +function [wave_speeds, ave_radius] = calculate_theoretical_wave_speeds(rel_network_spec, k, rho) + +% find current wave speeds +ave_radius = mean([rel_network_spec.inlet_radius(:), rel_network_spec.outlet_radius(:)], 2); +ave_radius_cm = 100*ave_radius; + +% - New version +wave_speed = empirical_wave_speed(ave_radius_cm, k, rho); +wave_speeds.all = wave_speed; + +% extract pwvs + +% - cf (noting that carotid measurements are taken half way along carotid) +lens_aorta_carotid = [rel_network_spec.length([1,2]); rel_network_spec.length(15)/2]; +carotid_radius_cm = 100* (rel_network_spec.inlet_radius(15) - (0.5*(rel_network_spec.inlet_radius(15) - rel_network_spec.outlet_radius(15)))); +path_speeds_aorta_carotid = [wave_speed([1,2]); empirical_wave_speed(carotid_radius_cm, k, rho)]; + +lens_aorta_femoral = rel_network_spec.length([1,2,14,18,27,28,35,37,39,41,42,44]); +path_speeds_aorta_femoral = wave_speed([1,2,14,18,27,28,35,37,39,41,42,44]); + +path_len = sum(lens_aorta_femoral)-sum(lens_aorta_carotid); +time_taken = sum(lens_aorta_femoral./path_speeds_aorta_femoral) - sum(lens_aorta_carotid./path_speeds_aorta_carotid); +wave_speeds.aorta = path_len/time_taken; + +% - arm (noting that brachial measurements are taken half way along brachial) +lens_aorta_radial = rel_network_spec.length([1,2,14,19,21,22]); +path_speeds_aorta_radial = wave_speed([1,2,14,19,21,22]); +lens_aorta_brachial = [rel_network_spec.length([1,2,14,19]); rel_network_spec.length(21)/2]; +brachial_radius_cm = 100* (rel_network_spec.inlet_radius(21) - (0.5*(rel_network_spec.inlet_radius(21) - rel_network_spec.outlet_radius(21)))); +path_speeds_aorta_brachial = [wave_speed([1,2,14,19]); empirical_wave_speed(brachial_radius_cm, k, rho)]; + +path_len = sum(lens_aorta_radial)-sum(lens_aorta_brachial); +time_taken = sum(lens_aorta_radial./path_speeds_aorta_radial) - sum(lens_aorta_brachial./path_speeds_aorta_brachial); +wave_speeds.arm = path_len/time_taken; + +% - leg +ankle_els = [1,2,14,18,27,28,35,37,39,41,42,44,46,49]; +lens_aorta_ankle = rel_network_spec.length(ankle_els); +path_speeds_aorta_ankle = wave_speed(ankle_els); +femoral_els = [1,2,14,18,27,28,35,37,39,41,42,44]; +lens_aorta_femoral = rel_network_spec.length(femoral_els); +path_speeds_aorta_femoral = wave_speed(femoral_els); + +path_len = sum(lens_aorta_ankle)-sum(lens_aorta_femoral); +time_taken = sum(lens_aorta_ankle./path_speeds_aorta_ankle) - sum(lens_aorta_femoral./path_speeds_aorta_femoral); +wave_speeds.leg = path_len/time_taken; + +end + +function wave_speed = empirical_wave_speed(ave_radius_cm, k, rho) + +Eh_D0 = (k(1)*exp(k(2)*ave_radius_cm))+k(3); % Eh/D0 (from Mynard's 2015 paper, eqn 3) +c0_squared = (2/3)*(Eh_D0/(rho/1000)); % from Mynard's 2015 paper, eqn 3, converts rho from kg/m3 to g/cm3 +wave_speed = sqrt(c0_squared)/100; % converts from cm/s to m/s. + +end + +function make_pw_along_path_figure(PATHS) + +% load path data +if ~exist(PATHS.exported_data_mat_pwdb_data_w_aorta_finger_path, 'file') + return +else + fprintf('\n - Plotting pulse waves along particular paths') +end + +do_fid_pts = 1; +do_brach_color = 1; % whether or not to highlight the brachial artery +%plot_f_b = 0; % whether or not to plot forward and backward waves + +load(PATHS.exported_data_mat_pwdb_data) +ages = [min(data.config.age), max(data.config.age)]; + +for age_no = 1:length(ages) + + curr_age = ages(age_no); + + % identify baseline simulation + baseline_sim_no = data.config.baseline_sim_for_age & data.config.age == curr_age; + + % Setup figure for Pressure and Flow vel + paper_size = [600, 400]; + fig_settings.lwidth = 2; + fig_settings.ftsize = 18; + paths = {'arm', 'leg'}; + fig_settings.sig_types = {'P','U'}; + fig_settings.colors = {[1,0,0], [1,0,0]}; + fig_settings.ylims = {[0,140], [-0.1, 1.5]}; + + for path_no = 1 : length(paths) + curr_path = paths{path_no}; + switch curr_path + case 'arm' + curr_path_var_name = 'aorta_finger'; + case 'leg' + curr_path_var_name = 'aorta_foot'; + end + + for sig_type_no = 1 : length(fig_settings.sig_types) + curr_sig_type = fig_settings.sig_types{sig_type_no}; + + % Load relevant data + switch curr_path + case 'arm' + load(PATHS.exported_data_mat_pwdb_data_w_aorta_finger_path) + case 'leg' + switch curr_sig_type + case 'P' + load(PATHS.exported_data_mat_pwdb_data_w_aorta_foot_path_p) + case 'U' + load(PATHS.exported_data_mat_pwdb_data_w_aorta_foot_path_u) + case 'A' + load(PATHS.exported_data_mat_pwdb_data_w_aorta_foot_path_a) + end + end + + + % extract relevant data + eval(['rel_data = data.path_waves.' curr_path_var_name '(baseline_sim_no);']); + eval(['rel_data.sig = rel_data.' curr_sig_type ';']); + rel_data.p1_el = data.pw_inds.AorticRoot_P1in_T(baseline_sim_no)*data.path_waves.fs+1; + rel_data.p2_el = data.pw_inds.AorticRoot_P2pk_T(baseline_sim_no)*data.path_waves.fs+1; + + figure('Position', [20,20, paper_size]) + if length(rel_data.sig) > 50 + inc = 2; + else + inc = 1; + end + for s = 1:inc:length(rel_data.sig) + if do_brach_color && strcmp(rel_data.artery{s}, 'brachial') + curr_color = 'b'; + else + curr_color = 'k'; + end + plot3([0:length(rel_data.sig{s})-1]/data.path_waves.fs, ones(length(rel_data.sig{s}),1)*rel_data.dist(s), rel_data.sig{s}, curr_color), hold on + end + + if do_brach_color && strcmp(curr_path, 'arm') + dist_at_start = min(rel_data.dist(strcmp(rel_data.artery, 'brachial'))); + dist_at_end = max(rel_data.dist(strcmp(rel_data.artery, 'brachial'))); + prop_brachial = 0.75; + desired_dist = dist_at_start + prop_brachial*(dist_at_end-dist_at_start); + [~,s] = min(abs(rel_data.dist-desired_dist)); + plot3([0:length(rel_data.sig{s})-1]/data.path_waves.fs, ones(length(rel_data.sig{s}),1)*rel_data.dist(s), rel_data.sig{s}, 'b', 'LineWidth', 2), hold on + end + + % Tidy up + xlabel('Time (s)', 'FontSize', fig_settings.ftsize) + ylabel('Distance (cm)', 'FontSize', fig_settings.ftsize) + if strcmp(curr_sig_type, 'P') + zlabel('Pressure (mmHg)', 'FontSize', fig_settings.ftsize) + elseif strcmp(curr_sig_type, 'U') + zlabel('Flow velocity (m/s)', 'FontSize', fig_settings.ftsize) + elseif strcmp(curr_sig_type, 'Q') + zlabel('Flow rate (m^3/s)', 'FontSize', fig_settings.ftsize) + end + set(gca, 'FontSize', fig_settings.ftsize -2 ) + view(15, 21) + %view(0, 21) + grid on + + eval(['xlim([0 length(rel_data.' curr_sig_type '{s})/data.path_waves.fs])']) + ylim([0 max(rel_data.dist)]) + if strcmp(curr_sig_type, 'P') + zlim([65, 130]) + end + + % annotate fiducial points + if do_fid_pts && strcmp(curr_sig_type, 'P') + plot3(rel_data.p1_el/data.path_waves.fs, rel_data.dist(1), rel_data.sig{1}(rel_data.p1_el), 'or', 'MarkerFaceColor', 'r') + plot3(rel_data.p2_el/data.path_waves.fs, rel_data.dist(1), rel_data.sig{1}(rel_data.p2_el), 'or', 'MarkerFaceColor', 'r') + if age_no == 1 + dim1 = [.13 .43 .1 .1]; + dim2 = [.28 .32 .1 .1]; + else + dim1 = [.13 .43 .1 .1]; + dim2 = [.29 .43 .1 .1]; + end + str = 'P1_a'; + annotation('textbox',dim1,'String',str,'FitBoxToText','on','LineStyle','none','Color','r','FontSize', fig_settings.ftsize); + str = 'P2_a'; + annotation('textbox',dim2,'String',str,'FitBoxToText','on','LineStyle','none','Color','r','FontSize', fig_settings.ftsize); + end + + % Save figure + if age_no == 1 + savepath = [PATHS.pw_path_fig, '_', curr_path, '_' curr_sig_type '_young']; + else + savepath = [PATHS.pw_path_fig, '_', curr_path, '_' curr_sig_type '_elderly']; + end + savefig(savepath) + PrintFigs(gcf, paper_size/70, savepath) + + clear curr_color curr_sig s + end + + end + close all + +end + +end + +function plot_baseline_signals(fig_settings, data) + +% identify baseline simulation data +baseline_sim_no = find(data.config.baseline_sim_for_all); + +% cycle through different signals +for sig_type_no = 1 : length(fig_settings.sig_types) + curr_sig_type = fig_settings.sig_types{sig_type_no}; + + % cycle through different sites + for req_site_no = 1 : length(fig_settings.req_sites) + curr_site = fig_settings.req_sites{req_site_no}; + + % extract relevant signal at this site + eval(['rel_sig.v = data.waves.' curr_sig_type '_' curr_site '{baseline_sim_no};']) + rel_sig.fs = data.waves.fs; + rel_sig.t = [0:length(rel_sig.v)-1]/rel_sig.fs; + + % convert to friendly units if needed + if sum(strcmp(curr_sig_type, {'P', 'Pe'})) + rel_sig.units = 'mmHg'; + elseif strcmp(curr_sig_type, 'A') + rel_sig.v = rel_sig.v*1000*1000; % m^2 to mm^2 + rel_sig.units = 'mm^2'; + elseif strcmp(curr_sig_type, 'PPG') + rel_sig.units = 'au'; + elseif strcmp(curr_sig_type, 'U') + rel_sig.units = 'm/s'; + end + + % setup subplot + if sig_type_no == 1 + subplot(length(fig_settings.req_sites),2,(2*req_site_no)-1) + else + subplot(length(fig_settings.req_sites),2,(2*req_site_no)) + end + + % plot signal + plot(rel_sig.t, rel_sig.v, 'Color', fig_settings.colors{sig_type_no}, 'LineWidth', fig_settings.lwidth) + + % tidy up + set(gca, 'XTick', 0:0.2:1) + set(gca, 'FontSize', fig_settings.ftsize,'XAxisLocation', 'origin') + xlim([0, rel_sig.t(end)]) + if req_site_no == 1 + dim = [.2+.5*(sig_type_no-1) .77 .2 .2]; + str = [strrep(curr_sig_type, '_WK', ''), ' [', rel_sig.units, ']']; + annotation('textbox',dim,'String',str,'FitBoxToText','on','LineStyle', 'none', 'FontSize', fig_settings.ftsize); +% title(str, 'FontSize', fig_settings.ftsize); + end + if req_site_no < length(fig_settings.req_sites) + set(gca, 'XTickLabel', []) + end + if sum(strcmp(fieldnames(fig_settings), 'ylims')) + ylims = fig_settings.ylims{sig_type_no}; + if ~isnumeric(ylims) + temp_range = range(rel_sig.v); + ylims = [min(rel_sig.v)-0.1*temp_range, max(rel_sig.v)+0.1*temp_range]; + end + ylim(ylims); + end + if req_site_no == length(fig_settings.req_sites) + xlab = xlabel('Time [s]', 'FontSize', fig_settings.ftsize); + ylims = ylim; + if ylims(1)<0 + set(xlab, 'Units', 'Normalized', 'Position', [0.6, -0.6, 0]); + end + end + + box off + + end + +end + + +end + +function comparison_w_mynard_waves_figure(PATHS) + +% see if the data is available +loadpath = '/Users/petercharlton/Google Drive/Work/Code/nektar/Mynard2015_data/ABME2015data.mat'; +if ~exist(loadpath, 'file') + return +end + +fprintf('\n - Making Figure to compare waves with those from Mynard 2015') + +% load data +load(PATHS.exported_data_mat_pwdb_data) + +% identify baseline simulation +baseline_sim_no = find(data.config.baseline_sim_for_all); + +% Import waves from Mynard's article +load(loadpath); + +% Setup plotting +wave_types = {'A', 'Q','P'}; +rel_sites = {'AorticRoot', 'Carotid', 'Brachial', 'Radial', 'CommonIliac', 'Femoral', 'AntTibial', 'SupTemporal'}; +ftsize = 24; +lwidth = 2; +plot_model_data_normalised = false; +offset = 0.25; + +% make plots for each wave type and each measurement site +for wave_type_no = 1 : length(wave_types) + + curr_wave_type = wave_types{wave_type_no}; + + for site_no = 1 : length(rel_sites) + curr_site = rel_sites{site_no}; + + if strcmp(curr_wave_type, 'PPG') + artery_name = find_artery_name(curr_site); % use PPG names + else + artery_name = curr_site; + end + + paper_size = [600,400]; + + % Make figure + figure('Position', [20,20, paper_size]) + + max_t = 0; + + if strcmp(curr_wave_type, 'Q') + units = 'm^3/s'; + elseif strcmp(curr_wave_type, 'P') + units = 'mmHg'; + elseif strcmp(curr_wave_type, 'A') + units = 'mm'; + end + + if plot_model_data_normalised + units = 'normalised'; + end + + % extract data to plot + if strcmp(curr_wave_type, 'Q') + eval(['temp1 = data.waves.U_', curr_site, '{baseline_sim_no};']); + eval(['temp2 = data.waves.A_', curr_site, '{baseline_sim_no};']); + curr_wav.v = temp1.*temp2; + else + eval(['curr_wav.v = data.waves.' curr_wave_type '_', curr_site, '{baseline_sim_no};']); + end + curr_wav.fs = data.waves.fs; + curr_wav.t = [0:length(curr_wav.v)-1]/curr_wav.fs; + + % convert units if necessary + if strcmp(curr_wave_type, 'A') + curr_wav.v= 1000*sqrt(curr_wav.v/pi); + end + + % plot + if ~plot_model_data_normalised + plot(curr_wav.t, curr_wav.v, 'b', 'LineWidth', lwidth), hold on + else + curr_wav.v = (curr_wav.v - min(curr_wav.v))/range(curr_wav.v); + plot(curr_wav.t, curr_wav.v + offset, 'b', 'LineWidth', lwidth), hold on + ylim([-0.1 1.1+offset]); + set(gca, 'YTick', []) + end + + % store legend label + max_t = max([max_t, max(curr_wav.t)]); + + % tidy up + xlim([0, max_t]) + xlabel('Time [s]', 'FontSize', ftsize) + ylab = ylabel([strrep(curr_wave_type, '_', ' '), ' [' units ']'], 'FontSize', ftsize); + set(gca, 'FontSize', ftsize) + + % Plot waves from literature + + % extract relevant wave from Mynard's data + lit_wave.t = a115lb.t; + lit_wave.fs = 1000; + switch curr_site + case 'AorticRoot' + mynard_name = 'AoRt'; + case 'Carotid' + mynard_name = 'Lcar'; + case 'Brachial' + mynard_name = 'LBrach'; + case 'Radial' + mynard_name = 'LRadI'; + case 'CommonIliac' + mynard_name = 'LcmIlc'; + case 'Femoral' + mynard_name = 'Lfem'; + case 'AntTibial' + mynard_name = 'LATib'; + case 'SupTemporal' + mynard_name = 'LSupTemp'; + end + wave_el = find(strcmp(a115lb.monitor.name, mynard_name)); + eval(['lit_wave.v = a115lb.tnode.' strrep(lower(curr_wave_type), 'a', 'A') '(:,wave_el);']); + if strcmp(curr_wave_type, 'P') || strcmp(curr_wave_type, 'A') + [~,temp] = min(lit_wave.v); + if temp > 799 + lit_wave.v = lit_wave.v(temp-799:temp); + elseif temp < 80 + lit_wave.v = lit_wave.v(temp:temp+799); + else + len = length(lit_wave.v); + lit_wave.v = [lit_wave.v(temp:end); lit_wave.v(1:799-(len-temp+1))]; + end + clear temp + + end + + % convert units if necessary + if strcmp(curr_wave_type, 'P') + lit_wave.v = lit_wave.v/1333.3; + elseif strcmp(curr_wave_type, 'Q') + lit_wave.v = lit_wave.v/1000000; + [r,lags] = xcorr(curr_wav.v, lit_wave.v); + [~, rel_lag] = max(r); + rel_lag = -1*(rel_lag-length(lit_wave.v)); + lit_wave.v = [lit_wave.v(rel_lag:end); lit_wave.v(1:rel_lag-1)]; + elseif strcmp(curr_wave_type, 'A') + lit_wave.v = lit_wave.v/10000; + lit_wave.v= 1000*sqrt(lit_wave.v/pi); + end + + % plot + plot([0:length(lit_wave.v)-1]/lit_wave.fs, lit_wave.v, 'r', 'LineWidth', lwidth), hold on + + max_t = max([max_t, max(curr_wav.t)]); + + % tidy up + xlim([0, max_t]) + xlabel('Time [normalised]', 'FontSize', ftsize) + ylab = ylabel([curr_wave_type, ' [' units ']'], 'FontSize', ftsize); + set(gca, 'FontSize', ftsize) + title(artery_name, 'FontSize', ftsize+4) + + % save + PrintFigs(gcf, paper_size/70, [PATHS.Analysis_figures, 'Mynard_vs_', curr_wave_type, '_', strrep(artery_name, ' ', '_')]) + + end + + +end + +end + +function make_changes_in_waves_age_figure(PATHS) + +fprintf('\n - Making Figure to show changes in wave shapes with age') + + +% - Import waves from literature +% Path for loading waves from literature +lit_waves_loadpath = '/Users/petercharlton/Google Drive/Work/Projects/PWV Project/Reports/Pulse_wave_database/Figures/literature_pulse_waves/waves_from_literature.mat'; +if ~exist(lit_waves_loadpath, 'file') + % if this file doesn't exist then insert dummy data + waves(1).author = 'abc'; waves(1).site = 'abc'; waves(1).wave_type = 'abc'; waves(1).v.y = []; waves(1).v.fs = nan; waves(1).age = -1; +else + % otherwise load waves from the literature + load(lit_waves_loadpath); +end + +% load data +load(PATHS.exported_data_mat_pwdb_data) + +% identify baseline simulation +baseline_sim_nos = find(data.config.baseline_sim_for_age); +ages = data.config.age(baseline_sim_nos); + +% Extract relevant data for min, max, and mid ages +[~,min_el] = min(ages); +mid_el = ceil(0.5*(1+length(ages))); +[~,max_el] = max(ages); clear ages +rel_sims = baseline_sim_nos([min_el, mid_el, max_el]); clear min_el mid_el max_el +rel_ages = data.config.age(rel_sims); + +% Setup plotting +wave_types = {'PPG', 'P', 'U'}; +rel_sites.P = {'Brachial', 'AorticRoot', 'Carotid', 'Radial', 'CommonIliac', 'Femoral', 'AntTibial', 'SupTemporal', 'Digital'}; +rel_sites.PPG = {'Digital', 'AntTibial', 'SupTemporal', 'Radial'}; +if sum(strcmp(fieldnames(data.waves), 'U_SupMidCerebral')) + rel_sites.U = {'SupMidCerebral', 'AorticRoot', 'Carotid'}; +else + rel_sites.U = {'AorticRoot', 'Carotid'}; +end + +ftsize = 28; +lwidth = 2; +age_colors = linspace(0.4,0.7, length(rel_ages)); +plot_model_data_normalised = true; + +% make plots for each wave type and each measurement site +for wave_type_no = 1 : length(wave_types) + + curr_wave_type = wave_types{wave_type_no}; + eval(['rel_wave_sites = rel_sites.' curr_wave_type ';']) + + for site_no = 1 : length(rel_wave_sites) + curr_site = rel_wave_sites{site_no}; + if strcmp(curr_site, 'AorticRoot') || strcmp(curr_site, 'Carotid') + offset = 0.4; + else + offset = 0.4; %0.25; + end + if strcmp(curr_wave_type, 'PPG') + artery_name = find_artery_name(curr_site); % use PPG names + else + artery_name = curr_site; + end + + % Determine whether there is a corresponding set of waves from the literature + rel_waves = false(length(waves),1); + for s = 1 : length(waves) + if strcmp(lower(waves(s).site), lower(artery_name)) && strcmp(waves(s).wave_type, curr_wave_type) + rel_waves(s) = true; + end + if strcmp(waves(s).site, 'aortic') && strcmp('AorticRoot', artery_name) && strcmp(waves(s).wave_type, curr_wave_type) + rel_waves(s) = true; + end + if strcmp(waves(s).site, 'cerebral') && strcmp('SupMidCerebral', artery_name) && strcmp(waves(s).wave_type, curr_wave_type) + rel_waves(s) = true; + end + end + clear s + rel_wave = find(rel_waves); clear rel_waves + if ~isempty(rel_wave) + lit_wave = waves(rel_wave); + paper_size = [1000,400]; + do_lit_wave = true; + else + paper_size = [1000,400]; + do_lit_wave = false; + end + + % Make figure + figure('Position', [20,20, paper_size]) + subplot('Position', [0.55,0.20,0.42,0.68]) + + leg_labels = {}; max_t = 0; + + eval(['units = data.waves.units.' curr_wave_type ';']) + + if plot_model_data_normalised + units = 'normalised'; + end + + % Plot each of the waves in turn (corresponding to the three ages) + leg_h = []; + for age_no = 1 : length(rel_ages) + + % extract data to plot + eval(['curr_wav.v = data.waves.' curr_wave_type '_', curr_site '{rel_sims(age_no)};']); + curr_wav.fs = data.waves.fs; + curr_wav.t = [0:length(curr_wav.v)-1]/curr_wav.fs; + + % plot + if ~plot_model_data_normalised + leg_h(end+1) = plot(curr_wav.t, curr_wav.v, 'Color', age_colors(age_no)*ones(1,3), 'LineWidth', lwidth); hold on + else + curr_wav.v = (curr_wav.v - min(curr_wav.v))/range(curr_wav.v); + leg_h(end+1) = plot(curr_wav.t, curr_wav.v +(offset*(age_no-1)), 'Color', age_colors(age_no)*ones(1,3), 'LineWidth', lwidth); hold on + ylim([-0.1 1.1+(offset*(length(rel_ages)-1))]); + set(gca, 'YTick', []) + end + + % store legend label + leg_labels = [leg_labels, num2str(rel_ages(age_no))]; + max_t = max([max_t, max(curr_wav.t)]); + + % save baseline fig + if age_no == 1 + + % tidy up + xlim([0, max_t]) + xlabel('Time [s]', 'FontSize', ftsize) + ylab = ylabel([curr_wave_type, ' [' units ']'], 'FontSize', ftsize); + set(gca, 'FontSize', ftsize) + box off + title([strrep(artery_name, 'cR', 'c R'), ', ' curr_wave_type], 'FontSize', ftsize+4) + + % Save fig + PrintFigs(gcf, paper_size/70, [PATHS.Analysis_figures, curr_wave_type, '_waves_', artery_name, '_baseline'], false) + + title('') + end + + end + + % tidy up + xlim([0, max_t]) + xlabel('Time [s]', 'FontSize', ftsize) + ylab = ylabel([curr_wave_type, ' [' units ']'], 'FontSize', ftsize); + %ylab = ylabel({curr_wave_type, ['[' units ']']}, 'FontSize', ftsize, 'Rotation', 0); + %set(ylab, 'Units', 'Normalized', 'Position', [-0.17, 0.5, 0]); + set(gca, 'FontSize', ftsize) + legend(fliplr(leg_h), fliplr(leg_labels)), clear leg_labels + str = [strrep(artery_name, 'cR', 'c R'), ', ' curr_wave_type]; + str = strrep(str, 'SupMidCerebral', 'Mid Cerebral'); + dim = [0.25,0.7,0.5,0.3]; + annotation('textbox',dim,'String',str,'LineStyle', 'none', 'FontSize', ftsize+8, 'HorizontalAlignment', 'center'); + box off + + % Plot waves from literature + subplot('Position', [0.05,0.20,0.42,0.68]) + if ~do_lit_wave + lit_wave.v(1).y = nan(1,100); + lit_wave.v(2).y = nan(1,100); + lit_wave.v(3).y = nan(1,100); + lit_wave.v(1).fs = 100; + lit_wave.v(2).fs = 100; + lit_wave.v(3).fs = 100; + lit_wave.age = [25,55,75]; + end + + leg_labels = {}; max_t = 0; + if length(lit_wave.v) < 3 + temp_rel_ages = rel_ages([1,3]); + elseif strcmp(curr_wave_type, 'PPG') + temp_rel_ages = [25,35,55]; + elseif strcmp(artery_name, 'Brachial') + temp_rel_ages = [25,35,75]; + else + temp_rel_ages = rel_ages; + end + + % Plot each of the waves in turn (corresponding to the three ages) + leg_h = []; + for age_no = 1 : length(temp_rel_ages) + + % identify relevant wave to plot + [~, rel_wave_el] = min(abs(lit_wave.age - temp_rel_ages(age_no))); + curr_wav.v = lit_wave.v(rel_wave_el).y; + curr_wav.fs = lit_wave.v(rel_wave_el).fs; + curr_wav.t = [0:length(curr_wav.v)-1]/curr_wav.fs; + curr_wav.age = lit_wave.age(rel_wave_el); + + % plot + leg_h(end+1) = plot(curr_wav.t, curr_wav.v + (offset*(age_no-1)), 'Color', age_colors(age_no)*ones(1,3), 'LineWidth', lwidth); hold on + ylim([-0.1 1.1+(offset*(length(temp_rel_ages)-1))]); + + % store legend label + leg_labels = [leg_labels, num2str(curr_wav.age,2)]; + max_t = max([max_t, max(curr_wav.t)]); + + end + + % tidy up + xlim([0, max_t]) + if strcmp(artery_name, 'SupMidCerebral') || strcmp(artery_name, 'Digital') + xlabel('Time [normalised]', 'FontSize', ftsize) + else + xlabel('Time [s]', 'FontSize', ftsize) + end + ylab = ylabel([curr_wave_type, ' [normalised]'], 'FontSize', ftsize); + %ylab = ylabel({curr_wave_type, ['[' units ']']}, 'FontSize', ftsize, 'Rotation', 0); + %set(ylab, 'Units', 'Normalized', 'Position', [-0.17, 0.5, 0]); + set(gca, 'FontSize', ftsize, 'YTick', []) + legend(fliplr(leg_h), fliplr(leg_labels)), clear leg_labels +% title([strrep(artery_name, 'cR', 'c R'), ' (\itin vivo\rm\bf)'], 'FontSize', ftsize+4) + box off + + % save + PrintFigs(gcf, paper_size/70, [PATHS.Analysis_figures, curr_wave_type, '_waves_', strrep(artery_name, ' ', '_')]) + + end + + +end + +end + +function artery_name = find_artery_name(site) + +switch site + case 'Brachial' + artery_name = 'Arm'; + case 'Radial' + artery_name = 'Wrist'; + case 'Carotid' + artery_name = 'Neck'; + case 'Digital' + artery_name = 'Finger'; + case 'Femoral' + artery_name = 'UpperLeg'; + case {'Anterior Tibial', 'AntTibial'} + artery_name = 'Ankle'; + case 'Thyroid' + artery_name = 'Ear'; + case 'SupTemporal' + artery_name = 'Ear'; +end + +end + +function PrintFigs(h, paper_size, savepath, close_fig) + +if nargin<4 + close_fig = true; +end + +set(h,'PaperUnits','inches'); +set(h,'PaperSize', [paper_size(1), paper_size(2)]); +set(h,'PaperPosition',[0 0 paper_size(1) paper_size(2)]); +set(gcf,'color','w'); +print(h,'-dpdf',savepath) +print(h,'-depsc',savepath) +%print(h,'-dpng',savepath) + +% if you want .eps illustrations, then do as follows: +up.eps_figs = 0; +if up.eps_figs + % you need to download 'export_fig' from: + % http://uk.mathworks.com/matlabcentral/fileexchange/23629-export-fig + export_fig_dir_path = 'C:\Documents\Google Drive\Work\Projects\PhD\Github\phd\Tools\Other Scripts\export_fig\altmany-export_fig-76bd7fa\'; + addpath(export_fig_dir_path) + export_fig(savepath, '-eps') +end +if close_fig + close all; +end + +% save +fid = fopen([savepath, '.txt'], 'w'); +p = mfilename('fullpath'); +p = strrep(p, '\', '\\'); +fprintf(fid, ['Figures generated by:\n\n ' p '.m \n\n on ' datestr(today)]); +fclose all; + +end +","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/extract_pwdb_simulation_data.m",".m","26124","639","function extract_pwdb_simulation_data(pwdb_no) +% EXTRACT_PWDB_SIMULATION_DATA extracts simulation data from the Pulse Wave +% DataBase simulation input and output files, and saves them in Matlab +% format. +% +% extract_pwdb_simulation_data +% +% Inputs: the input and output files for the simulations, which +% should be stored in the shared folder. +% +% Outputs: - the files are copied into a new folder for storage +% - a single Matlab file called 'collated_data' is generated +% containing the simulation data for the database. +% +% Accompanying Article: +% This code is provided to facilitate reproduction of the Pulse Wave +% Database described in: +% Charlton P.H. et al. Modelling arterial pulse waves in healthy +% ageing: in silico evaluation of haemodynamics and +% pulse wave indices, ~~ under review ~~ +% DOI: ~~ tbc ~~ +% Further information on the pwdb Pulse Wave Database is provided in +% this article and at the project website: +% https://peterhcharlton.github.io/pwdb +% +% Author: Peter H. Charlton +% +% Licence: +% Permission is hereby granted, free of charge, to any person obtaining a copy +% of this software and associated documentation files (the ""Software""), to deal +% in the Software without restriction, including without limitation the rights +% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +% copies of the Software, and to permit persons to whom the Software is +% furnished to do so, subject to the following conditions: +% +% The above copyright notice and this permission notice shall be included in all +% copies or substantial portions of the Software. +% +% THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +% SOFTWARE. +% +% Copyright (C) 2019 King's College London +% +% v.1.0 Contributed to by: Marie Willemet, Jordi Alastruey, and Peter H. Charlton + +fprintf('\n --- Extracting PWDB simulation data ---') + +%% Settings +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% SETTINGS TO CHANGE: This function specifies where to save the outputs % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +PATHS = setup_paths_for_post_processing; +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +% Copy input files and output files to a new folder for storage +if nargin==0 + pwdb_no = CopyFiles(PATHS); +end + +% Setup paths with current simulation paths +PATHS = setup_paths_for_post_processing(pwdb_no); + +% Convert output History files into Matlab format +up.all_data = false; up.all_beats = false; +up.dir = PATHS.OutputFiles; up.save_dir = PATHS.ProcessedData; +up.ds_factor = 2; +up.find_pw_els = 1; +if ~exist(PATHS.history_files_data, 'file') + PATHS.history_files_data = ConvertHistoryFiles(up); +end + +% Import arterial system characteristics +if ~exist(PATHS.system_chars, 'file') + import_system_chars(PATHS); +end + +% Import peripheral boundary conditions +if ~exist(PATHS.peripheral_boundarys, 'file') + import_peripheral_boundarys(PATHS); +end + +% Collate input and output data into single variable, and calculate PPGs +if ~exist(PATHS.collated_data, 'file') + collate_input_and_output_data(PATHS); +end + +fprintf('\n --- Finished extracting PWDB simulation data ---\n') + +end + +function pwdb_no = CopyFiles(PATHS) + +% Identify the number of this pwdb +prev_pwdbs = dir(PATHS.storage_folder); +prev_pwdbs = extractfield(prev_pwdbs, 'name'); +prev_pwdbs = prev_pwdbs(~cellfun(@isempty, strfind(prev_pwdbs, 'pwdb'))); +if isempty(prev_pwdbs) + pwdb_no = 1; +else + pwdb_nos = nan(length(prev_pwdbs),1); + for s = 1 : length(prev_pwdbs) + pwdb_nos(s) = cell2mat(textscan(prev_pwdbs{s}, 'pwdb_%n')); + end + clear s + pwdb_no = max(pwdb_nos)+1; clear pwdb_nos +end +clear prev_sims + +% Check to see whether there are any files to be copied across: +temp = dir(PATHS.shared_folder); +possible_files = extractfield(temp, 'name'); +possible_files = possible_files(~cell2mat(extractfield(temp, 'isdir'))); +possible_files = possible_files(~strcmp(possible_files, '.DS_Store')); +if isempty(possible_files) + pwdb_no = pwdb_no - 1; % take most recent simulation + return +end + +fprintf('\n --- Copying Files ---') + +% Identify files to be copied +files_to_copy = dir(PATHS.shared_folder); +exc = cell2mat(extractfield(files_to_copy, 'isdir')); +files_to_copy = extractfield(files_to_copy, 'name'); +files_to_copy =files_to_copy(~exc); clear exc +files_to_copy =files_to_copy(~strcmp(files_to_copy, '.DS_Store')); + +% Determine whether each file is an input or an output +file_type = nan(size(files_to_copy)); +for file_no = 1 : length(files_to_copy) + if ~isempty(strfind(files_to_copy{file_no}, 'command')) || ... + ~isempty(strfind(files_to_copy{file_no}, 'launch')) || ... + ~isempty(strfind(files_to_copy{file_no}, '.bcs')) || ... + ~isempty(strfind(files_to_copy{file_no}, '.in')) || ... + ~isempty(strfind(files_to_copy{file_no}, '.mat')) + file_type(file_no) = 1; + else + file_type(file_no) = 2; + end +end + +% Copy each input file +for file_no = 1 : length(files_to_copy) + curr_file_path = [PATHS.shared_folder, files_to_copy{file_no}]; + if file_type(file_no) == 1 + new_file_path = [input_folder, files_to_copy{file_no}]; + else + new_file_path = [output_folder, files_to_copy{file_no}]; + end + if ~exist(new_file_path, 'file') + copyfile(curr_file_path, new_file_path); + end + delete(curr_file_path) +end + +end + +function import_system_chars(PATHS) + +% Check to see whether the required ""period.tex"" files have been outputted +% from the simulations: + +rel_files = dir([PATHS.OutputFiles, '*_period.tex']); +if isempty(rel_files) + return +end + +fprintf('\n Importing arterial system characteristics') + +% load output data +load(PATHS.history_files_data); +history_files_data = data; clear data +sims = fieldnames(history_files_data); + +% setup input variables +[pvr, pvc, pvc_iw, ac, c, tau] = deal(nan(length(sims),1)); + +% extract data for each simulation +for sim_no = 1 : length(sims) + % identify file for this simulation + curr_sim = sims{sim_no}; + filepath = [PATHS.OutputFiles, curr_sim '_period.tex']; + fid = fopen(filepath); + % extract this file's data + finished = false; + while ~finished + line_text = fgetl(fid); + if ~isempty(strfind(line_text, ' Peripheral vascular resistance:')) + % Extract PVR + temp1 = strfind(line_text, ':'); + temp2 = strfind(line_text, 'Pa'); + rel_text = line_text(temp1+4:temp2-2); + pvr(sim_no) = str2double(rel_text); + + % Extract PVC (on next line) + line_text = fgetl(fid); + temp1 = strfind(line_text, ':'); + temp2 = strfind(line_text, 'm$'); + rel_text = line_text(temp1+4:temp2-2); + pvc(sim_no) = str2double(rel_text); + + % Extract impedance-weighted PVC (on next line) + line_text = fgetl(fid); + temp1 = strfind(line_text, ':'); + temp2 = strfind(line_text, 'm$'); + rel_text = line_text(temp1+5:temp2-2); + pvc_iw(sim_no) = str2double(rel_text); + + % Extract total arterial compliance (on next line) + line_text = fgetl(fid); + temp1 = strfind(line_text, ':'); + temp2 = strfind(line_text, 'm$'); + rel_text = line_text(temp1+5:temp2-2); + ac(sim_no) = str2double(rel_text); + + % Extract total compliance (on next line) + line_text = fgetl(fid); + temp1 = strfind(line_text, ':'); + temp2 = strfind(line_text, 'm$'); + rel_text = line_text(temp1+14:temp2-2); + c(sim_no) = str2double(rel_text); + + % Extract time constant (on next line) + line_text = fgetl(fid); + temp1 = strfind(line_text, ':'); + temp2 = strfind(line_text, 's \\'); + rel_text = line_text(temp1+11:temp2-2); + tau(sim_no) = str2double(rel_text); + + finished = true; + end + end +end + +% save arterial system characteristics data +system_chars = table(pvr, pvc, pvc_iw, ac, c, tau); +save(PATHS.system_chars, 'system_chars') + +end + +function import_peripheral_boundarys(PATHS) + +fprintf('\n Importing peripheral Windkessel boundary conditions') + +% load output data +load(PATHS.history_files_data); +history_files_data = data; clear data +sims = fieldnames(history_files_data); + +% extract data for each simulation +[c, r_sum] = deal(nan(length(sims),116)); +for sim_no = 1 : length(sims) + + % identify file for this simulation + curr_sim = sims{sim_no}; + filepath = [PATHS.InputFiles, curr_sim '.mat']; + input_data = load(filepath); + + % Extract required Windkessel data + if sum(strcmp(fieldnames(input_data.sim_settings), 'reflect_log')) && input_data.sim_settings.reflect_log && ~input_data.sim_settings.fixed.R1_FIXED + temp.c_vals = input_data.params.outlet.C_WK; %WK Compliance + temp.c_vals(temp.c_vals == 0) = nan; + c(sim_no,1:length(temp.c_vals)) = temp.c_vals; + temp.r_sum_vals = input_data.params.outlet.R_WK_tot; %WK Resistance (sum of R1 and R2) + temp.r_sum_vals(temp.r_sum_vals == 0) = nan; + r_sum(sim_no,1:length(temp.r_sum_vals)) = temp.r_sum_vals; + clear temp + else + warning('\nHaven''t written this part yet') + temp.c_vals = input_data.params.outlet.C_WK; %WK Compliance + temp.c_vals(temp.c_vals == 0) = nan; + c(sim_no,1:length(temp.c_vals)) = temp.c_vals; + temp.r_sum_vals = input_data.params.outlet.R_WK_tot; %WK Resistance (sum of R1 and R2) + temp.r_sum_vals(temp.r_sum_vals == 0) = nan; + r_sum(sim_no,1:length(temp.r_sum_vals)) = temp.r_sum_vals; + clear temp + end + +end + +% save peripheral Windkessel characteristics data +peripheral_chars.c = c; +peripheral_chars.r_sum = r_sum; +save(PATHS.peripheral_boundarys, 'peripheral_chars') + +end + +function collate_input_and_output_data(PATHS) + +fprintf('\n Collating input and output data') + +% load output data +load(PATHS.history_files_data); +history_files_data = data; clear data + +% Load system chars (if available) +if exist(PATHS.system_chars, 'file') + load(PATHS.system_chars); + do_system_chars = 1; +else + do_system_chars = 0; +end + +% import input, output and system chars data for each simulation +sims = fieldnames(history_files_data); +for sim_no = 1 : length(sims) + % import input data + curr_sim_input_data = [PATHS.InputFiles, sims{sim_no}]; + input_data = load(curr_sim_input_data); clear curr_sim_input_data + input_data = rmfield(input_data, 'sim_up'); + collated_data(sim_no).input_data = input_data; clear input_data + % import output data + eval(['output_data = history_files_data.' sims{sim_no} ';']) + collated_data(sim_no).output_data = output_data; clear output_data + % import system chars + if do_system_chars + temp_fields = system_chars.Properties.VariableNames; + for field_no = 1 : length(temp_fields) + eval(['collated_data(sim_no).system_chars.' temp_fields{field_no} ' = system_chars.' temp_fields{field_no} '(sim_no);']); + end + clear temp_fields + end +end + +% Calculate WK PPG data +for sim_no = 1 : length(sims) + + for domain_el = 1 : length(collated_data(sim_no).output_data) + + no_distance_els = length(collated_data(sim_no).output_data(domain_el).distances); + for distance_el = 1 : no_distance_els + + % Extract required data + Q.v = collated_data(sim_no).output_data(domain_el).A(:,distance_el).*collated_data(sim_no).output_data(domain_el).U(:,distance_el); + Q.fs = collated_data(sim_no).output_data(domain_el).fs; + P.v = collated_data(sim_no).output_data(domain_el).P(:,distance_el); + P.fs = collated_data(sim_no).output_data(domain_el).fs; + P_out.v = collated_data(sim_no).input_data.sim_settings.p_out*ones(size(P.v)); + P_out.fs = collated_data(sim_no).output_data(domain_el).fs; + Q1D.fs = collated_data(sim_no).output_data(domain_el).fs; + Q1D.v = collated_data(sim_no).output_data(domain_el).Q1D; + Q_out.fs = collated_data(sim_no).output_data(domain_el).fs; + Q_out.v = collated_data(sim_no).output_data(domain_el).Q_out; + + % Estimate PPG using Windkessel approach + curr_domain_no = collated_data(sim_no).output_data(domain_el).domain_no; + curr_length = collated_data(sim_no).input_data.sim_settings.network_spec.length(curr_domain_no); + end_of_segment_log = collated_data(sim_no).output_data(domain_el).distances(distance_el) == curr_length; + clear curr_length curr_domain_no + if ~isempty(Q1D.v) && end_of_segment_log + curr_PPG_WK.v = cumsum(Q1D.v-Q_out.v); +% curr_PPG_WK.v = (temp-min(temp))./range(temp); clear temp + curr_PPG_WK.v = calc_static_wave(curr_PPG_WK.v); + else + curr_PPG_WK = estimate_ppg_using_windkessel(P, Q, P_out); + end + curr_PPG_WK.v = curr_PPG_WK.v(:); + [~,rel_el] = min(curr_PPG_WK.v); + curr_PPG_WK.v = [curr_PPG_WK.v(rel_el:end); curr_PPG_WK.v(1:rel_el-1)]; + + % find normalisation scaling factor + norm_factor = 1./range(curr_PPG_WK.v); + + % normalise + curr_PPG_WK.v = (curr_PPG_WK.v-min(curr_PPG_WK.v)).*norm_factor; + +% curr_PPG_WK.v = sqrt(curr_PPG_WK.v); % Added to transform volume PPG into distance PPG + collated_data(sim_no).output_data(domain_el).PPG(:,distance_el) = curr_PPG_WK.v; + collated_data(sim_no).output_data(domain_el).PPG_start_sample(1,distance_el) = collated_data(sim_no).output_data(domain_el).start_sample(1,distance_el) + rel_el -1; + collated_data(sim_no).output_data(domain_el).PPG_scaling_factor(1,distance_el) = norm_factor; + clear rel_el curr_PPG_WK end_of_segment_log curr_length curr_domain_no norm_factor + + end + collated_data(sim_no).output_data(domain_el).units.PPG = 'au'; + + end + +end + +% Calculate forward and backward waves +do_extras = 0; +if do_extras + for sim_no = 1 : length(sims) + + for domain_el = 1:length(collated_data(sim_no).output_data) + + no_distance_els = length(collated_data(sim_no).output_data(domain_el).distances); + for distance_el = 1 : no_distance_els + + % Extract required data + U.v = collated_data(sim_no).output_data(domain_el).U(:,distance_el); + U.fs = collated_data(sim_no).output_data(domain_el).fs; + P.v = collated_data(sim_no).output_data(domain_el).P(:,distance_el); + P.fs = collated_data(sim_no).output_data(domain_el).fs; + D.v = 2*sqrt(collated_data(sim_no).output_data(domain_el).A(:,distance_el)/pi); + D.fs = collated_data(sim_no).output_data(domain_el).fs; + PPG.v = collated_data(sim_no).output_data(domain_el).PPG(:,distance_el); + + % Find reservoir pressure + Q.v = collated_data(sim_no).output_data(domain_el).Q(:,distance_el); + R = mean(P.v)/mean(Q.v); + + C = 1e-8; + tdia = collated_data(sim_no).input_data.sim_settings.lvet/1000; % ms to secs + tdia = tdia+0.06; + pout = collated_data(sim_no).input_data.sim_settings.p_out; + pout = 0; + options = optimset('MaxFunEvals',1000, 'display', 'off'); + input_vars = [C,pout]; + pres_cost_function = @(input_vars)calculate_pres_cost_function(P, Q, pout, R, tdia, input_vars); + [optimal_input_vars, cost_func] = fminsearch(pres_cost_function,input_vars, options); + %optimal_input_vars(2) + Pres = calc_pres(P,Q,optimal_input_vars(2),R, optimal_input_vars(1)); +% pres_cost_function = @(C)calculate_pres_cost_function(P, Q, pout, R, tdia, C); +% [optimal_C, cost_func] = fminsearch(pres_cost_function,C, options); +% Pres = calc_pres(P,Q,pout,R, optimal_C); + Pexc = P.v - Pres.v; + collated_data(sim_no).output_data(domain_el).Pexc(:,distance_el) = Pexc; + +% rel_els = 309:length(P.v); +% rel_t = [rel_els]/P.fs; rel_t = rel_t(:); +% rel_p = P.v(rel_els); +% +% P_inf = collated_data(sim_no).input_data.sim_settings.p_out; +% %g = fittype('a*exp(b*x)'); +% %g = fittype([num2str(P_inf), ' + ' num2str(P.v(1) - P_inf) '*exp(b*x)']); +% g = fittype(['a + ' num2str(P.v(1) - P_inf) '*exp(b*x)']); +% %options = fitoptions('Method', 'NonlinearLeastSquares','StartPoint', -0.5); +% myfit = fit(rel_t(:),rel_p,g); %, options); +% plot(myfit,rel_t,rel_p) +% RC = -1/myfit.b; +% %RC = 1.57*RC; +% %R = 1.57*R; +% C = RC/R; +% %P_inf = P.v(1)-myfit.a; +% %P_inf = collated_data(sim_no).input_data.sim_settings.p_out; +% P_0 = P.v(1); +% % New Method +% t = [0:length(P.v)-1]/P.fs; t = t(:); +% dt=1/P.fs; +% %RC = RC*1.57; +% qse=cumtrapz(Q.v.*exp(t/RC))*dt; +% P_wk = (exp(-t/RC).*(qse/C)) + (exp(-t/RC)*(P.v(1) - P_inf)) + P_inf; +% P_wk = P_wk/133.33; +% plot(P_wk, 'r') +% clear P_wk +% +% % Old Method +% for t_no = 1 : length(P.v) +% curr_t = (t_no-1)/P.fs; +% term2 = (P_0 - P_inf)*exp(-curr_t/(R*C)); +% term3a = Q.v(1:t_no); term3a = term3a(:); +% term3b = exp((((1:t_no)-1)/P.fs)./(R*C)); term3b = term3b(:); +% term3 = exp(-1*curr_t/(R*C)) * (1/C) * sum(term3a.*term3b) * (1/P.fs); +% temp_P_wk = P_inf + term2 + term3; +% P_wk(t_no,1) = temp_P_wk; +% end +% P_wk = P_wk/133.33; +% plot(P.v/133.33), hold on +% plot(P_wk, '--k') + + [Pr,A,B,Pinf,Tn,Pn]=kreservoir_v10_pc(P.v,length(P.v)-1,282); %collated_data(sim_no).input_data.sim_settings.lvet); + + PexcKP = P.v(:) - Pr(:); + collated_data(sim_no).output_data(domain_el).PexcKP(:,distance_el) = PexcKP; + + do_plot = 0; + if do_plot && domain_el == 1 + plot(P.v), hold on, plot(P.v(1)+Pexc), plot(P.v(1)+PexcKP) + waitfor(gcf) + end + + % Estimate wave speed, c + ave_radius_cm = 100*mean(D.v/2); + rho = collated_data(1).input_data.sim_settings.rho; + k = collated_data(1).input_data.sim_settings.network_spec.k; + Eh_D0 = (k(1)*exp(k(2)*ave_radius_cm))+k(3); % Eh/D0 (from Mynard's 2015 paper, eqn 3) + c0_squared = (2/3)*(Eh_D0/(rho/1000)); % from Mynard's 2015 paper, eqn 3, converts rho from kg/m3 to g/cm3 + c = sqrt(c0_squared)/100; % converts from cm/s to m/s. + + % Perform wave separation to obtain forward and backward P and U waves + dP_f = (diff(P.v) + (rho*c*diff(U.v)))/2; + dP_b = (diff(P.v) - (rho*c*diff(U.v)))/2; + dU_f = (diff(U.v) + (diff(P.v)/(rho*c)))/2; + dU_b = (diff(U.v) - (diff(P.v)/(rho*c)))/2; + dU_f = dP_f/(rho*c); + dU_b = -1*dP_b/(rho*c); + P_f = cumsum(dP_f); + P_b = cumsum(dP_b); + U_f = U.v(1) + cumsum(dU_f); + U_b = U.v(1) + cumsum(dU_b); + + collated_data(sim_no).output_data(domain_el).P_f(:,distance_el) = P_f; + collated_data(sim_no).output_data(domain_el).P_b(:,distance_el) = P_b; + collated_data(sim_no).output_data(domain_el).U_f(:,distance_el) = U_f; + collated_data(sim_no).output_data(domain_el).U_b(:,distance_el) = U_b; + + do_plot = 0; rel_dom_el = 7; + if do_plot && domain_el == rel_dom_el && distance_el == no_distance_els + figure('Position', [20,20,1000,600]) + subplot(2,2,1) + plot(P.v-P.v(1), 'k'), hold on, plot(P_f, 'b'), plot(P_b, 'r') + subplot(2,2,3) + plot(U.v, 'k'), hold on, plot(U_f, 'b'), plot(U_b, 'r') + end + + % Perform wave separation to obtain forward and backward P and U waves + dP_f = (diff(Pexc) + (rho*c*diff(U.v)))/2; + dP_b = (diff(Pexc) - (rho*c*diff(U.v)))/2; + %dP_b = (diff(P.v-PexcKP) - (rho*c*diff(U.v)))/2; + dU_f = (diff(U.v) + (diff(Pexc)/(rho*c)))/2; + dU_b = (diff(U.v) - (diff(Pexc)/(rho*c)))/2; + P_f = cumsum(dP_f); + P_b = cumsum(dP_b); + U_f = U.v(1) + cumsum(dU_f); + U_b = U.v(1) + cumsum(dU_b); + + if do_plot && domain_el == rel_dom_el && distance_el == no_distance_els + subplot(2,2,2) + plot(P.v-P.v(1), 'k'), hold on, plot(P_f, 'b'), plot(P_b, 'r'), plot(P.v-P.v(1)-PexcKP, 'g') + subplot(2,2,4) + plot(U.v, 'k'), hold on, plot(U_f, 'b'), plot(U_b, 'r') + waitfor(gcf) + end + + do_plot = 0; + if do_plot + figure('Position', [100,100,900,400]) + subplot(1,2,1), plot(U.v), hold on, plot(U_f), plot(U_b) + subplot(1,2,2), plot(PPG.v) + close all + end + end + + end + + end +end + + +% save collated data +a = whos('collated_data'); +if a.bytes > 1.8e9 + save(PATHS.collated_data, 'collated_data', '-v7.3') +else + save(PATHS.collated_data, 'collated_data') +end + +end + +function ppg = estimate_ppg_using_windkessel(P, Q, Pout) + +%% Calculate PPG + +% Calculate time vectors for input signals +P.t = [0:length(P.v)-1]/P.fs; +Q.t = [0:length(Q.v)-1]/Q.fs; + +% Find the resistance to flow further down the arterial tree +temp = P.v-Pout.v; % pressure drop between this segment and end of arterial tree +R = sum(temp)/sum(Q.v); % resistance is mean pressure drop over mean flow + +% Find the flow into the more distal part of the arterial tree from this segment +Qout.v = (P.v-Pout.v)./R; % I = V/R (electrical circuit) +Qout.t = P.t; + +% Find the volume stored in the arterial segment +Volvb.t = Q.t; +const = 0; +Volvb.v = const + cumsum(Q.v) - cumsum(Qout.v); % volume stored is the difference between inflow and outflow + +ppg.t = Volvb.t; +% ppg.v = normwave(Volvb.v); +ppg.v = Volvb.v; + +end + +function norm_wave = normwave(orig_wave) + +norm_wave = orig_wave; + +norm_wave = (norm_wave-min(norm_wave))./range(norm_wave); + +end + +function static_wave = calc_static_wave(orig_wave) + +orig_wave = orig_wave(:); + +% Calculate expected position of next point +mean_diff = mean([diff(orig_wave(end-1:end)), diff(orig_wave(1:2))]); +next_point = orig_wave(end) + mean_diff; + +% If the wave was static, then this next point would be equal to the first point +% So, we can make the wave static by making this next point equal to the first +temp = linspace(0,orig_wave(1)-next_point, length(orig_wave)); temp = temp(:); +static_wave = orig_wave + temp; + +end + +function pres_cost_function = calculate_pres_cost_function(P, Q, pout, R, tdia, input_vars) + +% setup +C = input_vars(1); +pout = input_vars(2); + +% calculate reservoir pressure +Pres = calc_pres(P,Q,pout,R, C); + +% assess performance +t = [0:length(Pres.v)-1]/Pres.fs; +duration_dia = t(end) - tdia; +rel_els = t>= (tdia+(1/3)*duration_dia); +%rel_els = t>= tdia; +pres_diffs = P.v(rel_els) - Pres.v(rel_els); + +% plot(t, P.v, 'b'), hold on +% plot(t(rel_els), P.v(rel_els), 'r'), hold on, plot(t(rel_els), Pres.v(rel_els), 'k'), title(num2str(C)) +% waitfor(gcf) + +pres_cost_function = sqrt(mean(pres_diffs.^2)); + +end + +function Pres = calc_pres(P,Q,pout,R, C) + +RC = R*C; +t = [0:length(P.v)-1]/P.fs; t = t(:); +dt=1/P.fs; +qse=cumtrapz(Q.v.*exp(t/RC))*dt; +Pres.v = (exp(-t/RC).*(qse/C)) + (exp(-t/RC)*(P.v(1) - pout)) + pout; +Pres.fs = P.fs; +end +","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/setup_paths_for_post_processing.m",".m","5583","88","function PATHS = setup_paths_for_post_processing(pwdb_no) + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% This line specifies the location of the storage folder % +% which the input and output files are copied into % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +PATHS.storage_folder = '/Users/petercharlton/Documents/Data/Nektar1D/ageing_sims/'; + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% This line specifies the location of the shared folder % +% containing the simulation input and output files % +% (this can be left alone unless reproducing the PWDB) % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +PATHS.shared_folder = '/Users/petercharlton/Documents/VM-share/'; + +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +%%%%%%%%%%% The rest of this function can be left alone %%%%%%%% + +% setup +if nargin>0 + fprintf([' (PWDB no. ' num2str(pwdb_no), ')\n']) +end +close all + +PATHS.slash_dirn = filesep; + +% add additional functions to path +[a,~,~] = fileparts(mfilename('fullpath')); +addpath(genpath(a)) + +if nargin > 0 + % Specify paths + PATHS.pwdb_filename_prefix = 'pwdb'; % for use in creating exported data files. + PATHS.OutputFiles = [PATHS.storage_folder, 'pwdb_' num2str(pwdb_no), PATHS.slash_dirn, 'output_data', PATHS.slash_dirn]; + PATHS.InputFiles = [PATHS.storage_folder, 'pwdb_' num2str(pwdb_no), PATHS.slash_dirn, 'input_data', PATHS.slash_dirn]; + PATHS.ProcessedData = [PATHS.storage_folder, 'pwdb_' num2str(pwdb_no), PATHS.slash_dirn, 'processed_data', PATHS.slash_dirn]; + PATHS.exported_data = [PATHS.storage_folder, 'pwdb_' num2str(pwdb_no), filesep, 'exported_data', filesep]; + PATHS.CaseStudies = [PATHS.storage_folder, 'pwdb_' num2str(pwdb_no), filesep, 'case_studies', filesep]; + PATHS.Analysis = [PATHS.storage_folder, 'pwdb_' num2str(pwdb_no), filesep, 'analysis', filesep]; + PATHS.Analysis_tables = [PATHS.storage_folder, 'pwdb_' num2str(pwdb_no), filesep, 'analysis', filesep, 'tables', filesep]; + PATHS.Analysis_figures = [PATHS.storage_folder, 'pwdb_' num2str(pwdb_no), filesep, 'analysis', filesep, 'figures', filesep]; + PATHS.history_files_data = [PATHS.ProcessedData, 'history_files_data.mat']; + PATHS.collated_data = [PATHS.ProcessedData, 'collated_data.mat']; + PATHS.haemodynamic_params = [PATHS.ProcessedData, 'haemodynamic_params.mat']; + PATHS.pulse_wave_params = [PATHS.ProcessedData, 'pulse_wave_params.mat']; + PATHS.pulse_wave_vels = [PATHS.ProcessedData, 'pulse_wave_vels.mat']; + PATHS.pulse_wave_inds = [PATHS.ProcessedData, 'pulse_wave_inds.mat']; + PATHS.table_data = [PATHS.Analysis_tables, 'table_data.mat']; + PATHS.baseline_waves_fig_a = [PATHS.Analysis_figures, 'baseline_waves_fig_a']; + PATHS.baseline_waves_fig_b = [PATHS.Analysis_figures, 'baseline_waves_fig_b']; + PATHS.pw_propagation_fig = [PATHS.Analysis_figures, 'pw_propagation_fig']; + PATHS.pw_path_fig = [PATHS.Analysis_figures, 'pw_path_fig']; + PATHS.wave_speed_fig = [PATHS.Analysis_figures, 'wave_speed_fig']; + PATHS.characteristics_table = [PATHS.Analysis_tables, 'characteristics_table']; + PATHS.characteristics_table_range = [PATHS.Analysis_tables, 'characteristics_table_range']; + PATHS.system_chars = [PATHS.ProcessedData, 'system_chars.mat']; + PATHS.exported_data_mat = [PATHS.exported_data, 'PWs', filesep, 'mat', filesep]; + PATHS.exported_data_csv = [PATHS.exported_data, 'PWs', filesep, 'csv', filesep]; + PATHS.exported_data_wfdb = [PATHS.exported_data, 'PWs', filesep, 'wfdb', filesep]; + PATHS.exported_data_geo = [PATHS.exported_data, 'geo', filesep]; + PATHS.exported_data_mat_pwdb_data = [PATHS.exported_data, PATHS.pwdb_filename_prefix, '_data.mat']; + PATHS.exported_data_mat_pwdb_data_w_aorta_finger_path = [PATHS.exported_data, PATHS.pwdb_filename_prefix, '_data_w_aorta_finger_path.mat']; + PATHS.exported_data_mat_pwdb_data_w_aorta_foot_path_p = [PATHS.exported_data, PATHS.pwdb_filename_prefix, '_data_w_aorta_foot_path_p.mat']; + PATHS.exported_data_mat_pwdb_data_w_aorta_foot_path_u = [PATHS.exported_data, PATHS.pwdb_filename_prefix, '_data_w_aorta_foot_path_u.mat']; + PATHS.exported_data_mat_pwdb_data_w_aorta_foot_path_a = [PATHS.exported_data, PATHS.pwdb_filename_prefix, '_data_w_aorta_foot_path_a.mat']; + PATHS.exported_data_mat_pwdb_data_w_aorta_brain_path = [PATHS.exported_data, PATHS.pwdb_filename_prefix, '_data_w_aorta_brain_path.mat']; + PATHS.exported_data_mat_pwdb_data_w_aorta_rsubclavian_path = [PATHS.exported_data, PATHS.pwdb_filename_prefix, '_data_w_aorta_rsubclavian_path.mat']; + PATHS.exported_data_model_configs = [PATHS.exported_data, PATHS.pwdb_filename_prefix, '_model_configs.csv']; + PATHS.peripheral_boundarys = [PATHS.ProcessedData, 'peripheral_boundarys.mat']; + PATHS.exported_data_onset_times = [PATHS.exported_data, PATHS.pwdb_filename_prefix, '_onset_times.csv']; + + % case studies + PATHS.collated_ASIs = [PATHS.CaseStudies, 'collated_ASIs.mat']; + PATHS.ASI_results = [PATHS.CaseStudies, 'ASI_results.mat']; + + % Create required folders + req_folders = {PATHS.storage_folder, PATHS.InputFiles, PATHS.OutputFiles, PATHS.ProcessedData, PATHS.CaseStudies}; + for folder_no = 1 : length(req_folders) + curr_folder = req_folders{folder_no}; + if ~exist(curr_folder, 'dir') + mkdir(curr_folder) + end + clear curr_folder + end + clear folder_no req_folders +end + +end","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/ppamp_case_study.m",".m","7902","206","function ppamp_case_study(pwdb_no) +% PPAMP_CASE_STUDY generates the plots reported in the case study on the +% determinants of pulse pressure amplification. +% +% ppamp_case_study +% +% Inputs: - the 'pwdb_data.mat' file produced by 'export_pwdb.m'. +% +% Outputs: - plots illustrating the results of the case study +% +% Accompanying Article: +% This code is provided to facilitate reproduction of the Pulse Wave +% Database described in: +% Charlton P.H. et al. Modelling arterial pulse waves in healthy +% ageing: a database for in silico evaluation of haemodynamics +% and pulse wave indices, ~~ under review ~~ +% DOI: ~~ tbc ~~ +% Further information on the pwdb Pulse Wave Database is provided in +% this article and at the project website: +% https://peterhcharlton.github.io/pwdb +% +% Author: Peter H. Charlton +% +% Licence: +% Permission is hereby granted, free of charge, to any person obtaining a copy +% of this software and associated documentation files (the ""Software""), to deal +% in the Software without restriction, including without limitation the rights +% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +% copies of the Software, and to permit persons to whom the Software is +% furnished to do so, subject to the following conditions: +% +% The above copyright notice and this permission notice shall be included in all +% copies or substantial portions of the Software. +% +% THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +% SOFTWARE. +% +% Copyright (C) 2019 King's College London +% +% v.1.0 Peter H Charlton, King's College London + +fprintf('\n --- Running Pulse Pressure Amplification (PP_amp) Case Study ---') + +% Setup paths with current simulation paths +PATHS = setup_paths_for_post_processing(pwdb_no); + +% Collate data +data = load_data(PATHS); + +% Investigate +make_plots(data, PATHS); + +end + +function data = load_data(PATHS) + +fprintf('\n - Loading data') + +% Load all data +load(PATHS.exported_data_mat_pwdb_data); + +end + +function make_plots(data, PATHS) + +fprintf('\n - Making Plots') + +rel_fields = {'PWV_a', 'age', 'dia_asc_a', 'P1in_a', 'P2in_a', 'SV', 'HR', 'LVET', 'CO', 'PP_amp', 'PWV_cf', 'PWV_br', 'DBP_a', 'P1pk_a', 'P2pk_a', 'PP_a', 'AP_a', 'DBP_b', 'P1pk_b', 'P2pk_b', 'P1in_b', 'P2in_b', 'PP_b', 'PP_f', 'SBP_a', 'SBP_b', 'MBP_a', 'MBP_b', 'dia_asc_a', 'SMBP_a', 'SBP_diff', 'c', 'AI_a', 'AI_c', 'P1in_c'}; +for field_no = 1 : length(rel_fields) + + curr_field = rel_fields{field_no}; + eval(['d.' curr_field ' = extractfield(data.haemods, ''' curr_field ''');']); + +end + +%% Make plot of PPamp vs age (using P1 and P2) + +ages = unique(d.age); +for age_no = 1 : length(ages) + curr_age = ages(age_no); + rel_els = d.age == curr_age & data.plausibility.plausibility_log(:)'; + sbpb.v(age_no) = mean(d.SBP_b(rel_els)); + sbpb.sd(age_no) = std(d.SBP_b(rel_els)); + p1a.v(age_no) = mean(d.P1in_a(rel_els)); + p1a.sd(age_no) = std(d.P1in_a(rel_els)); + p1b.v(age_no) = mean(d.P1in_b(rel_els)); + p1b.sd(age_no) = std(d.P1in_b(rel_els)); + p2a.v(age_no) = mean(d.P2pk_a(rel_els)); + p2a.sd(age_no) = std(d.P2pk_a(rel_els)); + p2b.v(age_no) = mean(d.P2pk_b(rel_els)); + p2b.sd(age_no) = std(d.P2pk_b(rel_els)); + dbpb.v(age_no) = mean(d.DBP_b(rel_els)); + dbpb.sd(age_no) = std(d.DBP_b(rel_els)); + sbpa.v(age_no) = mean(d.SBP_a(rel_els)); + sbpa.sd(age_no) = std(d.SBP_a(rel_els)); + dbpa.v(age_no) = mean(d.DBP_a(rel_els)); + dbpa.sd(age_no) = std(d.DBP_a(rel_els)); + apa.v(age_no) = mean(d.AP_a(rel_els)); + apa.sd(age_no) = std(d.AP_a(rel_els)); + ppamp.v(age_no) = mean( (d.SBP_b(rel_els)-d.DBP_b(rel_els))./(d.SBP_a(rel_els)-d.DBP_a(rel_els)) ); + ppamp.sd(age_no) = std( (d.SBP_b(rel_els)-d.DBP_b(rel_els))./(d.SBP_a(rel_els)-d.DBP_a(rel_els)) ); + ppamp_p1.v(age_no) = mean( (d.SBP_b(rel_els)-d.DBP_b(rel_els))./(d.P1in_a(rel_els)-d.DBP_a(rel_els)) ); + ppamp_p1.sd(age_no) = std( (d.SBP_b(rel_els)-d.DBP_b(rel_els))./(d.P1in_a(rel_els)-d.DBP_a(rel_els)) ); + ppamp_p2.v(age_no) = mean( (d.SBP_b(rel_els)-d.DBP_b(rel_els))./(d.P2pk_a(rel_els)-d.DBP_a(rel_els)) ); + ppamp_p2.sd(age_no) = std( (d.SBP_b(rel_els)-d.DBP_b(rel_els))./(d.P2pk_a(rel_els)-d.DBP_a(rel_els)) ); +end + +ftsize = 16; lwidth = 2; +age_ticks = unique(data.config.age); +ppamp_types = {'ppamp_p1', 'ppamp_p2', 'ppamp'}; +req_colors = {[1 0 0], [0 0 1], [0 0 0]}; +no_sd = 1; up.ylim_offset = 1.1; jitter = 0.6; +for type_no = 1 : length(ppamp_types) + + req_color= req_colors{type_no}; + eval(['rel_data = ' ppamp_types{type_no} ';']); + rel_data.age = ages; + + errorbar(rel_data.age-(2-type_no)*jitter, rel_data.v, rel_data.sd, '-o', 'Color', req_color, 'LineWidth', 2), hold on + + % tidy up + xlabel('Age [years]', 'FontSize', ftsize) + ylabel('PP_{amp} [ratio]', 'FontSize', ftsize) + set(gca, 'FontSize', ftsize, 'XTick', age_ticks) + xlim([20,80]) + grid on + box off + +end +leg_labels = {'PP_b / (P1_a - DBP_a)', 'PP_b / (P2_a - DBP_a)', 'PP_b / (SBP_a - DBP_a) = PP_{amp}'}; +legend(leg_labels, 'Location', 'NorthWest', 'FontSize', ftsize-4) +paper_size = [500,350]; +PrintFigs(gcf, paper_size/70, [PATHS.CaseStudies, 'PPamp_amp_aug']) + +%% Make plots of determinants + +paper_size = [500,350]; + + +figure('Position', [20 20 paper_size]) +plot(d.PWV_a.*d.LVET/1000, d.PP_b./(d.P2pk_a-d.DBP_a), '.') % keep this +set(gca, 'FontSize', ftsize) +xlabel('Aortic PWV x LVET [m]', 'FontSize', ftsize) +ylabel('PP_b / (P2_a - DBP_a)', 'FontSize', ftsize) +box off +grid on +PrintFigs(gcf, paper_size/70, [PATHS.CaseStudies, 'PPamp_p2']) + +figure('Position', [20 20 paper_size]) +plot(d.dia_asc_a, d.PP_b./(d.P1in_a-d.DBP_a), '.') % keep this +set(gca, 'FontSize', ftsize) +xlabel('Ascending Aortic Diameter [mm]', 'FontSize', ftsize) +ylabel('PP_b / (P1_a - DBP_a)', 'FontSize', ftsize) +box off +grid on +PrintFigs(gcf, paper_size/70, [PATHS.CaseStudies, 'PPamp_p1']) + +figure('Position', [20 20 paper_size]) +plot(d.PWV_a.*d.LVET/1000, d.PP_amp, '.') % keep this +set(gca, 'FontSize', ftsize) +xlabel('Aortic PWV x LVET [m]', 'FontSize', ftsize) +ylabel('PP_{amp}', 'FontSize', ftsize) +box off +grid on +PrintFigs(gcf, paper_size/70, [PATHS.CaseStudies, 'PPamp']) + + +end + +function PrintFigs(h, paper_size, savepath, close_plot) +set(h,'PaperUnits','inches'); +set(h,'PaperSize', [paper_size(1), paper_size(2)]); +set(h,'PaperPosition',[0 0 paper_size(1) paper_size(2)]); +set(gcf,'color','w'); +print(h,'-dpdf',savepath) +print(h,'-depsc',savepath) +%print(h,'-dpng',savepath) + +% if you want .eps illustrations, then do as follows: +up.eps_figs = 0; +if up.eps_figs + % you need to download 'export_fig' from: + % http://uk.mathworks.com/matlabcentral/fileexchange/23629-export-fig + export_fig_dir_path = 'C:\Documents\Google Drive\Work\Projects\PhD\Github\phd\Tools\Other Scripts\export_fig\altmany-export_fig-76bd7fa\'; + addpath(export_fig_dir_path) + export_fig(savepath, '-eps') +end + +if nargin > 3 && ~close_plot +else + close all; +end + +% save +fid = fopen([savepath, '.txt'], 'w'); +p = mfilename('fullpath'); +p = strrep(p, '\', '\\'); +fprintf(fid, ['Figures generated by:\n\n ' p '.m \n\n on ' datestr(today)]); +fclose all; + +end","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/pwdb_pwa.m",".m","60719","1156","function pwdb_pwa(pwdb_no) +% PWDB_PWA derives parameters from pulse waves, and saves them in +% Matlab format. +% +% pwdb_pwa +% +% Inputs: the 'collated_data.mat' file produced by 'extract_pwdb_simulation_data.m'. +% +% Outputs: - Matlab files containing the pulse wave parameters: +% pulse_wave_inds.mat +% pulse_wave_vels.mat +% haemodynamic_params.mat +% +% Accompanying Article: +% This code is provided to facilitate reproduction of the Pulse Wave +% Database described in: +% Charlton P.H. et al. Modelling arterial pulse waves in healthy +% ageing: in silico evaluation of haemodynamics and +% pulse wave indices, ~~ under review ~~ +% DOI: ~~ tbc ~~ +% Further information on the pwdb Pulse Wave Database is provided in +% this article and at the project website: +% https://peterhcharlton.github.io/pwdb +% +% Author: Peter H. Charlton +% +% Licence: +% Permission is hereby granted, free of charge, to any person obtaining a copy +% of this software and associated documentation files (the ""Software""), to deal +% in the Software without restriction, including without limitation the rights +% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +% copies of the Software, and to permit persons to whom the Software is +% furnished to do so, subject to the following conditions: +% +% The above copyright notice and this permission notice shall be included in all +% copies or substantial portions of the Software. +% +% THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +% SOFTWARE. +% +% Copyright (C) 2019 King's College London +% +% v.1.0 Contributed to by: Marie Willemet, Jordi Alastruey, and Peter H. Charlton + +fprintf('\n --- Performing Pulse Wave Analysis ---') + +%% Settings +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +% SETTINGS TO CHANGE: This function specifies where to save the outputs % +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% +PATHS = setup_paths_for_post_processing(pwdb_no); +%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% + +props.carotid = 0.5; + +% Extract pulse wave velocities +if ~exist(PATHS.pulse_wave_vels, 'file') + if ~exist('collated_data', 'var'), load(PATHS.collated_data), end + extract_pulse_wave_velocities(PATHS, props, collated_data); +end + +% Extract pulse wave parameters +if ~exist(PATHS.pulse_wave_inds, 'file') + if ~exist('collated_data', 'var'), load(PATHS.collated_data), end + extract_pulse_wave_inds(PATHS, props, collated_data); +end + +% Extract haemodynamic parameters +if ~exist(PATHS.haemodynamic_params, 'file') + if ~exist('collated_data', 'var'), load(PATHS.collated_data), end + extract_haemodynamic_parameters(PATHS, props, collated_data); +end + +fprintf('\n --- Finished analysing PWDB pulse waves ---\n') + +end + +function extract_pulse_wave_velocities(PATHS, props, collated_data) + +fprintf('\n Extracting pulse wave velocities:') + +% setup +sim_data.domain_nos = extractfield(collated_data(1).output_data, 'domain_no'); + +%% Extract PWVs +fprintf('\n - PWVs: ') +pwv_types = {'carotid_femoral', 'carotid_radial', 'carotid_ankle', 'carotid_brachial', ... + 'brachial_femoral', 'brachial_radial', 'brachial_ankle', ... + 'radial_femoral', 'radial_ankle', ... + 'femoral_ankle', ... + 'aorta_iliacbif'}; + +TT_waveform_ind = 1; % for pressure waves +for sim_no = 1 : length(collated_data) + fprintf([num2str(sim_no) ', ']); + sim_data.output_data = collated_data(sim_no).output_data; + sim_data.input_data = collated_data(sim_no).input_data; + + for pwv_type_no = 1 : length(pwv_types) + curr_pwv_type = pwv_types{pwv_type_no}; + + % identify two sites + temp = strfind(curr_pwv_type, '_'); + site1.name = curr_pwv_type(1:temp-1); + site2.name = curr_pwv_type(temp+1:end); + + % Extract information for each site + for site_no = 1 : 2 + % identify this site + eval(['curr_site = site' num2str(site_no) ';']) + % extract geometric data for this site + switch curr_site.name + case 'carotid' + curr_site.preceeding_domains = [1,2]; + curr_site.domain_no = 15; + curr_site.distance_prop = props.carotid; + case 'femoral' + curr_site.preceeding_domains = [1,2,14,18,27,28,35,37,39,41,42,44]; + curr_site.domain_no = 46; + curr_site.distance_prop = 0.5; + case 'radial' + curr_site.preceeding_domains = [1,2,14,19,21]; + curr_site.domain_no = 22; + curr_site.distance_prop = 1; + case 'ankle' + curr_site.preceeding_domains = [1,2,14,18,27,28,35,37,39,41,42,44,46]; + curr_site.domain_no = 49; + curr_site.distance_prop = 1; + case 'brachial' + curr_site.preceeding_domains = [1,2,14,19]; + curr_site.domain_no = 21; + curr_site.distance_prop = 0.75; + case 'aorta' + curr_site.preceeding_domains = []; + curr_site.domain_no = 1; + curr_site.distance_prop = 0; + case 'iliacbif' + curr_site.preceeding_domains = [1,2,14,18,27,28,35,37,39]; + curr_site.domain_no = 41; + curr_site.distance_prop = 1; + end + % calculate path length + curr_site.len_aorta_site = sum([sim_data.input_data.sim_settings.network_spec.length(curr_site.preceeding_domains); sim_data.input_data.sim_settings.network_spec.length(curr_site.domain_no)*curr_site.distance_prop]); + + % extract waveform data for this site + curr_site.domain_row = find(sim_data.domain_nos == curr_site.domain_no); + curr_site.seg_len = sim_data.input_data.sim_settings.network_spec.length(curr_site.domain_no); + [~, curr_site.distance_el] = min(abs(sim_data.output_data(curr_site.domain_row).distances-(curr_site.distance_prop*curr_site.seg_len))); + curr_site.v = sim_data.output_data(curr_site.domain_row).P(:,curr_site.distance_el); + curr_site.start_sample = sim_data.output_data(curr_site.domain_row).start_sample(curr_site.distance_el); + curr_site.no_samps_in_beat = length(sim_data.output_data(curr_site.domain_row).P(:,curr_site.distance_el)); + + % store data for this site + eval(['site' num2str(site_no) ' = curr_site;']) + end + clear site_no + path_len = site2.len_aorta_site - site1.len_aorta_site; + + % check to see if the length of each wave is similar + lens = [length(site1.v), length(site2.v)]; + if abs(diff(lens))/min(lens) > 0.1 + fprintf(['Different length PWs for sim ' num2str(sim_no) ', ' curr_pwv_type]) + Foot_TT = nan; + else + + % time-align waves + if site2.start_sample < site1.start_sample + % then the peripheral wave has been extracted from the previous simulated wave + site2.start_sample = site2.start_sample + site2.no_samps_in_beat; + end + delay = site2.start_sample - site1.start_sample; + site2.v = site2.v([end-delay:end,1:(end-delay-1)]); + + % check waves are same duration + if length(site2.v) == length(site1.v)+1 + site2.v = site2.v(1:end-1); + elseif length(site2.v) == length(site1.v)+2 + site2.v = site2.v(1:end-2); + elseif length(site1.v) == length(site2.v)+1 + site1.v = site1.v(1:end-1); + elseif length(site1.v) == length(site2.v)+2 + site1.v = site1.v(1:end-2); + end + if length(site2.v) ~= length(site1.v) + fprintf(['Different length PWs for sim ' num2str(sim_no) ', ' curr_pwv_type]) + Foot_TT = nan; + else + % repeat waves + temp = linspace(site1.v(1),site1.v(end),length(site1.v)); + site1.v = site1.v+site1.v(1)-temp(:); + site1.v = repmat(site1.v, [5,1]); + temp = linspace(site2.v(1),site2.v(end),length(site2.v)); + site2.v = site2.v+site2.v(1)-temp(:); + site2.v = repmat(site2.v, [5,1]); + + %plot(site1.v), hold on, plot(site2.v), xlim([0 1000]) + %close all + + % calculate PWV + algo_ind = 1; % 1- foot-to-foot algorithm; 4- least squares algorithm + Foot_TT = TTAlgorithm([site1.v site2.v],sim_data.output_data(1).fs,algo_ind,TT_waveform_ind,1,0); + end + + end + curr_pwv = path_len./Foot_TT(1); + +% % setup for this pwv type +% switch curr_pwv_type +% case 'carotid_femoral' +% % % Previously worked: +% % wave1_domain_no = 15; +% % wave1_distance_prop = 1; +% % wave2_domain_no = 46; +% % wave2_distance_prop = 0; +% % len_aorta_carotid = sum(sim_data.input_data.sim_settings.network_spec.length([1,2,15])); +% % len_aorta_femoral = sum(sim_data.input_data.sim_settings.network_spec.length([1,2,14,18,27,28,35,37,39,41,42,44])); +% % In keeping with calculation of input parameters: +% wave1_domain_no = 15; +% wave1_distance_prop = props.carotid; +% wave2_domain_no = 46; +% wave2_distance_prop = 0.5; +% len_aorta_carotid = sum([sim_data.input_data.sim_settings.network_spec.length([1,2]); sim_data.input_data.sim_settings.network_spec.length(15)*props.carotid]); +% len_aorta_femoral = sum([sim_data.input_data.sim_settings.network_spec.length([1,2,14,18,27,28,35,37,39,41,42,44]); sim_data.input_data.sim_settings.network_spec.length(46)/2]); +% % Calculate path length: +% path_len = len_aorta_femoral-len_aorta_carotid; +% +% case 'carotid_radial' +% wave1_domain_no = 15; +% wave1_distance_prop = props.carotid; +% wave2_domain_no = 22; +% wave2_distance_prop = 1; +% len_aorta_carotid = sum([sim_data.input_data.sim_settings.network_spec.length([1,2]); sim_data.input_data.sim_settings.network_spec.length(15)*props.carotid]); +% len_aorta_radial = sum(sim_data.input_data.sim_settings.network_spec.length([1,2,14,19,21,22])); +% path_len = len_aorta_radial-len_aorta_carotid; +% +% case 'brachial_radial' +% wave1_domain_no = 21; +% wave1_distance_prop = 0.75; +% wave2_domain_no = 22; +% wave2_distance_prop = 1; +% len_aorta_radial = sum(sim_data.input_data.sim_settings.network_spec.length([1,2,14,19,21,22])); +% len_aorta_brachial = sum(sim_data.input_data.sim_settings.network_spec.length([1,2,14,19])) + ... +% (sim_data.input_data.sim_settings.network_spec.length(21)*wave1_distance_prop); +% path_len = len_aorta_radial-len_aorta_brachial; +% +% case 'brachial_ankle' +% wave1_domain_no = 21; +% wave1_distance_prop = 0.75; +% wave2_domain_no = 49; +% wave2_distance_prop = 1; +% len_aorta_brachial = sum(sim_data.input_data.sim_settings.network_spec.length([1,2,14,19])) + ... +% (sim_data.input_data.sim_settings.network_spec.length(21)*wave1_distance_prop); +% len_aorta_ankle = sum(sim_data.input_data.sim_settings.network_spec.length( [1,2,14,18,27,28,35,37,39,41,42,44,46,49] )); +% path_len = len_aorta_ankle-len_aorta_brachial; +% +% case 'femoral_ankle' +% wave1_domain_no = 46; +% wave1_distance_prop = 0.5; +% wave2_domain_no = 49; +% wave2_distance_prop = 1; +% len_aorta_femoral = sum([sim_data.input_data.sim_settings.network_spec.length([1,2,14,18,27,28,35,37,39,41,42,44]); sim_data.input_data.sim_settings.network_spec.length(46)/2]); +% len_aorta_ankle = sum(sim_data.input_data.sim_settings.network_spec.length( [1,2,14,18,27,28,35,37,39,41,42,44,46,49] )); +% path_len = len_aorta_ankle-len_aorta_femoral; +% +% case 'aortic' +% wave1_domain_no = 1; +% wave1_distance_prop = 0; +% wave2_domain_no = 41; +% wave2_distance_prop = 1; +% path_len = sum(sim_data.input_data.sim_settings.network_spec.length([1,2,14,18,27,28,35,37,39,41])); +% end +% +% % extract required data +% domain_row = find(sim_data.domain_nos == wave1_domain_no); +% len = sim_data.input_data.sim_settings.network_spec.length(wave1_domain_no); +% [~, wave1_distance_el] = min(abs(sim_data.output_data(domain_row).distances-(wave1_distance_prop*len))); +% wave1.v = sim_data.output_data(domain_row).P(:,wave1_distance_el); +% %wave1.no_samps_in_beat = length(sim_data.output_data(domain_row).P(:,wave1_distance_el)); +% %wave1.start_sample = rem(sim_data.output_data(domain_row).start_sample(wave1_distance_el), wave1.no_samps_in_beat); +% wave1.start_sample = sim_data.output_data(domain_row).start_sample(wave1_distance_el); +% %if wave1.start_sample > 0.5*wave1.no_samps_in_beat +% % wave1.start_sample = wave1.no_samps_in_beat - wave1.start_sample; +% %end +% domain_row = find(sim_data.domain_nos == wave2_domain_no); +% len = sim_data.input_data.sim_settings.network_spec.length(wave2_domain_no); +% [~, wave2_distance_el] = min(abs(sim_data.output_data(domain_row).distances-(wave2_distance_prop*len))); +% wave2.v = sim_data.output_data(domain_row).P(:,wave2_distance_el); +% wave2.no_samps_in_beat = length(sim_data.output_data(domain_row).P(:,wave2_distance_el)); +% %wave2.start_sample = rem(sim_data.output_data(domain_row).start_sample(wave2_distance_el), wave2.no_samps_in_beat); +% wave2.start_sample = sim_data.output_data(domain_row).start_sample(wave2_distance_el); +% %if wave2.start_sample > 0.5*wave2.no_samps_in_beat +% % wave2.start_sample = wave2.no_samps_in_beat - wave2.start_sample; +% %end +% clear domain_row +% +% % check to see if the length of each wave is similar +% lens = [length(wave1.v), length(wave2.v)]; +% if abs(diff(lens))/min(lens) > 0.1 +% fprintf(['Different length PWs for sim ' num2str(sim_no) ', ' curr_pwv_type]) +% Foot_TT = nan; +% else +% +% % time-align waves +% if wave2.start_sample < wave1.start_sample +% % then the peripheral wave has been extracted from the previous simulated wave +% wave2.start_sample = wave2.start_sample + wave2.no_samps_in_beat; +% end +% delay = wave2.start_sample - wave1.start_sample; +% wave2.v = wave2.v([end-delay:end,1:(end-delay-1)]); +% +% % check waves are same duration +% if length(wave2.v) == length(wave1.v)+1 +% wave2.v = wave2.v(1:end-1); +% elseif length(wave2.v) == length(wave1.v)+2 +% wave2.v = wave2.v(1:end-2); +% elseif length(wave1.v) == length(wave2.v)+1 +% wave1.v = wave1.v(1:end-1); +% elseif length(wave1.v) == length(wave2.v)+2 +% wave1.v = wave1.v(1:end-2); +% end +% if length(wave2.v) ~= length(wave1.v) +% fprintf(['Different length PWs for sim ' num2str(sim_no) ', ' curr_pwv_type]) +% Foot_TT = nan; +% else +% % repeat waves +% temp = linspace(wave1.v(1),wave1.v(end),length(wave1.v)); +% wave1.v = wave1.v+wave1.v(1)-temp(:); +% wave1.v = repmat(wave1.v, [5,1]); +% temp = linspace(wave2.v(1),wave2.v(end),length(wave2.v)); +% wave2.v = wave2.v+wave2.v(1)-temp(:); +% wave2.v = repmat(wave2.v, [5,1]); +% +% %plot(wave1.v), hold on, plot(wave2.v), xlim([0 1000]) +% %close all +% +% % calculate PWV +% algo_ind = 1; % 1- foot-to-foot algorithm; 4- least squares algorithm +% Foot_TT = TTAlgorithm([wave1.v wave2.v],sim_data.output_data(1).fs,algo_ind,TT_waveform_ind,1,0); +% end +% +% end +% +% % if strcmp(curr_pwv_type, 'brachial_radial') +% % algo_ind = 1; % foot-to-foot algorithm +% % Foot_TT_old = TTAlgorithm([wave1.v wave2.v],sim_data.output_data(1).fs,algo_ind,TT_waveform_ind,1,0); +% % 100*(Foot_TT_old(1)-Foot_TT(1))/Foot_TT(1) +% % 100*((delay/1000)-Foot_TT(1))/Foot_TT(1) +% % end +% +% curr_pwv = path_len./Foot_TT(1); + + % store this PWV + eval(['pulse_wave_vels(sim_no).pwv.' curr_pwv_type ' = curr_pwv;']); + eval(['pulse_wave_vels(sim_no).ptt.' curr_pwv_type ' = Foot_TT(1);']); + + % calculate theoretical PWV + [theor_pwv, theor_ptt] = calculate_theoretical_pwv(site1, site2, sim_data); + eval(['pulse_wave_vels(sim_no).pwv_theor.' curr_pwv_type ' = theor_pwv;']); + eval(['pulse_wave_vels(sim_no).ptt_theor.' curr_pwv_type ' = theor_ptt;']); + + clear wave1* wave2* theor_pwv theor_ptt curr_pwv Foot_TT site1 site2 + end + clear curr_pwv_type pwv_type_no +end + +% save +save(PATHS.pulse_wave_vels, 'pulse_wave_vels') + +end + +function [theor_pwv, theor_ptt] = calculate_theoretical_pwv(site1, site2, sim_data) + +n_mini_segs = 10; +k = sim_data.input_data.sim_settings.network_spec.k; +rho = sim_data.input_data.sim_settings.rho; +domain_nos = extractfield(sim_data.output_data, 'domain_no'); + +for site_no = 1 :2 + + % Extract data for this site + eval(['curr_site = site' num2str(site_no) ';']) + + % Extract information on segments leading up to this site + % - these are the prescribed values + segs.in_rad = sim_data.input_data.sim_settings.network_spec.inlet_radius([curr_site.preceeding_domains, curr_site.domain_no]); + segs.out_rad = sim_data.input_data.sim_settings.network_spec.outlet_radius([curr_site.preceeding_domains, curr_site.domain_no]); + temp = segs.in_rad(end) - (segs.in_rad(end) - segs.out_rad(end))*curr_site.distance_prop; + segs.out_rad(end) = temp; clear temp + clear segs + + % - these are the simulated values (assuming linear tapering again) + no_segs = length(curr_site.preceeding_domains)+1; + for seg_no = 1 : no_segs + if seg_no < no_segs + curr_seg = curr_site.preceeding_domains(seg_no); + temp_dist_prop = 1; + else + curr_seg = curr_site.domain_no; + temp_dist_prop = curr_site.distance_prop; + end + rel_row = domain_nos == curr_seg; + dists = sim_data.output_data(rel_row).distances; + rel_dists = dists(dists<= sim_data.input_data.sim_settings.network_spec.length(curr_site.domain_no)*temp_dist_prop); + rel_cols = 1:length(rel_dists); + segs.in_rad(seg_no) = sqrt(mean(sim_data.output_data(rel_row).A(:,rel_cols(1)))/pi); + segs.out_rad(seg_no) = sqrt(mean(sim_data.output_data(rel_row).A(:,rel_cols(end)))/pi); + end + + % - lengths + segs.len = [sim_data.input_data.sim_settings.network_spec.length(curr_site.preceeding_domains); sim_data.input_data.sim_settings.network_spec.length(curr_site.domain_no)*curr_site.distance_prop]; + + % calculate theoretical ptts for each segment, and ptt for this site + for seg_no = 1 : length(segs.in_rad) + temp = linspace(segs.in_rad(seg_no), segs.out_rad(seg_no), n_mini_segs+1); + mini_segs.in_rad = temp(1:end-1); + mini_segs.out_rad = temp(2:end); + mini_segs.len = ones(n_mini_segs,1)*segs.len(seg_no)/n_mini_segs; + mini_segs.mean_rad = mean([mini_segs.in_rad(:), mini_segs.out_rad(:)],2); + mini_segs.wave_speed = empirical_wave_speed(mini_segs.mean_rad, k, rho); + mini_segs.ptt = mini_segs.len./mini_segs.wave_speed; + segs.ptt(seg_no) = sum(mini_segs.ptt); + clear mini_segs temp + end + clear seg_no + + curr_site.theor_ptt = sum(segs.ptt); + clear segs + + % Store data for this site + eval(['site' num2str(site_no) ' = curr_site;']) + +end +clear site_no + +% calculate theoretical pwv for this pair of sites +theor_ptt = site2.theor_ptt - site1.theor_ptt; +overall_len = site2.len_aorta_site - site1.len_aorta_site; +theor_pwv = overall_len/theor_ptt; + +end + +function wave_speed = empirical_wave_speed(ave_radius, k, rho) + +ave_radius_cm = ave_radius*100; + +Eh_D0 = (k(1)*exp(k(2)*ave_radius_cm))+k(3); % Eh/D0 (from Mynard's 2015 paper, eqn 3) +c0_squared = (2/3)*(Eh_D0/(rho/1000)); % from Mynard's 2015 paper, eqn 3, converts rho from kg/m3 to g/cm3 +wave_speed = sqrt(c0_squared)/100; % converts from cm/s to m/s. + +end + +function extract_pulse_wave_inds(PATHS, props, collated_data) + +%% extract pulse indices +fprintf('\n - pulse indices: ') + +% setup +options.do_plot = 0; +do_req_domains = 1; +if do_req_domains + sites = {'AorticRoot', 'ThorAorta', 'AbdAorta', 'IliacBif', 'Carotid', 'SupTemporal', 'SupMidCerebral', 'Brachial', 'Radial', 'Digital', 'CommonIliac', 'Femoral', 'AntTibial'}; + site_domain_no = [1, 18, 39, 41, 15, 87, 72, 21, 22, 112, 44, 46, 49]; + site_dist_prop = [0, 1, 0, 1,props.carotid, 1, 1, 0.75, 1, 1, 0.5, 0.5, 1]; +end + +for sim_no = 1 : length(collated_data) + fprintf([num2str(sim_no) ', ']); + sim_data.domain_nos = extractfield(collated_data(sim_no).output_data, 'domain_no'); + sim_data.output_data = collated_data(sim_no).output_data; + sim_data.input_data = collated_data(sim_no).input_data; + + % for each domain + for domain_no_el = 1 : length(sim_data.domain_nos) + + curr_domain_no = sim_data.domain_nos(domain_no_el); + if do_req_domains && ~sum(curr_domain_no == site_domain_no) + continue + end + + curr_distance_els = sim_data.output_data(domain_no_el).distances; + no_distance_els = length(curr_distance_els); + + if do_req_domains + dist_props = sim_data.output_data(domain_no_el).distances./sim_data.input_data.sim_settings.network_spec.length(curr_domain_no); + curr_site_el = find(site_domain_no == curr_domain_no); + [~,req_distance_el] = min(abs(dist_props-site_dist_prop(curr_site_el))); + end + + for distance_el = 1 : no_distance_els + + if do_req_domains & distance_el ~= req_distance_el + continue + end + + % For Pressure + sig.v = sim_data.output_data(domain_no_el).P(:,distance_el); + sig.fs = sim_data.output_data(domain_no_el).fs; + options.do_plot = 0; sig.ht = 1.75; + if domain_no_el == 7, options.do_plot = 0; end + [cv_inds, fid_pts, ~, ~] = PulseAnalyse10(sig, options); + [cv_inds_new, cv_inds_names] = convert_var_to_min_struct(cv_inds); + [fid_pts_new, fid_pts_names] = convert_var_to_min_struct(fid_pts); + clear cv_inds fid_pts + if options.do_plot + close all + plot(sig.v), hold on + el = fid_pts_new(strcmp(fid_pts_names,'p1')); + plot(el, sig.v(el), 'or') + el = fid_pts_new(strcmp(fid_pts_names,'P1in')); + plot(el, sig.v(el), '*r') + el = fid_pts_new(strcmp(fid_pts_names,'p2')); + plot(el, sig.v(el), 'ok') + el = fid_pts_new(strcmp(fid_pts_names,'p2in')); + plot(el, sig.v(el), '*k') + close all + end + pulse_wave_inds(sim_no).P_pwa(domain_no_el).cv_inds(:,distance_el) = cv_inds_new; + pulse_wave_inds(sim_no).P_pwa(domain_no_el).fid_pts(:,distance_el) = fid_pts_new; + clear cv_inds_new fid_pts_new + + % For PPG + sig.v = sim_data.output_data(domain_no_el).PPG(:,distance_el).^2; + sig.fs = sim_data.output_data(domain_no_el).fs; + options.do_plot = 0; sig.ht = 1.75; + [cv_inds, fid_pts, ~, ~] = PulseAnalyse10(sig, options); + [cv_inds_new, cv_inds_names] = convert_var_to_min_struct(cv_inds); + [fid_pts_new, fid_pts_names] = convert_var_to_min_struct(fid_pts); + clear cv_inds fid_pts + if options.do_plot + close all + end + pulse_wave_inds(sim_no).PPG_pwa(domain_no_el).cv_inds(:,distance_el) = cv_inds_new; + pulse_wave_inds(sim_no).PPG_pwa(domain_no_el).fid_pts(:,distance_el) = fid_pts_new; + + clear fid_pts_new cv_inds_new sig + + end + + clear no_distance_els distance_el + + end + clear domain_no_el + + % Add in names of variables + if ~sum(strcmp(fieldnames(pulse_wave_inds(1)), 'cv_ind_names')) + pulse_wave_inds(1).cv_ind_names = cv_inds_names; + pulse_wave_inds(1).fid_pt_names = fid_pts_names; + else + a = [cv_inds_names, pulse_wave_inds(1).cv_ind_names]; + if ~isequal(a(:,1), a(:,2)) + error('Check this') + end + a = [fid_pts_names, pulse_wave_inds(1).fid_pt_names]; + if ~isequal(a(:,1), a(:,2)) + error('Check this') + end + clear a + end + + % Time to reflected wave + rel_domain_el = sim_data.domain_nos == 15; + distance_el = 1; + rel_row = find(strcmp(pulse_wave_inds(1).fid_pt_names, 'p1')); + pulse_wave_inds(sim_no).Tr = pulse_wave_inds(sim_no).P_pwa(rel_domain_el).fid_pts(rel_row,distance_el)/collated_data(sim_no).output_data(1).fs; % as used in McEniery2005, and initially reported in Murgo1980 + + % Max diastolic - min systolic flow at finger + rel_domain_el = sim_data.domain_nos == 112; + sig.v = sim_data.output_data(rel_domain_el).U(:,end); + trs = find(sig.v(1:end-2) > sig.v(2:end-1) & sig.v(3:end) > sig.v(2:end-1)); + trs = trs(trscollated_data(sim_no).input_data.sim_settings.lvet); + [~, temp] = max(sig.v(pks)); + rel_pk = pks(temp); clear temp pks + pulse_wave_inds(sim_no).Q_mm = sig.v(rel_pk) - sig.v(rel_tr); + + % Max diastolic - min systolic ppg at finger + rel_domain_el = sim_data.domain_nos == 112; + sig.v = sim_data.output_data(rel_domain_el).PPG(:,end); + trs = find(sig.v(1:end-2) > sig.v(2:end-1) & sig.v(3:end) > sig.v(2:end-1)); + trs = trs(trscollated_data(sim_no).input_data.sim_settings.lvet); + [~, temp] = max(sig.v(pks)); + rel_pk = pks(temp); clear temp pks + pulse_wave_inds(sim_no).Q_mm = sig.v(rel_pk) - sig.v(rel_tr); clear rel_tr rel_pk + clear rel_domain_el sig sim_data + + % remove output data for this simulation to save memory + collated_data(sim_no).input_data= []; + collated_data(sim_no).output_data= []; + collated_data(sim_no).system_chars= []; +end +clear sim_no + +% save params +a = whos('pulse_wave_inds'); +if a.bytes > 1.8e9 + save(PATHS.pulse_wave_inds, 'pulse_wave_inds', '-v7.3') +else + save(PATHS.pulse_wave_inds, 'pulse_wave_inds') +end + +end + +function [new_var,new_names] = convert_var_to_min_struct(old_struct) + +vars = fieldnames(old_struct); + +% see if there are "".v"" fields in each variable +eval(['temp = old_struct.' vars{1} ';']) +if isstruct(temp) & sum(strcmp(fieldnames(temp), 'v')) + nested_v_fields = true; +else + nested_v_fields = false; +end +clear temp + +% extract data +new_var = nan(length(vars),1); +new_names = cell(length(vars),1); +for var_no = 1 : length(vars) + curr_var = vars{var_no}; + if nested_v_fields + eval(['curr_val = old_struct.' curr_var '.v;']) + else + eval(['curr_val = old_struct.' curr_var ';']) + end + new_var(var_no) = curr_val; + new_names{var_no} = curr_var; + +end + +end + +function extract_haemodynamic_parameters(PATHS, props, collated_data) + +fprintf('\n - Extracting haemodynamic parameters') + +% load collated data +load(PATHS.pulse_wave_vels) +load(PATHS.pulse_wave_inds) + +% setup +params = {'age',... + 'HR', 'SV', 'CO', 'LVET', 'dPdt', 'PFT', 'RFV', ... % cardiac + 'SBP_a', 'DBP_a', 'MBP_a', 'PP_a', 'SBP_b', 'DBP_b', 'MBP_b', 'PP_b', ... % routine BPs + 'SBP_f', 'DBP_f', 'MBP_f', 'PP_f', 'PP_amp', 'MBP_drop_finger', 'MBP_drop_ankle', 'SBP_diff', 'SMBP_a', ... % additional BPs + 'P1pk_a', 'P1pk_c', 'P1pk_b', 'P1pk_r', 'P1pk_d', 'P1in_a', 'P1in_c', 'P1in_b', 'P1in_r', 'P1in_d', ... % pulse wave points + 'P2pk_a', 'P2pk_c', 'P2pk_b', 'P2pk_r', 'P2pk_d', 'P2in_a', 'P2in_c', 'P2in_b', 'P2in_r', 'P2in_d', ... % pulse wave points + 'Ps_a', 'Ps_c', 'Ps_b', 'Ps_r', 'Ps_d', 'Pst_a', 'Pst_c', 'Pst_b', 'Pst_r', 'Pst_d', ... % pulse wave points + 'AI_a', 'AI_c', 'AI_b', 'AI_r', 'AI_d', 'AP_a', 'AP_c', 'AP_b', 'AP_r', 'AP_d', ... % augmentation indices + 'Tr_a', 'Tr_c', 'IAD', 'IADabs', 'svr', ... % non-routine parameters + 'PWV_a', 'PWV_cf', 'PWV_cr', 'PWV_ca', 'PWV_cb', 'PWV_bf', 'PWV_br', 'PWV_ba', 'PWV_rf', 'PWV_ra', 'PWV_fa', ... % pulse wave velocities (measured) + 'PWVt_a', 'PWVt_cf', 'PWVt_cr', 'PWVt_ca', 'PWVt_cb', 'PWVt_bf', 'PWVt_br', 'PWVt_ba', 'PWVt_rf', 'PWVt_ra', 'PWVt_fa', ... % pulse wave velocities (measured) + 'dia_asc_a', 'dia_desc_thor_a', 'dia_abd_a', 'dia_car', 'len_prox_a', ... % geometry + 'RI', 'SI', 'AGI_mod'}; % PPG indices +if exist(PATHS.system_chars, 'file') + load(PATHS.system_chars) + params = [params, {'pvr', 'pvc', 'pvc_iw', 'ac', 'c', 'tau'}]; % system chars +end + %'PPamp_s_a', 'PPamp_P1_a', 'PPamp_P2_a', 'PPamp_s_c', 'PPamp_P1_c', 'PPamp_P2_c'}; +for param_no = 1 : length(params) + eval(['haemodynamic_params.' params{param_no} ' = nan(length(collated_data),1);']); +end +prop_brach = 3/4; % distance along ""brachial artery"" (which is actually axillary and brachial in one long segment) to take cuff measurements + +fid_pt_names = pulse_wave_inds(1).fid_pt_names; +cv_ind_names = pulse_wave_inds(1).cv_ind_names; + +% extract parameters for each simulation +for sim_no = 1 : length(collated_data) + sim_data.input_data = collated_data(sim_no).input_data; + sim_data.output_data = collated_data(sim_no).output_data; + sim_data.inds = pulse_wave_inds(sim_no); + sim_data.vels = pulse_wave_vels(sim_no); + sim_data.domain_nos = extractfield(sim_data.output_data, 'domain_no'); + + % extract each parameter from this simulation in turn + for param_no = 1 : length(params) + + % extract the parameter + curr_param = params{param_no}; + + if strcmp(curr_param, 'age') + curr_val = sim_data.input_data.sim_settings.age; + elseif (length(curr_param)>1 && sum(strcmp(curr_param(1:2), {'P1', 'P2', 'Ps', 'AI', 'AP'}))) ... + || (length(curr_param) > 6 && strcmp(curr_param(1:6), 'PPamp_')) + temp.sep = strfind(curr_param, '_'); + temp.quantity = curr_param(1:temp.sep(1)-1); + if strcmp(temp.quantity(end), 't') + temp.type = 'time'; + temp.quantity = temp.quantity(1:end-1); + else + temp.type = 'value'; + end + temp.location = curr_param(temp.sep(end)+1:end); + switch temp.location + case 'a' + rel_domain_no = 1; + rel_dist_prop = 0; + case 'c' + rel_domain_no = 15; + rel_dist_prop = props.carotid; + case 'd' + rel_domain_no = 112; + rel_dist_prop = 1; + case 'r' + rel_domain_no = 22; + rel_dist_prop = 1; + case 'b' + rel_domain_no = 21; + rel_dist_prop = 0.75; + end + rel_row = find(sim_data.domain_nos == rel_domain_no); + temp.distances = sim_data.output_data(rel_row).distances; + [~, temp.rel_distance_el] = min(abs(temp.distances - (rel_dist_prop*sim_data.input_data.sim_settings.network_spec.length(rel_domain_no)))); + rel_sig = sim_data.output_data(rel_row).P(:,temp.rel_distance_el); + %curr_val = 60/(length(rel_sig)/sim_data.output_data(rel_row).fs); % in bpm + + switch temp.quantity + case 'P1pk' + rel_val_row = find(strcmp(fid_pt_names, 'p1pk')); + rel_pt.el = sim_data.inds.P_pwa(rel_row).fid_pts(rel_val_row, temp.rel_distance_el); + case 'P2pk' + rel_val_row = find(strcmp(fid_pt_names, 'p2pk')); + rel_pt.el = sim_data.inds.P_pwa(rel_row).fid_pts(rel_val_row, temp.rel_distance_el); + case 'P1in' + rel_val_row = find(strcmp(fid_pt_names, 'p1in')); + rel_pt.el = sim_data.inds.P_pwa(rel_row).fid_pts(rel_val_row, temp.rel_distance_el); + case 'P2in' + rel_val_row = find(strcmp(fid_pt_names, 'p2in')); + rel_pt.el = sim_data.inds.P_pwa(rel_row).fid_pts(rel_val_row, temp.rel_distance_el); + case 'Ps' + rel_val_row = find(strcmp(fid_pt_names, 's')); + rel_pt.el = sim_data.inds.P_pwa(rel_row).fid_pts(rel_val_row, temp.rel_distance_el); + case 'AI' + rel_val_row1 = find(strcmp(fid_pt_names, 'p1in')); + rel_val_row2 = find(strcmp(fid_pt_names, 'p2pk')); + el1 = sim_data.inds.P_pwa(rel_row).fid_pts(rel_val_row1, temp.rel_distance_el); + el2 = sim_data.inds.P_pwa(rel_row).fid_pts(rel_val_row2, temp.rel_distance_el); + curr_wav = sim_data.output_data(rel_row).P(:,temp.rel_distance_el); + if isnan(el1) + p1 = nan; + else + p1 = curr_wav(el1); + end + if isnan(el2) + p2 = nan; + else + p2 = curr_wav(el2); + end + if ~isnan(p2) & ~isnan(p1) + rel_pt.v = 100*(p2-p1)/(max(curr_wav)-min(curr_wav)); % as percent + else + rel_pt.v = nan; + end + clear rel_val_row1 rel_val_row2 el1 el2 curr_wav p1 p2 + case 'AP' + rel_val_row1 = find(strcmp(fid_pt_names, 'p1in')); + rel_val_row2 = find(strcmp(fid_pt_names, 'p2pk')); + el1 = sim_data.inds.P_pwa(rel_row).fid_pts(rel_val_row1, temp.rel_distance_el); + el2 = sim_data.inds.P_pwa(rel_row).fid_pts(rel_val_row2, temp.rel_distance_el); + curr_wav = sim_data.output_data(rel_row).P(:,temp.rel_distance_el); + if isnan(el1) + p1 = nan; + else + p1 = curr_wav(el1); + end + if isnan(el2) + p2 = nan; + else + p2 = curr_wav(el2); + end + if ~isnan(p2) & ~isnan(p1) + rel_pt.v = (p2-p1)/133.33; % in mmHg + else + rel_pt.v = nan; + end + clear rel_val_row1 rel_val_row2 el1 el2 curr_wav p1 p2 + case 'PP_amp' + error('Check this') + end + if ~sum(strcmp(fieldnames(rel_pt),'v')) + if isnan(rel_pt.el) + rel_pt.t = nan; + rel_pt.v = nan; + else + rel_pt.t = (rel_pt.el-1)/sim_data.output_data(rel_row).fs; + rel_pt.v = rel_sig(rel_pt.el)/133.33; + end + end + + switch temp.type + case 'time' + curr_val = rel_pt.t; + case 'value' + curr_val = rel_pt.v; + end + clear temp rel_pt + + else + switch curr_param + case 'HR' + rel_domain_no = 1; + rel_row = find(sim_data.domain_nos == rel_domain_no); + rel_sig = sim_data.output_data(rel_row).P(:,1); + curr_val = 60/(length(rel_sig)/sim_data.output_data(rel_row).fs); % in bpm + case 'SV' + rel_domain_no = 1; + rel_row = find(sim_data.domain_nos == rel_domain_no); + rel_sig = sim_data.output_data(rel_row).U(:,1).*sim_data.output_data(rel_row).A(:,1); + curr_val = sum(rel_sig)/sim_data.output_data(rel_row).fs; % in m3 + curr_val = 1000*1000*curr_val; % in ml + case 'CO' + curr_val = haemodynamic_params(sim_no).HR * haemodynamic_params(sim_no).SV / 1000; % in l/min + case 'LVET' + rel_domain_no = 1; + rel_row = find(sim_data.domain_nos == rel_domain_no); + rel_sig = sim_data.output_data(rel_row).U(:,1); + temp = find(rel_sig(11:end)<0,1); temp = temp+10-1; + curr_val = 1000*temp/sim_data.output_data(rel_row).fs; % in ms + clear temp + case 'dPdt' + rel_domain_no = 1; + rel_row = find(sim_data.domain_nos == rel_domain_no); + rel_sig = sim_data.output_data(rel_row).P(:,1); + dPdt = (diff(rel_sig)/133.33).*(sim_data.output_data(rel_row).fs); % dP/dt in mmHg/s + curr_val = max(dPdt); clear dPdt + case 'PFT' + rel_domain_no = 1; + rel_row = find(sim_data.domain_nos == rel_domain_no); + rel_sig = sim_data.output_data(rel_row).U(:,1).*sim_data.output_data(rel_row).A(:,1); + [~, temp_el] = max(rel_sig); + curr_val = 1000*temp_el/sim_data.output_data(rel_row).fs; % in ms + case 'RFV' + rel_domain_no = 1; + rel_row = find(sim_data.domain_nos == rel_domain_no); + rel_sig = sim_data.output_data(rel_row).U(:,1).*sim_data.output_data(rel_row).A(:,1); + rel_els = rel_sig<0; + curr_val = -1*sum(rel_sig(rel_els))/sim_data.output_data(rel_row).fs; % in m3 + curr_val = 1000*1000*curr_val; % in ml + case 'SBP_a' + rel_domain_no = 1; + rel_row = find(sim_data.domain_nos == rel_domain_no); + rel_sig = sim_data.output_data(rel_row).P(:,1); + curr_val = max(rel_sig)/133.33; % convert Pa to mmHg + case 'DBP_a' + rel_domain_no = 1; + rel_row = find(sim_data.domain_nos == rel_domain_no); + rel_sig = sim_data.output_data(rel_row).P(:,1); + curr_val = min(rel_sig)/133.33; % convert Pa to mmHg + case 'MBP_a' + rel_domain_no = 1; + rel_row = find(sim_data.domain_nos == rel_domain_no); + rel_sig = sim_data.output_data(rel_row).P(:,1); + curr_val = mean(rel_sig)/133.33; % convert Pa to mmHg + case 'PP_a' + rel_domain_no = 1; + rel_row = find(sim_data.domain_nos == rel_domain_no); + rel_sig = sim_data.output_data(rel_row).P(:,1); + curr_val = range(rel_sig)/133.33; % convert Pa to mmHg + case 'SBP_b' + rel_domain_no = 21; + rel_row = find(sim_data.domain_nos == rel_domain_no); + temp.distances = sim_data.output_data(rel_row).distances; + [~, temp.rel_distance_el] = min(abs(temp.distances - (prop_brach*sim_data.input_data.sim_settings.network_spec.length(rel_domain_no)))); + rel_sig = sim_data.output_data(rel_row).P(:,temp.rel_distance_el); clear temp + curr_val = max(rel_sig)/133.33; % convert Pa to mmHg + case 'DBP_b' + rel_domain_no = 21; + rel_row = find(sim_data.domain_nos == rel_domain_no); + temp.distances = sim_data.output_data(rel_row).distances; + [~, temp.rel_distance_el] = min(abs(temp.distances - (prop_brach*sim_data.input_data.sim_settings.network_spec.length(rel_domain_no)))); + rel_sig = sim_data.output_data(rel_row).P(:,temp.rel_distance_el); clear temp + curr_val = min(rel_sig)/133.33; % convert Pa to mmHg + case 'MBP_b' + rel_domain_no = 21; + rel_row = find(sim_data.domain_nos == rel_domain_no); + temp.distances = sim_data.output_data(rel_row).distances; + [~, temp.rel_distance_el] = min(abs(temp.distances - (prop_brach*sim_data.input_data.sim_settings.network_spec.length(rel_domain_no)))); + rel_sig = sim_data.output_data(rel_row).P(:,temp.rel_distance_el); clear temp + curr_val = mean(rel_sig)/133.33; % convert Pa to mmHg + case 'PP_b' + rel_domain_no = 21; + rel_row = find(sim_data.domain_nos == rel_domain_no); + temp.distances = sim_data.output_data(rel_row).distances; + [~, temp.rel_distance_el] = min(abs(temp.distances - (prop_brach*sim_data.input_data.sim_settings.network_spec.length(rel_domain_no)))); + rel_sig = sim_data.output_data(rel_row).P(:,temp.rel_distance_el); clear temp + curr_val = range(rel_sig)/133.33; % convert Pa to mmHg + case 'SBP_f' + rel_domain_no = 112; % digital + rel_row = find(sim_data.domain_nos == rel_domain_no); + rel_sig = sim_data.output_data(rel_row).P(:,end); + curr_val = max(rel_sig)/133.33; % convert Pa to mmHg + case 'DBP_f' + rel_domain_no = 112; % digital + rel_row = find(sim_data.domain_nos == rel_domain_no); + rel_sig = sim_data.output_data(rel_row).P(:,end); + curr_val = min(rel_sig)/133.33; % convert Pa to mmHg + case 'MBP_f' + rel_domain_no = 112; % digital + rel_row = find(sim_data.domain_nos == rel_domain_no); + rel_sig = sim_data.output_data(rel_row).P(:,end); + curr_val = mean(rel_sig)/133.33; % convert Pa to mmHg + case 'PP_f' + rel_domain_no = 112; % digital + rel_row = find(sim_data.domain_nos == rel_domain_no); + rel_sig = sim_data.output_data(rel_row).P(:,end); + curr_val = range(rel_sig)/133.33; % convert Pa to mmHg + case 'PP_amp' + curr_val = haemodynamic_params(sim_no).PP_b / haemodynamic_params(sim_no).PP_a; + case 'MBP_drop_finger' + rel_domain_no = 1; + rel_row = find(sim_data.domain_nos == rel_domain_no); + rel_sig = sim_data.output_data(rel_row).P(:,1); + central_mbp = mean(rel_sig)/133.33; % convert Pa to mmHg + rel_domain_no = 112; + rel_row = find(sim_data.domain_nos == rel_domain_no); + rel_sig = sim_data.output_data(rel_row).P(:,end); + peripheral_mbp = mean(rel_sig)/133.33; % convert Pa to mmHg + curr_val = central_mbp - peripheral_mbp; + case 'MBP_drop_ankle' + rel_domain_no = 1; + rel_row = find(sim_data.domain_nos == rel_domain_no); + rel_sig = sim_data.output_data(rel_row).P(:,1); + central_mbp = mean(rel_sig)/133.33; % convert Pa to mmHg + rel_domain_no = 49; + rel_row = find(sim_data.domain_nos == rel_domain_no); + rel_sig = sim_data.output_data(rel_row).P(:,end); + peripheral_mbp = mean(rel_sig)/133.33; % convert Pa to mmHg + curr_val = central_mbp - peripheral_mbp; + case 'SBP_diff' + rel_domain_no = 21; + rel_row = find(sim_data.domain_nos == rel_domain_no); + temp.distances = sim_data.output_data(rel_row).distances; + [~, temp.rel_distance_el] = min(abs(temp.distances - (prop_brach*sim_data.input_data.sim_settings.network_spec.length(rel_domain_no)))); + rel_sig = sim_data.output_data(rel_row).P(:,temp.rel_distance_el); clear temp + temp.sbp_b = max(rel_sig)/133.33; + rel_domain_no = 1; + rel_row = find(sim_data.domain_nos == rel_domain_no); + rel_sig = sim_data.output_data(rel_row).P(:,1); + temp.sbp_a = max(rel_sig)/133.33; + curr_val = temp.sbp_b - temp.sbp_a; % convert Pa to mmHg + case 'SMBP_a' + rel_domain_no = 1; + rel_row = find(sim_data.domain_nos == rel_domain_no); + rel_sig = sim_data.output_data(rel_row).P(:,1); + temp.sbp = max(rel_sig)/133.33; + temp.mbp = mean(rel_sig)/133.33; + curr_val = temp.sbp - temp.mbp; % convert Pa to mmHg + case 'IAD' + rel_domain_no = 7; % right brachial + rel_row = find(sim_data.domain_nos == rel_domain_no); + temp.distances = sim_data.output_data(rel_row).distances; + [~, distance_el] = min(abs(temp.distances - (prop_brach*sim_data.input_data.sim_settings.network_spec.length(rel_domain_no)))); + rel_sig = sim_data.output_data(rel_row).P(:,distance_el); + right_arm_sbp = max(rel_sig)/133.33; % convert Pa to mmHg + actual_prop_dist = temp.distances(distance_el)/sim_data.input_data.sim_settings.network_spec.length(rel_domain_no); + rel_domain_no = 21; % left brachial + rel_row = find(sim_data.domain_nos == rel_domain_no); + temp.distances = sim_data.output_data(rel_row).distances; + [~, distance_el] = min(abs(temp.distances - (actual_prop_dist*sim_data.input_data.sim_settings.network_spec.length(rel_domain_no)))); + rel_sig = sim_data.output_data(rel_row).P(:,distance_el); + left_arm_sbp = max(rel_sig)/133.33; % convert Pa to mmHg + curr_val = right_arm_sbp - left_arm_sbp; + case 'IADabs' + rel_domain_no = 7; % right brachial + rel_row = find(sim_data.domain_nos == rel_domain_no); + temp.distances = sim_data.output_data(rel_row).distances; + [~, distance_el] = min(abs(temp.distances - (prop_brach*sim_data.input_data.sim_settings.network_spec.length(rel_domain_no)))); + rel_sig = sim_data.output_data(rel_row).P(:,distance_el); + right_arm_sbp = max(rel_sig)/133.33; % convert Pa to mmHg + actual_prop_dist = temp.distances(distance_el)/sim_data.input_data.sim_settings.network_spec.length(rel_domain_no); + rel_domain_no = 21; % left brachial + rel_row = find(sim_data.domain_nos == rel_domain_no); + temp.distances = sim_data.output_data(rel_row).distances; + [~, distance_el] = min(abs(temp.distances - (actual_prop_dist*sim_data.input_data.sim_settings.network_spec.length(rel_domain_no)))); + rel_sig = sim_data.output_data(rel_row).P(:,distance_el); + left_arm_sbp = max(rel_sig)/133.33; % convert Pa to mmHg + curr_val = abs(right_arm_sbp - left_arm_sbp); + case 'Tr_c' + % - carotid + rel_domain_no = 15; % carotid + rel_prop = props.carotid; + % working + rel_row = find(sim_data.domain_nos == rel_domain_no); + temp.distances = sim_data.output_data(rel_row).distances; + [~, distance_el] = min(abs(temp.distances - (rel_prop*sim_data.input_data.sim_settings.network_spec.length(rel_domain_no)))); + rel_val_row = find(strcmp(fid_pt_names, 'p1in')); + curr_val = 1000*(sim_data.inds.P_pwa(rel_row).fid_pts(rel_val_row, distance_el)-1)/sim_data.output_data(1).fs; % as used in McEniery2005, and initially reported in Murgo1980 + case 'Tr_a' + % - aortic root + rel_domain_no = 1; + rel_prop = 0; + % working + rel_row = find(sim_data.domain_nos == rel_domain_no); + temp.distances = sim_data.output_data(rel_row).distances; + [~, distance_el] = min(abs(temp.distances - (rel_prop*sim_data.input_data.sim_settings.network_spec.length(rel_domain_no)))); + rel_val_row = find(strcmp(fid_pt_names, 'p1in')); + curr_val = 1000*(sim_data.inds.P_pwa(rel_row).fid_pts(rel_val_row, distance_el)-1)/sim_data.output_data(1).fs; % as used in McEniery2005, and initially reported in Murgo1980 + case 'PWV_a' + curr_val = sim_data.vels.pwv.aorta_iliacbif; + case 'PWV_cf' + curr_val = sim_data.vels.pwv.carotid_femoral; + case 'PWV_cr' + curr_val = sim_data.vels.pwv.carotid_radial; + case 'PWV_ca' + curr_val = sim_data.vels.pwv.carotid_ankle; + case 'PWV_cb' + curr_val = sim_data.vels.pwv.carotid_brachial; + case 'PWV_bf' + curr_val = sim_data.vels.pwv.brachial_femoral; + case 'PWV_br' + curr_val = sim_data.vels.pwv.brachial_radial; + case 'PWV_ba' + curr_val = sim_data.vels.pwv.brachial_ankle; + case 'PWV_rf' + curr_val = sim_data.vels.pwv.radial_femoral; + case 'PWV_ra' + curr_val = sim_data.vels.pwv.radial_ankle; + case 'PWV_fa' + curr_val = sim_data.vels.pwv.femoral_ankle; + case 'PWVt_a' + curr_val = sim_data.vels.pwv_theor.aorta_iliacbif; + case 'PWVt_cf' + curr_val = sim_data.vels.pwv_theor.carotid_femoral; + case 'PWVt_cr' + curr_val = sim_data.vels.pwv_theor.carotid_radial; + case 'PWVt_ca' + curr_val = sim_data.vels.pwv_theor.carotid_ankle; + case 'PWVt_cb' + curr_val = sim_data.vels.pwv_theor.carotid_brachial; + case 'PWVt_bf' + curr_val = sim_data.vels.pwv_theor.brachial_femoral; + case 'PWVt_br' + curr_val = sim_data.vels.pwv_theor.brachial_radial; + case 'PWVt_ba' + curr_val = sim_data.vels.pwv_theor.brachial_ankle; + case 'PWVt_rf' + curr_val = sim_data.vels.pwv_theor.radial_femoral; + case 'PWVt_ra' + curr_val = sim_data.vels.pwv_theor.radial_ankle; + case 'PWVt_fa' + curr_val = sim_data.vels.pwv_theor.femoral_ankle; + + + % Diameters using values measured from the simulated waves + case 'dia_asc_a' + % - asc aorta + rel_domain_nos = find(sim_data.input_data.sim_settings.network_spec.asc_aorta); + [~,domain_els,~] = intersect(sim_data.domain_nos, rel_domain_nos); + for s = 1 : length(domain_els) + curr_domain_el = domain_els(s); + ave_areas(s,1) = mean([max(sim_data.output_data(curr_domain_el).A(:,1)), max(sim_data.output_data(curr_domain_el).A(:,end))]); + end + lengths = sim_data.input_data.sim_settings.network_spec.length(rel_domain_nos); + curr_val = 1000*2*(sum(lengths.*sqrt(ave_areas./pi)))/sum(lengths); + clear ave_areas lengths + case 'dia_desc_thor_a' + % - desc thor aorta + rel_domain_nos = find(sim_data.input_data.sim_settings.network_spec.desc_thor_aorta); + [~,domain_els,~] = intersect(sim_data.domain_nos, rel_domain_nos); + for s = 1 : length(domain_els) + curr_domain_el = domain_els(s); + ave_areas(s,1) = mean([max(sim_data.output_data(curr_domain_el).A(:,1)), max(sim_data.output_data(curr_domain_el).A(:,end))]); + end + lengths = sim_data.input_data.sim_settings.network_spec.length(rel_domain_nos); + curr_val = 1000*2*(sum(lengths.*sqrt(ave_areas./pi)))/sum(lengths); + clear ave_areas lengths + case 'dia_abd_a' + % - abd aorta + rel_domain_nos = find(sim_data.input_data.sim_settings.network_spec.abd_aorta); + [~,domain_els,~] = intersect(sim_data.domain_nos, rel_domain_nos); + for s = 1 : length(domain_els) + curr_domain_el = domain_els(s); + ave_areas(s,1) = mean([max(sim_data.output_data(curr_domain_el).A(:,1)), max(sim_data.output_data(curr_domain_el).A(:,end))]); + end + lengths = sim_data.input_data.sim_settings.network_spec.length(rel_domain_nos); + curr_val = 1000*2*(sum(lengths.*sqrt(ave_areas./pi)))/sum(lengths); + clear ave_areas lengths + case 'dia_car' + % - carotid + rel_domain_nos = find(sim_data.input_data.sim_settings.network_spec.both_carotid); + [~,domain_els,~] = intersect(sim_data.domain_nos, rel_domain_nos); + for s = 1 : length(domain_els) + curr_domain_el = domain_els(s); + ave_areas(s,1) = mean([mean(sim_data.output_data(curr_domain_el).A(:,1)), mean(sim_data.output_data(curr_domain_el).A(:,end))]); + end + lengths = sim_data.input_data.sim_settings.network_spec.length(rel_domain_nos); + curr_val = 1000*2*(sum(lengths.*sqrt(ave_areas./pi)))/sum(lengths); + clear ave_areas lengths + case 'len_prox_a' + % - proximal aortic length + rel_els = sim_data.input_data.sim_settings.network_spec.proximal_aorta; + curr_val = 1000*sum( sim_data.input_data.sim_settings.network_spec.length(rel_els) ); + case 'svr' + % vascular + rel_domain_no = 1; + rel_row = find(sim_data.domain_nos == rel_domain_no); + rel_dist_el = 1; + curr_val = mean(sim_data.output_data(rel_row).P(:,rel_dist_el))/mean(sim_data.output_data(rel_row).U(:,rel_dist_el).*sim_data.output_data(rel_row).A(:,rel_dist_el))/(1e6); + % PPG + case 'RI' + rel_domain_no = 112; domain_el = find(sim_data.domain_nos == rel_domain_no); + rel_dist_el = 3; + rel_val_row = find(strcmp(cv_ind_names, 'RI')); + curr_val = sim_data.inds.PPG_pwa(domain_el).cv_inds(rel_val_row, rel_dist_el); + case 'SI' + rel_domain_no = 112; domain_el = find(sim_data.domain_nos == rel_domain_no); + rel_dist_el = 3; + rel_val_row = find(strcmp(cv_ind_names, 'delta_t')); + curr_val = 1.75/sim_data.inds.PPG_pwa(domain_el).cv_inds(rel_val_row, rel_dist_el); + case 'AGI_mod' + rel_domain_no = 112; domain_el = find(sim_data.domain_nos == rel_domain_no); + rel_dist_el = 3; + rel_val_row = find(strcmp(cv_ind_names, 'AGI_mod')); + curr_val = sim_data.inds.PPG_pwa(domain_el).cv_inds(rel_val_row, rel_dist_el); + case 'pvr' + curr_val = system_chars.pvr(sim_no); + case 'pvc' + curr_val = system_chars.pvc(sim_no); + case 'pvc_iw' + curr_val = system_chars.pvc_iw(sim_no); + case 'ac' + curr_val = system_chars.ac(sim_no); + case 'c' + curr_val = system_chars.c(sim_no); + case 'tau' + curr_val = system_chars.tau(sim_no); + end + clear temp + end + + % store this extracted parameter + eval(['haemodynamic_params(sim_no).' curr_param ' = curr_val;']) + + clear rel_dist_el curr_val rel_domain_no domain_el rel_val_row + end + +end + +% save params +save(PATHS.haemodynamic_params, 'haemodynamic_params') + +end +","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/co_case_study.m",".m","25315","654","function co_case_study(pwdb_no) +% CO_CASE_STUDY generates the plots reported in the case study on +% estimating cardiac output from blood pressure waveforms +% +% co_case_study +% +% Inputs: - the 'pwdb_data' file produced by 'export_pwdb.m'. +% +% Outputs: - plots illustrating the results of the case study +% +% Accompanying Article: +% This code is provided to facilitate reproduction of the Pulse Wave +% Database described in: +% Charlton P.H. et al. Modelling arterial pulse waves in healthy +% ageing: a database for in silico evaluation of haemodynamics +% and pulse wave indices, ~~ under review ~~ +% DOI: ~~ tbc ~~ +% Further information on the pwdb Pulse Wave Database is provided in +% this article and at the project website: +% https://peterhcharlton.github.io/pwdb +% +% Author: Peter H. Charlton +% +% Licence: +% Permission is hereby granted, free of charge, to any person obtaining a copy +% of this software and associated documentation files (the ""Software""), to deal +% in the Software without restriction, including without limitation the rights +% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +% copies of the Software, and to permit persons to whom the Software is +% furnished to do so, subject to the following conditions: +% +% The above copyright notice and this permission notice shall be included in all +% copies or substantial portions of the Software. +% +% THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +% SOFTWARE. +% +% Copyright (C) 2019 King's College London +% +% v.1.0 Peter H. Charlton, King's College London + +fprintf('\n --- Running Cardiac Output (CO) Case Study ---') + +% Setup paths with current simulation paths +PATHS = setup_paths_for_post_processing(pwdb_no); + +% Cardiac output algorithm settings +up.settings = cardiac_output_settings; +display_settings(up); + +% Setup universal parameters +up = setup_up(up); + +% Collate data +data = load_data(PATHS, up); + +% Find cardiac output +data = find_cardiac_output(data, up); + +% Make results plots +make_results_plots(data, up, PATHS); + +% Make additional plots +if up.make_plots + make_additional_plots(co_data, up) +end + +% % Display results +% display_results(co_data, up); + +end + +function settings = cardiac_output_settings + +% This specifies the settings used for cardiac output estimation + +%% %%%%%%%%%%%%%%%%% Anatomical Site for ABP measurement %%%%%%%%%%%%%%%%% +settings.artery.options = { ... + 'Femoral', ... % 1 + 'Radial', ... % 2 + 'AorticRoot', ... % 3 + 'Brachial', ... % 4 + }; +settings.artery.choice = 2; + +end + +function display_settings(up) + +% This displays the settings that the user has chosen + +different_settings = fieldnames(up.settings); +desired_len = 10; + +message = '\n ---------\n Settings:\n ---------'; +for s = 1 : length(different_settings) + curr_setting_name = strrep(different_settings{s}, '_', ' '); + eval(['curr_setting_choice = up.settings.' different_settings{s} '.options{up.settings.' different_settings{s} '.choice};']); + spaces = repmat(' ', [1, desired_len-length(curr_setting_name)]); + message = [message, '\n ', curr_setting_name, ':', spaces, curr_setting_choice]; + clear curr_setting* +end +clear s + +message = [message, '\n']; + +fprintf(message) + + +end + +function up = setup_up(up) + +close all +% identify the artery of interest +chosen_option = identify_chosen_option(up, 'artery'); + +% physiological parameters which are varied in the database +up.params = {'pwv', 'dia', 'mbp', 'lvet', 'hr', 'sv'}; + +% CO algorithms +up.algorithm_types = {... +% 'area under curve', ... % 1 (pub 5) +% 'systolic area', ... % 2 (pub 6?) + 'rms', ... % 3 (pub 10) +% 'rms_pulsatile', ... % 4 (pub 11) +% 'integrate compliance', ... % 5 (pub 8) +% 'constant compliance', ... % 6 (pub 9) +% 'esvb', ... % 7 +% 'erlanger_hooker', ... % 8 + 'liljestrand', ... % 9 +% 'herd',... % 10 +% 'harley',... % 11 +% 'kouchoukos',... % 12 +% 'wesseling',... % 13 +% 'erlanger',... % 14 +% 'wesseling2',... % 15 + }; + +%% - make additional plots +up.make_plots = 0; + +%% - set current directory +cd(fileparts(which(mfilename))); + +end + +function data = load_data(PATHS, up) + +% identify the artery of interest +chosen_option = identify_chosen_option(up, 'artery'); + +fprintf(['\n - Loading data for ' chosen_option ' artery']) + +% Load all data +load(PATHS.exported_data_mat_pwdb_data); +orig_data = data; +% Identify relevant data +rel_subjs = data.plausibility.plausibility_log'; +clear data + +% - set up groups +rel_cols = strcmp(orig_data.config.variations.param_names, 'pwv') | ... + strcmp(orig_data.config.variations.param_names, 'mbp') | ... + strcmp(orig_data.config.variations.param_names, 'dia'); +% Group 1: changes in these variables, and no change in other variables +data.group1 = sum(abs(orig_data.config.variations.params(:,~rel_cols))')==0 & orig_data.config.baseline_sim_for_age' == 0; +data.group1 = data.group1(:); +% Group 2: changes in other variables, but no change in specified variables +data.group2 = ~data.group1 & orig_data.config.baseline_sim_for_age == 0; + +% - set up groups +rel_cols = strcmp(orig_data.config.variations.param_names, 'pwv'); +% Group 1: changes in these variables, and no change in other variables +data.group1 = sum(abs(orig_data.config.variations.params(:,~rel_cols))')==0 & orig_data.config.baseline_sim_for_age' == 0; +data.group1 = data.group1(:); + +rel_cols = strcmp(orig_data.config.variations.param_names, 'dia'); +% Group 2: changes in these variables, and no change in other variables +data.group2 = sum(abs(orig_data.config.variations.params(:,~rel_cols))')==0 & orig_data.config.baseline_sim_for_age' == 0; +data.group2 = data.group2(:); + +rel_cols = strcmp(orig_data.config.variations.param_names, 'mbp'); +% Group 3: changes in these variables, and no change in other variables +data.group3 = sum(abs(orig_data.config.variations.params(:,~rel_cols))')==0 & orig_data.config.baseline_sim_for_age' == 0; +data.group3 = data.group3(:); + +rel_cols = strcmp(orig_data.config.variations.param_names, 'lvet'); +% Group 4: changes in these variables, and no change in other variables +data.group4 = sum(abs(orig_data.config.variations.params(:,~rel_cols))')==0 & orig_data.config.baseline_sim_for_age' == 0; +data.group4 = data.group4(:); + +rel_cols = strcmp(orig_data.config.variations.param_names, 'hr'); +% Group 5: changes in these variables, and no change in other variables +data.group5 = sum(abs(orig_data.config.variations.params(:,~rel_cols))')==0 & orig_data.config.baseline_sim_for_age' == 0; +data.group5 = data.group5(:); + +rel_cols = strcmp(orig_data.config.variations.param_names, 'sv'); +% Group 6: changes in these variables, and no change in other variables +data.group6 = sum(abs(orig_data.config.variations.params(:,~rel_cols))')==0 & orig_data.config.baseline_sim_for_age' == 0; +data.group6 = data.group6(:); + +% Group 7: all except baseline +data.group7 = orig_data.config.baseline_sim_for_age == 0; + +% - extract data +eval(['data.p = orig_data.waves.P_' chosen_option '(:);']); +data.age = orig_data.config.age; +data.ref_log = orig_data.config.baseline_sim_for_age; +data.end_sys_samp_no = orig_data.waves.fs*extractfield(orig_data.haemods, 'LVET')/1000; data.end_sys_samp_no = data.end_sys_samp_no(:); +data.settings.fs = orig_data.waves.fs; + +% - extract CO +data.ref_co = extractfield(orig_data.haemods, 'CO'); +data.ref_co = data.ref_co(:); + +% - identify calibration subject +data.cal_subj = nan(length(data.age),1); +for s = 1 : length(data.age) + curr_age = data.age(s); + data.cal_subj(s,1) = find(data.ref_log & data.age == curr_age); +end + +% Extract param values +for param_no = 1 : length(up.params) + curr_param = up.params{param_no}; + eval(['data.params.' curr_param ' = orig_data.config.' curr_param '_SD(rel_subjs);']) +end + +% Remove physiologically implausible subjs from analysis +fields = fieldnames(data); +for field_no = 1 : length(fields) + eval(['curr_field = data.' fields{field_no} ';']); + % skip if this doesn't need adjusting + if isstruct(curr_field) + continue + end + % otherwise remove those subjects which were implausible + curr_field = curr_field(rel_subjs); + eval(['data.' fields{field_no} ' = curr_field;']); +end + +end + +function data = find_cardiac_output(data, up) + +% algorithm to use +fprintf(['\n - Estimating cardiac output']) + +co_data.sv_est = nan(length(data.age),length(up.algorithm_types)); + + +% cycle through each subject +for subj_no = 1 : length(data.age) + + % cycle through each algorithm + for alg_no = 1 : length(up.algorithm_types) + + curr_alg = up.algorithm_types{alg_no}; + + % calculate uncalibrated sv + switch curr_alg + case 'area under curve' % (charlton 2014, eqn 5) + data.sv_est(subj_no, alg_no) = sum(data.p{subj_no})/data.settings.fs; + + case 'systolic area' % (charlton 2014, eqn 6?) + rel_t = 1:data.end_sys_samp_no(subj_no); + data.sv_est(subj_no, alg_no) = sum(data.p{subj_no}(rel_t))/data.settings.fs; + + case 'rms' % (charlton 2014, eqn 10) + data.sv_est(subj_no, alg_no) = sqrt(mean(data.p{subj_no}.^2)); + + case 'rms_pulsatile' % (charlton 2014, eqn 11) + data.sv_est(subj_no, alg_no) = sqrt(mean((data.p{subj_no}-mean(data.p{subj_no})).^2)); + + case 'integrate compliance' % (charlton 2014, eqn 8) + start_dia_el = data.end_sys_samp_no(subj_no); + compliance = calc_compliance(data.p{subj_no}, data.settings.fs); + data.sv_est(subj_no, alg_no) = -1 * compliance * ... + (data.p{subj_no}(end) - data.p{subj_no}(start_dia_el) ) ... + * (1 + ( ... + (sum(data.p{subj_no}(1:start_dia_el))/data.settings.fs)/ ... % assume Pout is 0 + (sum(data.p{subj_no}(start_dia_el:end))/data.settings.fs) ... + ) ); + + case 'constant compliance' % (charlton 2014, eqn 9) + compliance = calc_compliance(data.p{subj_no}, data.settings.fs); + p_out = 0; + [p_s, sys_peak_el] = max(data.p{subj_no}); + t_s = sys_peak_el/data.settings.fs; + t_d = length(data.p{subj_no})/data.settings.fs; + p_d = data.p{subj_no}(end); + p_0 = data.p{subj_no}(1); + tau = -1*(t_d-t_s)/log(p_d/p_s); % use D1 + % assuming P(t_d) = P(t_0) + data.sv_est(subj_no, alg_no) = compliance*( (p_d-p_0) + ( (1/tau)*sum(data.p{subj_no}-p_out)/data.settings.fs ) ); + + case 'esvb' %?\cite{Papaioannou2012} + a1 = 0.4; % ?\cite{Reymond2009} + b1 = 5; + pmaxc = 20; + pwidth = 30; + C = a1 + (b1./ (1 + ( (data.p{subj_no}-pmaxc)/pwidth ).^2 ) ); + T = (length(data.p{subj_no})-1)/data.settings.fs; + PP = max(data.p{subj_no}) - min(data.p{subj_no}); + data.sv_est(subj_no, alg_no) = mean(C*PP./T); + + case 'erlanger_hooker' %?\cite{Papaioannou2012} + PP = max(data.p{subj_no}) - min(data.p{subj_no}); + T = (length(data.p{subj_no})-1)/data.settings.fs; + data.sv_est(subj_no, alg_no) = PP/T; + + case 'liljestrand' %?\cite{Papaioannou2012} + PP = max(data.p{subj_no}) - min(data.p{subj_no}); + T = (length(data.p{subj_no})-1)/data.settings.fs; + p_d = data.p{subj_no}(end); + p_s = max(data.p{subj_no}); + data.sv_est(subj_no, alg_no) = PP/(T*(p_s+p_d)); + + case 'herd' %?\cite{Papaioannou2012} + p_d = data.p{subj_no}(end); + p_m = mean(data.p{subj_no}); + T = (length(data.p{subj_no})-1)/data.settings.fs; + data.sv_est(subj_no, alg_no) = (p_m - p_d)/T; + + case 'harley' %?\cite{Papaioannou2012} + PP = max(data.p{subj_no}) - min(data.p{subj_no}); + start_dia_el = data.end_sys_samp_no(subj_no); + Ts = start_dia_el/data.settings.fs; + T = (length(data.p{subj_no})-1)/data.settings.fs; + data.sv_est(subj_no, alg_no) = PP*Ts/T; + + case 'kouchoukos' %?\cite{Papaioannou2012} + Psa = sum(data.p{subj_no}(rel_t))/data.settings.fs; + start_dia_el = data.end_sys_samp_no(subj_no); + Ts = start_dia_el/data.settings.fs; + T = (length(data.p{subj_no})-1)/data.settings.fs; + Td = T - Ts; + data.sv_est(subj_no, alg_no) = (Psa/T)*(1 + (Ts/Td)); + + case 'wesseling' %?\cite{Papaioannou2012} + Psa = sum(data.p{subj_no}(rel_t))/data.settings.fs; + T = (length(data.p{subj_no})-1)/data.settings.fs; + data.sv_est(subj_no, alg_no) = Psa/T; + + case 'erlanger' %?\cite{Papaioannou2012} + PP = max(data.p{subj_no}) - min(data.p{subj_no}); + data.sv_est(subj_no, alg_no) = PP; + + case 'wesseling2' %?\cite{Papaioannou2012} + Psa = sum(data.p{subj_no}(rel_t))/data.settings.fs; + T = (length(data.p{subj_no})-1)/data.settings.fs; + HR = 60/T; + Pm = mean(data.p{subj_no}); + data.sv_est(subj_no, alg_no) = (Psa/T)*(163+HR-0.48*Pm); + end + + % calibrate sv + cal_const = data.sv_est(data.cal_subj(subj_no), alg_no)./data.ref_co(subj_no); + data.co_cal(subj_no, alg_no) = data.sv_est(subj_no, alg_no)/cal_const; + + end + +end + +end + +function compliance = calc_compliance(p, fs) + +% using C4 + +dt = 1/fs; +p_out = 0; +compliance = 1./(sum(p-p_out)*dt); + +% using C2 + +p_sys = max(p); +p_dia = p(end); +compliance = 1/(p_sys+p_dia); + +% using C3 +p_sys = max(p); +p_dia = p(end); +compliance = 1/(p_sys+(2*p_dia)); + + + +end + +function chosen_option = identify_chosen_option(up, rel_setting) + +eval(['rel_options = up.settings.' rel_setting '.options;']); +eval(['rel_choice = up.settings.' rel_setting '.choice;']); +chosen_option = rel_options{rel_choice}; + +end + +function display_results(co_data, up) + +d = co_data; + +for subj_no = 1 : length(d) + + % identify the parameter of interest + chosen_option = identify_chosen_option(up, 'physiological_parameter'); + eval(['param_data = co_data(subj_no).' chosen_option '.v;']) + param_vals = unique(param_data); + baseline_val = param_data(co_data(subj_no).baseline_el); + baseline_el = find(param_vals == 0); + init_color = 0.6; + for s = 1 : length(param_vals) + curr_param_val = param_vals(s); + if curr_param_val == 0 + colors(s,:) = init_color*[0,0,1]; + elseif curr_param_val < 0 + const = 0.3/sum(param_vals<0); + colors(s,:) = (init_color + (s-baseline_el)*const)*[0,0,1]; + else + const = 0.4/sum(param_vals>0); + colors(s,:) = (init_color + (s-baseline_el)*const)*[0,0,1]; + end + end + + % - make figure + screensize = get( 0, 'Screensize' ); + figure('Position', [125, 125, 900, 500]) + subplot(1,3,1:2) + + ftsize = 14; + + % Plot baseline value + %plot(co_data.ref_co(co_data.baseline_el), co_data.co_est(co_data.baseline_el), 'ok', 'MarkerSize', 10, 'MarkerEdgeColor','b','MarkerFaceColor','b'), + %hold on, + + % Plot other values + for s = 1 : length(co_data(subj_no).ref_co) + color_number = find(param_vals == param_data(s)); + if s == find(co_data(subj_no).baseline_el) + label_h(color_number) = plot(co_data(subj_no).ref_co(s), co_data(subj_no).co_est(s), 'o', 'color', colors(color_number,:), ... + 'MarkerSize', 10, 'MarkerEdgeColor', colors(color_number,:), 'MarkerFaceColor', colors(color_number,:)); + hold on + else + label_h(color_number) = plot(co_data(subj_no).ref_co(s), co_data(subj_no).co_est(s), 'o', 'color', colors(color_number,:), ... + 'MarkerSize', 6, 'MarkerEdgeColor', colors(color_number,:), 'MarkerFaceColor', colors(color_number,:)); + hold on + end + end + + % set limits and plot line of identity + const = 0.2; + lims = [min([co_data(subj_no).ref_co; co_data(subj_no).co_est]), max([co_data(subj_no).ref_co; co_data(subj_no).co_est])]; + lims = [floor(lims(1)-(const*range(lims))), ceil(lims(2)+(const*range(lims)))]; + xlim(lims), ylim(lims), axis equal, plot(lims, lims, 'k'), xlim(lims), ylim(lims) + + % Find individual errors + mape = nan(size(param_vals)); + for s = 1 : length(mape) + rel_els = find(param_data == param_vals(s)); + mape(s) = round(1000*mean(abs((co_data(subj_no).co_est(rel_els) - co_data(subj_no).ref_co(rel_els))./co_data(subj_no).ref_co(rel_els))))/10; + end + + + % make legend + for s = 1 : length(param_vals) + labels{s} = [chosen_option ' = ' num2str(param_vals(s)) ', MAPE = ' num2str(mape(s))]; + end + legend(label_h', labels, 'Position', [0.65,0.5, 0.3, 0.2]) + + % Add axis labels + xlabel('Reference CO [l/min]', 'FontSize', ftsize) + ylabel('Estimated CO [l/min]', 'FontSize', ftsize) + set(gca, 'FontSize', ftsize, 'XTick', ceil(lims(1)):lims(end), 'YTick', ceil(lims(1)):lims(end)) + + % Find error + mape = round(10*100*mean(abs(co_data(subj_no).co_est - co_data(subj_no).ref_co)./co_data(subj_no).ref_co))/10; + title(['Varying ' strrep(chosen_option, '_', ' ') '. MAPE = ' num2str(mape) ' %']) + + % Display results + + message = ['\n\nResults:', '\n--------']; + message = [message, '\n ', 'Mean absolute percentage error: ', num2str(mape), ' %%']; + message = [message, '\n']; + + fprintf(message) + +end + +end + +function make_additional_plots(co_data, up) + +%% - Plot of ABP pulse + +% extract data +data.v = co_data.p{find(co_data.baseline_el)}; +data.t = (0:length(data.v)-1)./data.settings.fs; + +% make figure +figure('Position', [100,100,500,400]) +ftsize = 14; + +% plot areas +rel_els = data.t <= up.analysis.duration_systole/1000; +h = area(data.t(rel_els), data.v(rel_els)); hold on +h.FaceColor = 0.7*ones(1,3); +h.LineStyle = 'none'; +dim = [.23 .3 .1 .1]; +str = {'Systolic','Area'}; +annotation('textbox',dim,'String',str,'FitBoxToText','on', 'LineStyle', 'none', 'FontSize', ftsize); +rel_els = data.t > up.analysis.duration_systole/1000; +h = area(data.t(rel_els), data.v(rel_els)); hold on +h.FaceColor = 0.5*ones(1,3); +h.LineStyle = 'none'; +dim = [.53 .3 .1 .1]; +str = {'Diastolic','Area'}; +annotation('textbox',dim,'String',str,'FitBoxToText','on', 'LineStyle', 'none', 'FontSize', ftsize); + +% plot pulse +lwidth = 2; +plot(data.t,data.v, 'b', 'LineWidth', lwidth) +xlabel('Time [s]', 'FontSize', ftsize) +ylabel('ABP [Pa]', 'FontSize', ftsize) +set(gca, 'FontSize', ftsize) +ylim([0, 1.1*max(data.v)]) +box off + +savepath = 'C:\Users\pc13\Dropbox\Work\AppliedMaths_SummerSchool\Classes\Day7\Group Activity\Figures\abp_pulse'; +print(gcf,savepath,'-depsc') +close('all') + +end + +function make_results_plots(data, up, PATHS) + +fprintf('\n - Making plots') + +% calculate errors +data.error = data.co_cal-data.ref_co; +data.ape = abs(100*(data.error./data.ref_co)); + +% cycle through each algorithm +for rel_alg = 1:length(data.co_cal(1,:)) + + % Extract results for this algorithm + params = fieldnames(data.params); + rel_ape_data = nan(sum(data.group1),length(params)); %sum(data.group1),length(params)); + for param_no = 1 : length(params) + curr_param = params{param_no}; + eval(['rel_subjs = data.group' num2str(param_no) ';']); + rel_ape_data(:, param_no) = data.ape(rel_subjs,rel_alg); + end + + %% make scatter plots + + % setup + paper_size = [500,400]; + figure('Position', [20,20,paper_size]) + ftsize = 22; + all_color = 0.4*[1,1,1]; + + % plot + plot([0,14], [0,14], 'Color', 0.4*[1,1,1]), hold on + x_data = data.ref_co(data.group7); + y_data = data.co_cal(data.group7,rel_alg); + plot(x_data, y_data, 'o', 'Color', all_color, 'MarkerFaceColor', all_color) + + x_data = data.ref_co(data.group3); + y_data = data.co_cal(data.group3,rel_alg); + plot(x_data, y_data, 'or', 'MarkerFaceColor', 'r', 'MarkerSize', 8) + + x_data = data.ref_co(data.group6 | data.group5); + y_data = data.co_cal(data.group6 | data.group5,rel_alg); + plot(x_data, y_data, 'ob', 'MarkerFaceColor', 'b', 'MarkerSize', 8) + + + % tidy up + all_data = [data.ref_co(data.group7); data.co_cal(:,rel_alg)]; + lims = [floor(min(all_data)), ceil(max(all_data))]; + xlim(lims), ylim(lims) + box off + set(gca, 'FontSize', ftsize) + xlabel('Reference CO (l/min)', 'FontSize', ftsize) + ylabel('Estimated CO (l/min)', 'FontSize', ftsize) + curr_alg = up.algorithm_types{rel_alg}; + switch curr_alg + case 'liljestrand' + title_text = 'Pulse Pressure'; + case 'rms' + title_text = 'Root-Mean-Square'; + end + dim = [0.15,0.7,0.7,0.3]; + annotation('textbox',dim,'String',[title_text, ' Algorithm'],'LineStyle', 'none', 'FontSize', ftsize, 'HorizontalAlignment', 'center'); + + % annotate MAPE + data.mape(rel_alg,1) = mean(data.ape(data.group7, rel_alg)); + dim = [.5 .14 .2 .2]; + str = ['MAPE (all) = ' num2str(data.mape(rel_alg),'%5.1f'), ' %']; + annotation('textbox',dim,'String',str,'FitBoxToText','on', 'LineStyle', 'none', 'FontSize', ftsize-2, 'Color', all_color); + + data.mape_mbp(rel_alg,1) = mean(data.ape(data.group3, rel_alg)); + dim = [.5 .08 .2 .2]; + str = ['MAPE (MAP) = ' num2str(data.mape_mbp(rel_alg),'%5.1f'), ' %']; + annotation('textbox',dim,'String',str,'FitBoxToText','on', 'LineStyle', 'none', 'FontSize', ftsize-2, 'Color', 'r'); + + data.mape_co(rel_alg,1) = mean(data.ape( (data.group6 | data.group5), rel_alg)); + dim = [.5 .02 .2 .2]; + str = ['MAPE (CO) = ' num2str(data.mape_co(rel_alg),'%5.1f'), ' %']; + annotation('textbox',dim,'String',str,'FitBoxToText','on', 'LineStyle', 'none', 'FontSize', ftsize-2, 'Color', 'b'); + + % save plot + PrintFigs(gcf, paper_size/70, [PATHS.CaseStudies, 'CO_analysis_corr_', curr_alg]) + +end + +end + +function PrintFigs(h, paper_size, savepath, close_plot) +set(h,'PaperUnits','inches'); +set(h,'PaperSize', [paper_size(1), paper_size(2)]); +set(h,'PaperPosition',[0 0 paper_size(1) paper_size(2)]); +set(gcf,'color','w'); +print(h,'-dpdf',savepath) +print(h,'-depsc',savepath) +%print(h,'-dpng',savepath) + +% if you want .eps illustrations, then do as follows: +up.eps_figs = 0; +if up.eps_figs + % you need to download 'export_fig' from: + % http://uk.mathworks.com/matlabcentral/fileexchange/23629-export-fig + export_fig_dir_path = 'C:\Documents\Google Drive\Work\Projects\PhD\Github\phd\Tools\Other Scripts\export_fig\altmany-export_fig-76bd7fa\'; + addpath(export_fig_dir_path) + export_fig(savepath, '-eps') +end + +if nargin > 3 && ~close_plot +else + close all; +end + +% save +fid = fopen([savepath, '.txt'], 'w'); +p = mfilename('fullpath'); +p = strrep(p, '\', '\\'); +fprintf(fid, ['Figures generated by:\n\n ' p '.m \n\n on ' datestr(today)]); +fclose all; + +end","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/Literature Review/pwdb_changes_with_age_analysis.m",".m","14656","345","function results_table = pwdb_changes_with_age_analysis +% PWDB_CHANGES_WITH_AGE_ANALYSIS runs an analysis of metadata from a literature +% review of articles describing changes in cardiovascular parameters with +% age. +% +% pwdb_changes_with_age_analysis +% +% Inputs: +% pwdb_changes_with_age_review.txt - An input file containing the +% metadata from the literature review, which is provided as +% supplementary material with the article (detailed below). +% +% Outputs: +% results_table - A table containing the results of the literature +% review. +% +% Accompanying Article: +% This code is provided to facilitate reproduction of the literature +% review analysis performed in: +% Charlton P.H. et al. Modelling arterial pulse waves in healthy +% ageing: a database for in silico evaluation of haemodynamics +% and pulse wave indices, ~~ under review ~~ +% DOI: ~~ tbc ~~ +% Further information on the literature review is provided in this +% article and its supplementary material. +% +% Author: Peter H. Charlton +% +% Licence: +% Permission is hereby granted, free of charge, to any person obtaining a copy +% of this software and associated documentation files (the ""Software""), to deal +% in the Software without restriction, including without limitation the rights +% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +% copies of the Software, and to permit persons to whom the Software is +% furnished to do so, subject to the following conditions: +% +% The above copyright notice and this permission notice shall be included in all +% copies or substantial portions of the Software. +% +% THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +% SOFTWARE. +% +% Copyright (C) 2019 King's College London +% +% v.1.0 Peter H. Charlton, King's College London% + +% Output the licence details +provide_licence_details + +% Setup universal parameters +up = setup_up; + +% Load data from Excel Spreadsheet +data = load_data(up); + +% Eliminate repeated data +data = eliminate_repetitions(data, up); + +% Make initial table of literature review results +init_results_table = make_init_table_of_results(data, up); + +% Make final table of literature review results +results_table = make_final_table_of_results(init_results_table, up); + +end + +function provide_licence_details + +licence_details = ['\n\n changes_with_age_analysis', ... + '\n Copyright (C) 2018 King''s College London',... + '\n This program comes with ABSOLUTELY NO WARRANTY', ... + '\n and is available under the GNU public license.\n']; + +fprintf(licence_details) + +end + +function up = setup_up + +close all + +filename = 'pwdb_changes_with_age_review.txt'; +up.paths.root_folder = [fileparts(mfilename('fullpath')), filesep]; +up.paths.raw_data = [up.paths.root_folder, filename]; +if ~exist(up.paths.raw_data, 'file') + uiwait(msgbox(['At the next dialog box, please select the ""' filename '"" file which was provided as Supplementary Material'])) + [~,up.paths.root_folder] = uigetfile(up.paths.raw_data); + if isnumeric(up.paths.root_folder) && up.paths.root_folder == 0 + error(['Couldn''t find the input data file (' filename '). Please download it from the article''s supplementary material, and try again.']) + end + up.paths.raw_data = [up.paths.root_folder, filename]; +end +up.paths.savefolder = up.paths.root_folder; + +up.curr_params_for_analysis = {'Dia - Aorta Abd', 'Dia - Aorta Asc', 'Dia - Aorta D Thor', 'Dia - Carotid', 'Ejection time', 'Heart rate', 'Cardiac output', 'Stroke volume'}; +up.curr_params_for_change_with_age_plots = {'Stroke volume_pmd', 'Stroke volume_amd', 'Stroke volume_lit', 'Dia_desc_thor_pmd', 'Dia_desc_thor_amd', 'Dia_desc_thor_lit', 'Dia_abd_ao_pmd', 'Dia_abd_ao_amd', 'Dia_abd_ao_lit', 'Dia_asc_ao_pmd', 'Dia_asc_ao_amd', 'Dia_asc_ao_lit', 'Heart rate_pmd', 'Heart rate_amd'}; +up.eps_figs = 0; +up.ftsize = 20; + +up.mod_ages = 25:80; +up.mod_age_ticks = 20:10:up.mod_ages(end); +up.baseline_age = 25; +up.do_plot = 1; +up.color_2sd = 0.5*ones(1,3); +up.color_1sd = 0.75*ones(1,3); +up.mean_color = 'b'; +up.ylim_offset = 0.1; + +up.params.change_with_age = {'Dia - Aorta Abd', 'Dia - Aorta D Thor', 'Dia - Aorta Asc', 'Dia - Carotid', 'Length - Aorta Asc', 'Stroke volume', 'Heart rate', 'PWV - Aorta', 'PWV - Arm', 'PWV - Leg', 'Stiffness - Radial', 'Stiffness - Iliac', 'Stiffness - Femoral', 'Stiffness - Carotid', 'Stiffness - Brachial', 'Stiffness - Aorta D Thor', 'Stiffness - Aorta Asc', 'Stiffness - Aorta Abd', 'Sys Compliance', 'Sys Vasc Res', 'Length - Carotid', 'Length - Aorta D Thor', 'Length - Aorta Abd', 'Ejection time'}; + +end + +function init_results_table = make_init_table_of_results(data, up) + +fprintf('\n - Making initial table of results') + +vars = unique(data.var); + +%% Extract the number of articles which reported each type of change for each variable +for var_no = 1 : length(vars) + + curr_var = vars{var_no}; + rel_els = find(strcmp(data.var, curr_var)); + + changes.n(var_no) = length(rel_els); + changes.inc(var_no) = sum(strcmp(data.change(rel_els), 'increase')); + changes.dec(var_no) = sum(strcmp(data.change(rel_els), 'decrease')); + changes.none(var_no) = sum(strcmp(data.change(rel_els), 'none')); + changes.non_linear(var_no) = sum(strcmp(data.change(rel_els), 'non_linear')); + +end + +%% Find percentage of articles which reported each type of change +temp = fieldnames(changes); +for field_no = 1 : length(temp) + eval(['perc_changes.' temp{field_no} ' = 100*changes.' temp{field_no} './changes.n;']); +end +y = [perc_changes.dec(:), perc_changes.none(:), perc_changes.inc(:), perc_changes.non_linear(:)]; + + +%% Create strings of articles which investigated each parameter +articles_strings = cell(length(vars),1); +for var_no = 1 : length(vars) + rel_els = find(strcmp(data.var, vars{var_no})); + articles_strings{var_no} = ''; + for article_no = 1 : length(rel_els) + articles_strings{var_no} = [articles_strings{var_no}, data.article{rel_els(article_no)}, ',']; + end + articles_strings{var_no} = articles_strings{var_no}(1:end-1); +end + +%% Create table summarising literature review +var = vars; +n = changes.n'; +inc_n = changes.inc'; +inc_p = 100*inc_n./n; +dec_n = changes.dec'; +dec_p = 100*dec_n./n; +none_n = changes.none'; +none_p = 100*none_n./n; +non_linear_n = changes.non_linear'; +non_linear_p = 100*non_linear_n./n; + +init_results_table = table(var,n,none_p,inc_p,dec_p,non_linear_p,articles_strings); + +end + +function final_results_table = make_final_table_of_results(init_results_table, up) + +fprintf('\n - Making final table of results') + +req_params = {'Heart rate', 'Stroke volume', 'Ejection time', 'Peak flow time', 'Reverse Flow Volume', 'PWV Aorta', 'PWV - Arm', 'PWV - Leg', 'Dia - Aorta Asc', 'Dia - Aorta D Thor', 'Dia - Aorta Abd', 'Dia - Carotid', 'Dia - Iliac', 'Dia - Femoral', 'Dia - Brachial', 'Dia - Radial', 'Length - prox aorta', 'Length - dist aorta', 'Length - Carotid', 'Length - Iliac', 'Systemic Vascular Resistance', 'Systemic Vascular Compliance'}; + +for param_no = 1 : length(req_params) + + % Identify current parameter + curr_param = req_params{param_no}; + + % See if this corresponds to a single parameter in the literature review + rel_row_el = find(strcmp(init_results_table.var, curr_param)); + if ~isempty(rel_row_el) + + temp = init_results_table(rel_row_el,:); + articles_strings = strsplit(temp.articles_strings{1,1}, ','); + temp.n_studies = temp.n; + temp.n_articles = length(unique(articles_strings)); + temp = [temp(:,1),temp(:,[end-1,end]),temp(:,2:end-2)]; + temp.n = []; + rel_row = temp; + else + % if not, then collect the data from the parameters which + % correspond to this parameter. + switch curr_param + case 'PWV Aorta' + rel_row_els = ~cellfun(@isempty, strfind(init_results_table.var, 'PWV - Aorta')) & ~strcmp(init_results_table.var, 'PWV - Aorta Leg'); + case 'Length - prox aorta' + rel_row_els = ~cellfun(@isempty, strfind(init_results_table.var, 'Length - Aorta Asc')) | ~cellfun(@isempty, strfind(init_results_table.var, 'Length - Aorta Arch')); + case 'Length - dist aorta' + rel_row_els = ~cellfun(@isempty, strfind(init_results_table.var, 'Length - Aorta Abd')) | ~cellfun(@isempty, strfind(init_results_table.var, 'Length - Aorta D Thor')) | ~cellfun(@isempty, strfind(init_results_table.var, 'Length - Aorta Desc')) | ~cellfun(@isempty, strfind(init_results_table.var, 'Length - Aorta Thor')); + end + rel_rows = init_results_table(rel_row_els,:); + + % collect these rows into a single row + var = {curr_param}; + n_studies = sum(rel_rows.n); + none_p = 100*sum(rel_rows.n.*rel_rows.none_p/100)/n_studies; + inc_p = 100*sum(rel_rows.n.*rel_rows.inc_p/100)/n_studies; + dec_p = 100*sum(rel_rows.n.*rel_rows.dec_p/100)/n_studies; + non_linear_p = 100*sum(rel_rows.n.*rel_rows.non_linear_p/100)/n_studies; + all_articles = []; + for s = 1 : height(rel_rows) + all_articles = [all_articles, strsplit(rel_rows.articles_strings{s}, ',')]; + end + all_articles = unique(all_articles); + articles_strings = ''; + for s= 1 : length(all_articles) + articles_strings = [articles_strings, all_articles{s}, ',']; + end + articles_strings = {articles_strings(1:end-1)}; + n_articles = length(all_articles); + rel_row = table(var, n_studies, n_articles, none_p, inc_p, dec_p, non_linear_p, articles_strings); + clear var n_studies n_articles none_p inc_p dec_p non_linear_p articles_strings rel_rows rel_row_els curr_param + end + + final_results_table(param_no,:) = rel_row; + clear rel_row rel_row_el +end +clear param_no + +% Rename some variables +final_results_table.var = strrep(final_results_table.var, 'PWV - Aorta Leg', 'PWV - Lower Limb'); +final_results_table.var = strrep(final_results_table.var, 'PWV - Aorta Arm', 'PWV - Upper Limb'); +final_results_table.var = strrep(final_results_table.var, 'Dia - Aorta Asc', 'Dia - Asc Aorta'); +final_results_table.var = strrep(final_results_table.var, 'Dia - Aorta D Thor', 'Dia - Desc Thor Aorta'); +final_results_table.var = strrep(final_results_table.var, 'Dia - Aorta Abd', 'Dia - Abd Aorta'); + +end + +function rows = load_data(up) + +fprintf('\n - Loading data from input file') + +filepath = up.paths.raw_data; +if strcmp(filepath(end-2:end),'xls') || strcmp(filepath(end-3:end),'xlsx') + % If the raw data is presented in Excel Format + [~, ~, data] = xlsread(up.paths.raw_data); + headers = data(1,:); + rel_col = find(strcmp(headers, 'Article')); + rows.article = data(2:end, rel_col); + rel_col = find(strcmp(headers, 'Dependent Variable')); + rows.var = data(2:end, rel_col); + rel_col = find(strcmp(headers, 'Subgroup')); + rows.subgroup = data(2:end, rel_col); + rel_col = find(strcmp(headers, 'Significant Change')); + rows.change = data(2:end, rel_col); + rel_col = find(strcmp(headers, 'No subjects')); + rows.n = data(2:end, rel_col); + rows.n = convert_to_num(rows.n); +else + % If it is tab-delimited format + data = tdfread(up.paths.raw_data); + rows.article = cellstr(data.Article); + rows.var = cellstr(data.Dependent_Variable); + rows.subgroup = cellstr(data.Subgroup); + rows.change = cellstr(data.Significant_Change); + rows.n = data.No_subjects; +end + +end + +function data = eliminate_repetitions(data, up) + +fprintf('\n - Eliminating repetitions') + +% eliminate rows +elim_rows = []; +% eliminate repetition due to difference between compliance and distensibility (for reasons given in article discussion) +curr_el = find(strcmp(data.article, 'VanderHeijden-Spek2000') & strcmp(data.subgroup, 'compliance')); +elim_rows = [elim_rows; curr_el]; +% eliminate repetition due to difference between women and men (taking men) +curr_el = find(strcmp(data.article, 'Fleg1995') & strcmp(data.subgroup, 'women')); +elim_rows = [elim_rows; curr_el]; +% eliminate repetitions due to differences between intima and media thickness +curr_el = find(strcmp(data.article, 'Virmani1991') & ~cellfun(@isempty, strfind(data.subgroup, 'media'))); +elim_rows = [elim_rows; curr_el]; +% eliminate repetitions due to different methods for calculating ejection time (corrected or not) +curr_el = find(strcmp(data.article, 'Gardin1987') & ~cellfun(@isempty, strfind(data.subgroup, 'corrected'))); +elim_rows = [elim_rows; curr_el]; +curr_el = find(strcmp(data.article, 'Shaw1973') & ~cellfun(@isempty, strfind(data.subgroup, 'Q-wave to PCG sound'))); +elim_rows = [elim_rows; curr_el]; +% eliminate repetitions due to different methods for measuring ejection time (from pressure wave or echo) +curr_el = find(strcmp(data.article, 'Salvi2018') & ~cellfun(@isempty, strfind(data.subgroup, 'carotid'))); +elim_rows = [elim_rows; curr_el]; + + + +keep_rows = setxor(1:length(data.article), elim_rows); +data_fields = fieldnames(data); +for field_no = 1 : length(data_fields) + eval(['data.' data_fields{field_no} ' = data.' data_fields{field_no} '(keep_rows);']); +end + +clear elim_rows keep_rows + +% identify entries which are repetitions from the same article. +for s = 1 : length(data.article) + temp{s} = [data.article{s}, data.var{s}]; +end +temp = temp(:); + +elim_rows = []; +for s = 2 : length(temp) + repeat_els = find(strcmp(temp{s}, temp(1:s-1))); + if ~isempty(repeat_els) + cand_changes = [data.change{s}; data.change(repeat_els)]; + if length(unique(cand_changes)) > 1 + error('Do something about this'); + end + elim_rows = [elim_rows; s]; + end +end + +% eliminate repetitions +keep_rows = setxor(1:length(temp), elim_rows); +data_fields = fieldnames(data); +for field_no = 1 : length(data_fields) + eval(['data.' data_fields{field_no} ' = data.' data_fields{field_no} '(keep_rows);']); +end + +end + +function new = convert_to_num(old) + +% From: https://uk.mathworks.com/matlabcentral/answers/30547-convert-cell-to-matrix-with-mixed-data-types + +old(cellfun(@ischar,old)) = {NaN}; +new = cell2mat(old); + +end +","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/Additional Functions/make_param_label.m",".m","13025","404","function [label, units, abbr, graph_title, graph_title_no_units] = make_param_label(curr_param) + + +switch curr_param + case {'HR', 'hr'} + label = 'HR: Heart rate [bpm]'; + units = 'bpm'; + abbr = 'HR'; + graph_title = 'Heart Rate [bpm]'; + case {'SV', 'sv'} + label = 'SV: Stroke volume [ml]'; + units = 'ml'; + abbr = 'SV'; + graph_title = 'Stroke Volume [ml]'; + case 'CO' + label = 'CO: Cardiac output [l/min]'; + units = 'l/min'; + abbr = 'CO'; + graph_title = 'Cardiac Output [l/min]'; + case {'LVET', 'lvet'} + label = 'LVET: Left ventricular ejection time [ms]'; + units = 'ms'; + abbr = 'LVET'; + graph_title = 'Left Ventricular Ejection Time [ms]'; + case 'dPdt' + label = 'dP/dt: Maximum aortic value [mmHg/s]'; + units = 'mmHg/s'; + abbr = 'dp/dt'; + graph_title = 'dP/dt [mmHg/s]'; + case {'t_PF', 't_pf', 'PFT', 'pft'} + label = 'PFT: Peak flow time [ms]'; + units = 'ms'; + abbr = 'PFT'; + graph_title = 'Peak Flow Time [ms]'; + case {'reg_vol', 'RFV', 'rfv'} + label = 'Reverse flow volume [ml]'; + units = 'ml'; + abbr = 'RFV'; + graph_title = 'Reverse Flow Volume [ml]'; + case 'SBP_a' + label = 'Aortic pressure [mmHg]: SBP, systolic'; + units = 'mmHg'; + abbr = 'SBP_a'; + graph_title = 'Aortic SBP [mmHg]'; + case 'DBP_a' + label = '\\hspace{4.1cm} DBP, diastolic'; + units = 'mmHg'; + abbr = 'DBP_a'; + graph_title = 'Aortic Disatolic Blood Pressure [mmHg]'; + case 'dbp' + label = 'dbp'; + units = 'mmHg'; + abbr = 'DBP'; + graph_title = 'Diastolic Blood Pressure [mmHg]'; % 'DBP [mmHg]' + case {'MBP_a', 'mbp', 'MBP'} + label = '\\hspace{4.1cm} MAP, mean'; + units = 'mmHg'; + abbr = 'MAP_a'; + graph_title = 'Mean Arterial Pressure [mmHg]'; %'Aortic MBP [mmHg]'; + case 'PP_a' + label = '\\hspace{4.1cm} PP, pulse pressure'; + units = 'mmHg'; + abbr = 'PP_a'; + graph_title = 'Aortic PP [mmHg]'; + case 'SBP_b' + label = 'Brachial pressure [mmHg]: SBP'; + units = 'mmHg'; + abbr = 'SBP_b'; + graph_title = 'Brachial SBP [mmHg]'; + case 'DBP_b' + label = '\\hspace{4.5cm} DBP'; + units = 'mmHg'; + abbr = 'DBP_b'; + graph_title = 'Brachial DBP [mmHg]'; + case 'MBP_b' + label = '\\hspace{4.5cm} MBP'; + units = 'mmHg'; + abbr = 'MBP_b'; + graph_title = 'Brachial MBP [mmHg]'; + case 'PP_b' + label = '\\hspace{4.5cm} PP'; + units = 'mmHg'; + abbr = 'PP_b'; + graph_title = 'Brachial PP [mmHg]'; + case 'SBP_f' + label = 'Digital pressure [mmHg]: SBP'; + units = 'mmHg'; + abbr = 'SBP_b'; + graph_title = 'Digital SBP [mmHg]'; + case 'DBP_f' + label = '\\hspace{4.5cm} DBP'; + units = 'mmHg'; + abbr = 'DBP_b'; + graph_title = 'Digital DBP [mmHg]'; + case 'MBP_f' + label = '\\hspace{4.5cm} MBP'; + units = 'mmHg'; + abbr = 'MBP_b'; + graph_title = 'Digital MBP [mmHg]'; + case 'PP_f' + label = '\\hspace{4.5cm} PP'; + units = 'mmHg'; + abbr = 'PP_b'; + graph_title = 'Digital PP [mmHg]'; + case 'PP_amp' + label = 'Pulse Pressure Amplification'; + units = 'ratio'; + abbr = 'PP_{amp}'; + graph_title = 'Pulse Pressure Amplification'; + case {'AP', 'AP_c', 'AP_a'} + label = 'Augmentation Pressure [mmHg]'; + units = 'mmHg'; + abbr = 'AP'; + graph_title = 'Augmentation Pressure [mmHg]'; + case {'AIx', 'AI_c', 'AI_a'} + label = 'Augmentation Index [\\%%]'; + units = '%%'; + abbr = 'AIx'; + graph_title = 'Augmentation Index [%]'; + case 'PWV_a' + label = 'Pulse wave velocity [m/s]: aortic'; + units = 'm/s'; + abbr = 'PWV_{a}'; + graph_title = 'Aortic PWV [m/s]'; + case {'PWV_cf', 'pwv_cf', 'expected_pwv_aorta'} + label = '\\hspace{4.43cm} carotid-femoral'; + units = 'm/s'; + abbr = 'PWV_{cf}'; + graph_title = 'Carotid-Femoral PWV [m/s]'; + case 'pwv' + label = 'Pulse wave velocity [m/s]'; + units = 'm/s'; + abbr = 'PWV'; + graph_title = 'Pulse wave velocity [m/s]'; + case {'PWV_br', 'pwv_br', 'expected_pwv_arm'} + label = '\\hspace{4.43cm} brachial-radial'; + units = 'm/s'; + abbr = 'PWV_{br}'; + graph_title = 'Brachial-Radial PWV [m/s]'; + case {'PWV_fa', 'pwv_fa', 'expected_pwv_leg'} + label = '\\hspace{4.43cm} femoral-ankle'; + units = 'm/s'; + abbr = 'PWV_{fa}'; + graph_title = 'Femoral-Ankle PWV [m/s]'; + case {'dia_asc_a', 'dia_asc'} + label = 'Diameter [mm]: ascending aorta'; + units = 'mm'; + abbr = 'dia_{asca}'; + graph_title = 'Asc. Aorta Dia [mm]'; + case {'dia_desc_thor_a', 'dia_desc_thor'} + label = '\\hspace{2.7cm} descending thoracic aorta'; + units = 'mm'; + abbr = 'dia_{dta}'; + graph_title = 'Desc. Thor. Aorta Dia [mm]'; + case {'dia_abd_a', 'dia_abd'} + label = '\\hspace{2.7cm} abdominal aorta'; + units = 'mm'; + abbr = 'dia_{abda}'; + graph_title = 'Abd. Aorta Dia [mm]'; + case {'dia_car', 'dia_carotid'} + label = '\\hspace{2.7cm} carotid'; + units = 'mm'; + abbr = 'dia_{car}'; + graph_title = 'Carotid Dia [mm]'; + case 'len_prox_a' + label = 'Length of proximal aorta [mm]'; + units = 'mm'; + abbr = 'Len'; + graph_title = 'Prox. Aortic Length [mm]'; + case 'svr' + label = 'Systemic vascular resistance [10$^6$ Pa s m$^{-3}$]'; + units = '10^6 Pa s / m3'; + abbr = 'SVR'; + graph_title = 'Systemic Vascular Resistance'; + case {'Tr', 'Tr_a', 'Tr_c'} + label = 'Time to Reflected Wave [ms]'; + units = 'ms'; + abbr = 'Tr'; + graph_title = 'Time to Reflected Wave [ms]'; + case 'ht' + label = 'Height [m]'; + units = 'm'; + abbr = 'Ht'; + graph_title = 'Height [m]'; + case 'MBP_drop_finger' + label = 'Pressure drop to finger [mmHg]'; + units = 'mmHg'; + abbr = 'drop fin'; + graph_title = 'Pressure drop to finger [mmHg]'; + case 'MBP_drop_ankle' + label = 'Pressure drop to ankle [mmHg]'; + units = 'mmHg'; + abbr = 'drop ankle'; + graph_title = 'Pressure drop to ankle [mmHg]'; + case 'dia' + label = 'Arterial diameter'; + units = 'm'; + abbr = 'Dia'; + graph_title = 'Arterial diameter [m]'; + case 'len' + label = 'Proximal aortic length [m]'; + units = 'm'; + abbr = 'Len'; + graph_title = 'Proximal Aortic Length [m]'; + case {'rho','density'} + label = 'Density'; + units = 'kg /m^3'; + abbr = 'rho'; + graph_title = 'Density [kg /m^3]'; + case {'pvc', 'PVC'} + label = 'Peripheral vasc comp.'; + units = 'scaling factor'; + abbr = 'PVC'; + graph_title = 'Peripheral Vasc Comp. []'; + case {'pvc_adj'} + label = 'Peripheral vasc compliance [10^9 m^3/Pa]'; + units = 'm3/Pa'; + abbr = 'PVC'; + graph_title = 'Peripheral vasc comp. [10^9 m^3/Pa]'; + case 'p_out' + label = 'Outflow pressure [mmHg]'; + units = 'mmHg'; + abbr = 'p_out'; + graph_title = 'Outflow pressure [mmHg]'; + case 'p_drop' + label = 'Assumed pressure drop [mmHg]'; + units = 'mmHg'; + abbr = 'p_drop'; + graph_title = 'Assumed pressure drop [mmHg]'; + case 'time_step' + label = 'Simulation time step [s]'; + units = 's'; + abbr = 'time_step'; + graph_title = 'Simulation time step [s]'; + case {'mu', 'viscosity'} + label = 'Viscosity [Pa s]'; + units = 'Pa s'; + abbr = 'mu'; + graph_title = 'Viscosity [Pa s]'; + case 'alpha' + label = 'Alpha [-]'; + units = '-'; + abbr = '\alpha'; + graph_title = 'Alpha [-]'; + case 'age' + label = 'Age [years]'; + units = 'years'; + abbr = 'age'; + graph_title = 'Age [years]'; + case 'visco_elastic_log' + label = 'Elastic (0) or visco-elastic (1)'; + units = ''; + abbr = 'viscLog'; + graph_title = 'Elastic vs Visco-Elastic'; + case 'AGI_mod' + label = 'Modified Ageing Index [au]'; + units = 'au'; + abbr = 'agi_mod'; + graph_title = 'Modified Ageing Index'; + case 'gamma' + label = 'Wall viscosity'; + units = 'au'; + abbr = 'gamma'; + graph_title = 'Wall Viscosity'; + case 'RI' + label = 'Reflection Index [au]'; + units = 'au'; + abbr = 'ri'; + graph_title = 'Reflection Index'; + case 'SI' + label = 'Stiffness Index [m/s]'; + units = 'm/s'; + abbr = 'ri'; + graph_title = 'Stiffness Index'; + case 'IAD' + label = 'Inter-arm SBP Difference'; + units = 'mmHg'; + abbr = 'IAD'; + graph_title = 'Inter-arm SBP Difference'; + case 'IADabs' + label = 'abs Inter-arm SBP Difference'; + units = 'mmHg'; + abbr = 'IADabs'; + graph_title = 'abs Inter-arm SBP Difference'; + case 'pvr' + label = 'Peripheral Vascular Resistance'; + units = 'Pa s/m^3'; + abbr = 'PVR'; + graph_title = label; + case {'b0', 'gamma_b0'} + label = 'Wall Viscosity b0 Parameter'; + units = 'g/s'; + abbr = 'b0'; + graph_title = label; + case {'b1', 'gamma_b1'} + label = 'Wall Viscosity b1 Parameter'; + units = 'g cm/s'; + abbr = 'b1'; + graph_title = label; + case 'k1' + label = 'Stiffness k1 Parameter'; + units = 'g/s^2/cm'; + abbr = 'k1'; + graph_title = label; + case 'k2' + label = 'Stiffness k2 Parameter'; + units = '/cm'; + abbr = 'k2'; + graph_title = label; + case 'k3' + label = 'Stiffness k3 Parameter'; + units = 'g/s^2/cm'; + abbr = 'k3'; + graph_title = label; + case 'reflect_log' + label = 'Reflections'; + units = ''; + abbr = 'Reflections'; + graph_title = label; + case 'SBP_diff' + label = 'Difference in aortic and brachial SBP [mmHg]'; + units = 'mmHg'; + abbr = 'SBP_diff'; + graph_title = 'Difference in aortic and brachial SBP [mmHg]'; + case 'SMBP_a' + label = 'Systolic - Mean Aortic BP [mmHg]'; + units = 'mmHg'; + abbr = 'SMBP'; + graph_title = 'Systolic - Mean Aortic BP [mmHg]'; + case 'tau' + label = 'Time constant [s]'; + units = 's'; + abbr = 'tau'; + graph_title = 'Time constant [s]'; + case 'P1t_a' + label = 'Time of aortic P1'; + units = 's'; + abbr = 'P1t'; + graph_title = 'Time of aortic P1 [s]'; + case 'P1t_c' + label = 'Time of carotid P1'; + units = 's'; + abbr = 'P1t'; + graph_title = 'Time of carotid P1 [s]'; + case 'P1_a' + label = 'Magnitude of aortic P1'; + units = 'mmHg'; + abbr = 'P1'; + graph_title = 'Magnitude of aortic P1 [mmHg]'; + case 'P1_c' + label = 'Magnitude of carotid P1'; + units = 'mmHg'; + abbr = 'P1'; + graph_title = 'Magnitude of carotid P1 [mmHg]'; + case 'P2t_a' + label = 'Time of aortic P2'; + units = 's'; + abbr = 'P2t'; + graph_title = 'Time of aortic P2 [s]'; + case 'P2t_c' + label = 'Time of carotid P2'; + units = 's'; + abbr = 'P2t'; + graph_title = 'Time of carotid P2 [s]'; + case 'P2_a' + label = 'Magnitude of aortic P2'; + units = 'mmHg'; + abbr = 'P2'; + graph_title = 'Magnitude of aortic P2 [mmHg]'; + case 'P2_c' + label = 'Magnitude of carotid P2'; + units = 'mmHg'; + abbr = 'P2'; + graph_title = 'Magnitude of carotid P2 [mmHg]'; + case 'trial' + label = 'Trial Parameter'; + units = ''; + abbr = 'trial'; + graph_title = 'Trial Parameter []'; + case 'trial2' + label = 'Trial Parameter 2'; + units = ''; + abbr = 'trial'; + graph_title = 'Trial Parameter 2 []'; + case 'trial3' + label = 'Trial Parameter 3'; + units = ''; + abbr = 'trial'; + graph_title = 'Trial Parameter 3 []'; +end + +% create graph title without units +graph_title_no_units = graph_title; +temp = strfind(graph_title_no_units, ' ['); +if ~isempty(temp) + graph_title_no_units = graph_title_no_units(1:temp-1); +end +graph_title_no_units = strrep(graph_title_no_units, 'MBP', 'Mean Arterial Pressure'); +graph_title_no_units = strrep(graph_title_no_units, 'SBP', 'Systolic Blood Pressure'); +graph_title_no_units = strrep(graph_title_no_units, 'DBP', 'Diastolic Blood Pressure'); +graph_title_no_units = strrep(graph_title_no_units, 'PP', 'Pulse Pressure'); + +end +","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/Additional Functions/estimate_ppg_using_windkessel.m",".m","915","33","function ppg = estimate_ppg_using_windkessel(P, Q, Pout) + +%% Calculate PPG + +% Calculate time vectors for input signals +P.t = [0:length(P.v)-1]/P.fs; +Q.t = [0:length(Q.v)-1]/Q.fs; + +% Find the resistance to flow further down the arterial tree +temp = P.v-Pout.v; % pressure drop between this segment and end of arterial tree +R = sum(temp)/sum(Q.v); % resistance is mean pressure drop over mean flow + +% Find the flow into the more distal part of the arterial tree from this segment +Qout.v = (P.v-Pout.v)./R; % I = V/R (electrical circuit) +Qout.t = P.t; + +% Find the volume stored in the arterial segment +Volvb.t = Q.t; +const = 0; +Volvb.v = const + cumsum(Q.v) - cumsum(Qout.v); % volume stored is the difference between inflow and outflow + +ppg.t = Volvb.t; +ppg.v = normwave(Volvb.v); + +end + +function norm_wave = normwave(orig_wave) + +norm_wave = orig_wave; + +norm_wave = (norm_wave-min(norm_wave))./range(norm_wave); + +end","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/Additional Functions/AorticFlowWave.m",".m","51898","944","function inflow = AorticFlowWave(params) +% AORTICFLOWWAVE generates an exemplary aortic flow wave, with optional +% input parameters specifying its properties +% +% AorticFlowWave +% +% Inputs: - params, an optional structure of input parameters +% +% Outputs: - inflow, a structure containing the waveform and its +% properties. +% +% Accompanying Article: +% This code is provided to facilitate reproduction of the Pulse Wave +% Database described in: +% Charlton P.H. et al. Modelling arterial pulse waves in healthy +% ageing: a database for in silico evaluation of haemodynamics +% and pulse wave indices, ~~ under review ~~ +% DOI: ~~ tbc ~~ +% Further information on the pwdb Pulse Wave Database is provided in +% this article and at the project website: +% https://peterhcharlton.github.io/pwdb +% +% Author: Peter H. Charlton +% +% Licence: +% Permission is hereby granted, free of charge, to any person obtaining a copy +% of this software and associated documentation files (the ""Software""), to deal +% in the Software without restriction, including without limitation the rights +% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +% copies of the Software, and to permit persons to whom the Software is +% furnished to do so, subject to the following conditions: +% +% The above copyright notice and this permission notice shall be included in all +% copies or substantial portions of the Software. +% +% THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +% SOFTWARE. +% +% Copyright (C) 2018 King's College London +% +% Contributed to by: Marie Willemet, Jordi Alastruey, and Peter H. Charlton +% v.1.0 + +%% ==== Setup input params (adding default and derived values where necessary) +if nargin < 1 + params = struct; +end +inflow = setup_params(params); + +%% ==== Find Template Flow Wave +template_flow = create_template_inflow_waveform(inflow); + +%% ==== Find Adjusted Flow Wave +inflow = adjust_template_flow(inflow, template_flow); + +%% ==== Adjust Sampling Frequency +inflow = adjust_sampling_frequency(inflow); + +%% ==== Calculate Characteristics of Inflow wave +inflow = calc_characteristics_inflow_wave(inflow); + +%% ==== Plot Figures +plot_figures(inflow); + +end + +function inflow = setup_params(params) + +%% Setup + +% store the user-specified input params +inflow.input_params = params; clear params + +% shut figures unless plotting multiple flow waveforms +if ~sum(strcmp(fieldnames(inflow.input_params),'plot_multiple')) + close all +end + +%% Input parameters + +% if CO and HR have been specified, but not SV, then calculate SV +curr_params = fieldnames(inflow.input_params); +if sum(strcmp(curr_params, 'HR')) && sum(strcmp(curr_params, 'CO')) && ~sum(strcmp(curr_params, 'SV')) + inflow.input_params.SV = 1000*inflow.input_params.CO / inflow.input_params.HR; +end + +% If either HR or T has been specified, but not the other, then specify it +if sum(strcmp(curr_params, 'HR')) && ~sum(strcmp(curr_params, 'T')) + inflow.input_params.T = 60/inflow.input_params.HR; +elseif ~sum(strcmp(curr_params, 'HR')) && sum(strcmp(curr_params, 'T')) + inflow.input_params.HR = 60/inflow.input_params.T; +end + +% If LVET has been specified then make sure it is in secs +if sum(strcmp(curr_params, 'LVET')) && inflow.input_params.LVET > 2 + inflow.input_params.LVET = inflow.input_params.LVET/1000; % convert from ms to secs +end + +% If T_Peak_Flow has been specified then make sure it is in secs +if sum(strcmp(curr_params, 'T_Peak_Flow')) && inflow.input_params.T_Peak_Flow > 2 + inflow.input_params.T_Peak_Flow = inflow.input_params.T_Peak_Flow/1000; % convert from ms to secs +end + +% identify any missing parameters +curr_params = fieldnames(inflow.input_params); +req_params = {'fs', 'wave_type', 'HR', 'SV', 'CO', 'T', 'LVET', 'T_Peak_Flow', 'T_sys_upslope_ip', 'Q_sys_upslope_ip', 'T_Min_Flow', 'T_dia', 'Reg_Vol', 'rev_flow', 'contractility_const'}; +curr_req_params = intersect(curr_params, req_params); +missing_params = setxor(curr_req_params, req_params); clear curr_params curr_req_params +% moves CO, LVET, T and T_sys_upslope_ip to the end, as they are dependent on other parameters. +for rel_param = req_params + temp = find(strcmp(missing_params, rel_param{1,1})); + if ~isempty(temp) + missing_params = missing_params([1:temp-1, temp+1 : length(missing_params)]); + missing_params(end+1) = {rel_param{1,1}}; + end +end + + +% If any parameters are missing then insert the baseline values for them +for param_no = 1 : length(missing_params) + + % identify the current missing parameter + curr_missing_param = missing_params{param_no}; + + % specify the baseline value of this parameter + switch curr_missing_param + case 'HR' + val = 75; % in bpm + val = 75; % Mynard's, in bpm + case 'SV' + val = 83; % im ml + val = (6.2*1000/inflow.input_params.HR); % Mynard's, in ml + case 'CO' + val = inflow.input_params.HR*inflow.input_params.SV/1000; % im l/min + %val = 6.2; % Mynard's, in l/min + case 'wave_type' + val = 'elderly'; % either 'young' or 'avg' or 'elderly' + val = 'Mynard'; % Use Mynard2015's aortic root wave + case 'rev_flow' + val = 1; % between 0 and 1 - the proportion of reverse flow to include + case 'fs' + val = 1000; % in Hz + case 'contractility_const' + val = 1; % a multiplication factor applied to the time of the systolic peak + case 'T' + val = 60/inflow.input_params.HR; + case 'T_sys_upslope_ip' + val = (0.020/0.085)*inflow.input_params.T_Peak_Flow; + val = (0.010/0.080)*inflow.input_params.T_Peak_Flow; % Mynard's + case 'Q_sys_upslope_ip' + val = 0.32; + % Haven't measured Mynard's - don't think it's used + case 'LVET' + val = calc_lvet(inflow); + val = 0.282; % Mynard's, s + case 'T_Peak_Flow' + val = (0.085/0.290)*inflow.input_params.LVET; + val = (0.080/0.282)*inflow.input_params.LVET; % Mynard's + case 'T_Min_Flow' + val = (0.310/0.290)*inflow.input_params.LVET; + val = (0.298/0.282)*inflow.input_params.LVET; % Mynard's + case 'T_dia' + val = (0.330/0.290)*inflow.input_params.LVET; + val = (0.309/0.282)*inflow.input_params.LVET; % Mynard's + case 'Reg_Vol' + val = 0.73; + val = 1.2775; % Mynard's, ml + end + + % insert this baseline value + eval(['inflow.input_params.' curr_missing_param ' = val;']) + + clear val + +end + +%% Scale contractility and reverse flow magnitude +contractility_times = {'T_sys_upslope_ip', 'T_Peak_Flow'}; +for s = 1 : length(contractility_times) + eval(['inflow.input_params.' contractility_times{s} ' = inflow.input_params.contractility_const * inflow.input_params.' contractility_times{s} ';']); +end +inflow.input_params.Reg_Vol = inflow.input_params.rev_flow * inflow.input_params.Reg_Vol; + +%% Input settings + +% identify any missing settings +curr_params = fieldnames(inflow.input_params); +req_params = {'do_plot','save_plot', 'plot_multiple', 'plot_name', 'file_path'}; +curr_req_params = intersect(curr_params, req_params); +missing_params = setxor(curr_req_params, req_params); clear curr_params req_params + +% If any parameters are missing then insert the baseline values for them +for param_no = 1 : length(missing_params) + + % identify the current missing parameter + curr_missing_param = missing_params{param_no}; + + % specify the baseline value of this parameter + switch curr_missing_param + case 'do_plot' + val = true; % whether or not to plot the generated wave + case 'save_plot' + val = false; + case 'plot_multiple' + val = false; + case 'plot_name' + val = 'AorticFlowWave_plot'; + case 'file_path' + val = '/Users/petercharlton/Google Drive/Work/Code/AorticFlowWave/AorticFlowWave manual/Figures/'; + if ~exist(val, 'dir') + val = uigetdir; + end + end + + % insert this baseline value + eval(['inflow.input_settings.' curr_missing_param ' = val;']) + + clear val + +end + +% move user specified settings to this new structure +for param_no = 1 : length(curr_req_params) + + % identify the current missing parameter + curr_setting = curr_req_params{param_no}; + + % insert this setting + eval(['inflow.input_settings.' curr_setting ' = inflow.input_params.' curr_setting ';']) + + % remove from the params structure + inflow.input_params = rmfield(inflow.input_params, curr_setting); + +end + +%% Put fields in alphabetical order +inflow.input_params = orderfields(inflow.input_params); +inflow.input_settings = orderfields(inflow.input_settings); + +end + +function LVET = calc_lvet(inflow) + +% use the function provided in the following article to derive LVET: +% +% Weissler et al, ""Relationships between left ventricular ejection time, +% stroke volume, and heart rate in normal individuals and patients with +% cardiovascular disease"", American Heart Journal, vol. 62, 1961. +% DOI: 10.1016/0002-8703(61)90403-3 + +% Function: +% LVET = 0.266 + 0.0011*(SV - 82) - 0.0009*(HR - 73) +% where LVET is in secs, SV [ml] is stroke volume, and HR [bpm] is heart rate. + +% If a LVET has been specified as an input, then take this +if ~sum(strcmp(fieldnames(inflow.input_params), 'LVET')) + + % otherwise, calculate using this formula + LVET = 0.266 + 0.0011*(inflow.input_params.SV - 82) - 0.0009*(inflow.input_params.HR - 73); % in secs + +else + LVET = inflow.input_params.LVET; +end + + +end + +function template_flow = create_template_inflow_waveform(inflow) + +%% === Setup constants +do_change = 1; +if do_change + prop = 1.2; + prop2 = 1.1; + prop3 = 1.1; + prop4 = 1.04; + prop5 = 1.05; + prop6 = 1.03; +else + [prop, prop2,prop3,prop4,prop5, prop6] = deal(1); +end + +% timings +template_flow.T = 1; +template_flow.ti_0 = (1/prop)*0.024*template_flow.T; %Time of inflection point in systolic increase +template_flow.tmax_0 = 0.08*template_flow.T; %Time of systolic peak +template_flow.ti2_0 = (1/prop5)*prop2*0.17*template_flow.T; %0.150; Time of inflection point in systolic decrease (old only) +template_flow.ti3_0 = prop4*prop2*0.21*template_flow.T; %0.150; Time of inflection point in systolic decrease (old only) +template_flow.ts_0 = 0.290*template_flow.T; %Time of start of dicrotic notch +template_flow.tmin_0 = 0.310*template_flow.T; %Time of minimum flow during dicrotic notch %%% THIS HAS BEEN ADJUSTED from 0.30 +template_flow.td_0 = 0.330*template_flow.T; %Time of start of diastole + +% flows +template_flow.Qmax = 1; %Systolic peak flow +template_flow.Qi = 0.367; %Flow at inflection point on systolic upslope +template_flow.Qi2 = prop5*prop3*(1/prop2)*0.647; %Flow at inflection point in systolic decrease (old) +template_flow.Qi3 = prop6*(1/prop3)*(1/prop2)*0.496; %Flow at second inflection point in systolic decrease (old) + +% find approximate Qmin (during reverse flow) +template_flow.Qmin = -0.1; %Minimum flow during dicrotic notch +% % Adjust if the regurgitation volume is provided +% if sum(strcmp(fieldnames(params),'Reg_Vol')) +% desired_ratio_reverse_to_forward_flow = params.Reg_Vol/(params.SV+params.Reg_Vol); +% curr_reverse_flow = abs(0.5*(template_flow.td_0-template_flow.ts_0)*template_flow.Qmin); +% curr_forward_flow = 0.5*template_flow.ts_0*template_flow.Qmax; +% approx_curr_ratio_reverse_to_forward_flow = curr_reverse_flow/curr_forward_flow; +% scale_factor = desired_ratio_reverse_to_forward_flow/approx_curr_ratio_reverse_to_forward_flow; +% template_flow.Qmin = template_flow.Qmin*scale_factor; +% end + +% round timings to right sizes of time vector +ti = round(template_flow.ti_0 *1000)./1000; +tmax = round(template_flow.tmax_0*1000)./1000; +ti2 = round(template_flow.ti2_0 *1000)./1000; +ti3 = round(template_flow.ti3_0 *1000)./1000; +ts = round(template_flow.ts_0 *1000)./1000; +tmin = round(template_flow.tmin_0*1000)./1000; +td = round(template_flow.td_0 *1000)./1000; + +% time step +dt = 1/1000; + +%% === Calculate template using Marie's piecewise polynomial + +% switch params.wave_type % young, avg, or elderly +% case 'young' +% template_flow.age = 'young'; +% template_flow.v = Get_parametric_young(dt, template_flow.Qi, template_flow.Qmax, template_flow.Qmin, ti, tmax, tmin, ts, td); +% case 'avg' +% template_flow.age = 'avg'; +% young = Get_parametric_young(dt, template_flow.Qi, template_flow.Qmax, template_flow.Qmin, ti, tmax, tmin, ts, td); +% elderly = Get_parametric_old(dt, template_flow.Qi, template_flow.Qmax, template_flow.Qmin, template_flow.Qi2, ti, tmax, tmin, ti2, ts, td); +% template_flow.v = (young+elderly)./2; clear young elderly +% case 'elderly' +% template_flow.age = 'elderly'; +% template_flow.v = Get_parametric_old(dt, template_flow.Qi, template_flow.Qmax, template_flow.Qmin, template_flow.Qi2, ti, tmax, tmin, ti2, ts, td); +% case 'impulse' +% template_flow.age = 'impulse'; +% durn_of_impulse = 0.05*template_flow.T; +% durn_of_impulse_samples = round(durn_of_impulse*(1/dt)); +% durn_of_beat = template_flow.T; +% durn_of_beat_samples = round(durn_of_beat*(1/dt)); +% template_flow.v = [0, ones(1,durn_of_impulse_samples), zeros(1,durn_of_beat_samples - durn_of_impulse_samples-1)]; +% end + +if strcmp(inflow.input_params.wave_type, 'elderly') + template_flow.age = 'elderly'; + template_flow.v = Get_parametric_pete(dt, template_flow.Qi, template_flow.Qmax, template_flow.Qmin, template_flow.Qi2, ti, tmax, tmin, ti2, ts, td, template_flow.Qi3, ti3); +elseif strcmp(inflow.input_params.wave_type, 'Mynard') + template_flow.age = 'young'; + template_flow.v = Get_Mynard2015_flow_wave; +end +template_flow.t = [0:(length(template_flow.v)-1)]*(1/1000); + +end + +function inflow = adjust_template_flow(inflow, template_flow) +%% === Adjust template to give desired timings + +% setup +dt = 1/inflow.input_params.fs; + +% Find sytolic upslope +deb = 1; [~, fin] = max(template_flow.v); +sys_upslope.v = template_flow.v(deb:fin); +sys_upslope.t = linspace(0, inflow.input_params.T_Peak_Flow, length(sys_upslope.v)); + +% Find systolic downslope +[~, temp] = max(template_flow.v); deb = temp+1; clear temp +fin = find(template_flow.v(1:end-1) > 0 & template_flow.v(2:end) <= 0); fin = fin(1); +sys_downslope.v = template_flow.v(deb:fin); +sys_downslope.t = linspace(sys_upslope.t(end)+dt, inflow.input_params.LVET, length(sys_downslope.v)); + +% Find reverse flow +deb = find(template_flow.v(1:end-1) > 0 & template_flow.v(2:end) <= 0); deb = deb(1)+1; +fin = find(template_flow.v ~= 0, 1, 'last'); +reverse.v = template_flow.v(deb:fin); +reverse.t = linspace(sys_downslope.t(end)+dt, inflow.input_params.T_dia, length(reverse.v)); + +% Find diastolic flat line +no_els = round((inflow.input_params.T - (inflow.input_params.T_dia+dt))/dt); +diastolic.t = linspace(inflow.input_params.T_dia+dt, inflow.input_params.T, no_els); +diastolic.v = zeros(size(diastolic.t)); + +% concatenate to give waveform +mod_flow.t = [sys_upslope.t, sys_downslope.t, reverse.t, diastolic.t]; +mod_flow.v = [sys_upslope.v, sys_downslope.v, reverse.v, diastolic.v]; + +% resample to give constant fs, without irregular spacing at joins +inflow.t = (0 : floor(mod_flow.t(end)*inflow.input_params.fs))/inflow.input_params.fs; +inflow.v = interp1(mod_flow.t, mod_flow.v, inflow.t); + +if sum(strcmp(fieldnames(inflow.input_params), 'Reg_Vol')) + + % Scale to give desired reverse flow volume + scale_factor = inflow.input_params.Reg_Vol/abs(sum(inflow.v(inflow.v<0)*dt)); + inflow.v(inflow.v<0) = inflow.v(inflow.v<0)*scale_factor; % flow is now in ml/s + + % Scale to give desired stroke volume + scale_factor = (inflow.input_params.SV+inflow.input_params.Reg_Vol)/(sum(inflow.v(inflow.v>0))*dt); + inflow.v(inflow.v>0) = inflow.v(inflow.v>0)*scale_factor; + +else + % Scale to give desired stroke volume + scale_factor = inflow.input_params.SV/(sum(inflow.v)*dt); + inflow.v = inflow.v*scale_factor; % flow is now in ml/s + +end + +% Convert to required units +CO_in_m3_per_sec = inflow.input_params.CO/(60*1000); %(convert from l/min) +inflow.v = inflow.v./mean(inflow.v).*CO_in_m3_per_sec; + +% Scale to give desired Qmax (if specified). This overrides the CO value +if sum(strcmp(fieldnames(inflow.input_params), 'Qmax')) + scale_factor = inflow.input_params.Qmax/max(inflow.v); + inflow.v(inflow.v>0) = inflow.v(inflow.v>0)*scale_factor; +end + +% Specify dQdt (if specified) +if sum(strcmp(fieldnames(inflow.input_params), 'dQdt_max')) + sf = 1; + options = optimset('MaxFunEvals',200, 'display', 'off'); + dQdt_cost_function = @(sf)calculate_dQdt_cost_function(inflow, inflow.input_params.dQdt_max, sf); + [optimal_sf, ~] = fminsearch(dQdt_cost_function, sf, options); + inflow = calculate_new_inflow_from_sf(inflow, optimal_sf); + current_dQdt_max = calc_dQ_dt_max(inflow); +end + +end + +function dQdt_cost_function = calculate_dQdt_cost_function(inflow, desired_dQdt_max, sf) + +new_inflow = calculate_new_inflow_from_sf(inflow, sf); + +current_dQdt_max = calc_dQ_dt_max(new_inflow); + +% fprintf(""\n - SF: %f, dQdt_max: %f"", sf, current_dQdt_max); + +dQdt_cost_function = abs(current_dQdt_max-desired_dQdt_max); + +end + +function current_dQ_dt_max = calc_dQ_dt_max(inflow) +current_dQ_dt_max = max(diff(inflow.v))/(1/inflow.input_params.fs); +end + +function new_inflow = calculate_new_inflow_from_sf(inflow, sf) + +new_inflow = inflow; + +deb = 1; [~, fin] = max(inflow.v); % identify systolic upslope +old_deriv = [0, diff(inflow.v(deb:fin))]; +[~,ms] = max(old_deriv); +old_deriv_sum = sum(old_deriv); +% old way +N1 = ms; +N2 = fin-deb+1-N1; +scale_vector = ones(1,N1+N2).*[linspace(1,sf,N1), linspace(sf,1,N2)]; +% % new way +% N1 = ms; +% N2 = round((0.5*(fin-deb))-ms); +% N3 = fin-deb+1-N1-N2; +% scale_vector = ones(1,N1+N2+N3).*[linspace(1,sf,N1), sf*ones(1,N2), linspace(sf,1,N3)]; +% applying scaling to derivative +new_deriv = old_deriv.*scale_vector; + +% to avoid shifting the point of max dQdt: +new_deriv(new_deriv>new_deriv(ms)) = new_deriv(ms); + +new_deriv = old_deriv_sum*new_deriv/sum(new_deriv); +new_inflow.v = [inflow.v(1)+cumsum(new_deriv), inflow.v(fin+1:end)]; + +end + +function Q = Get_parametric_pete(dt, Qi, Qmax, Qmin,Qi2, ti,tmax,tmin,ti2, ts, td, Qi3, ti3) + +%% Find Q1 (systolic uplslope, fourth order) + +t_matrix = [ + 0 0 0 0 1; % Q1(0) = 0 + ti^4 ti^3 ti^2 ti 1; % Q1(ti) = Qi + 4*3*ti^2 3*2*ti 2*1 0 0; % Q1''(ti) = 0 + 4*tmax^3 3*tmax^2 2*tmax 1 0; % Q1'(tmax) = 0 + tmax^4 tmax^3 tmax^2 tmax 1 % Q1(tmax) = Qmax + ]; + +q_matrix = [ + 0; + Qi; + 0; + 0; + Qmax + ]; + +%Solve for coefficients t_matrix*coeffs=q_matrix: coeffs = t_matrix\q_matrix; +Q1_coeffs = t_matrix\q_matrix; + +% %% Find Q2 (systolic downslope, second order) +% +% t_matrix = [ +% tmax^2 tmax 1; % Q2(tmax) = Qmax +% 2*tmax 1 0; % Q2'(tmax) = 0 +% ts^2 ts 1; % Q2(ts) = 0 +% ]; +% +% q_matrix = [ +% Qmax; +% 0; +% 0; +% ]; +% +% %Solve for coefficients t_matrix*coeffs=q_matrix: coeffs = t_matrix\q_matrix; +% Q2_coeffs = t_matrix\q_matrix; +% +% %% Find Q2 (systolic downslope with inflection point, fourth order) +% +% t_matrix = [ +% tmax^4 tmax^3 tmax^2 tmax 1; % Q2(tmax) = Qmax +% 4*tmax^3 3*tmax^2 2*tmax 1 0; % Q2'(tmax) = 0 +% ti2^4 ti2^3 ti2^2 ti2 1; % Q2(ti2) = Qi2 +% 4*3*ti2^2 3*2*ti2 2*1 0 0; % Q2''(ti2) = 0 +% ts^4 ts^3 ts^2 ts 1; % Q2(ts) = 0 +% ]; +% +% q_matrix = [ +% Qmax; +% 0; +% Qi2; +% 0; +% 0; +% ]; +% +% %Solve for coefficients t_matrix*coeffs=q_matrix: coeffs = t_matrix\q_matrix; +% Q2_coeffs = t_matrix\q_matrix; + +%% Find Q2 (systolic downslope with two inflection points, sixth order) + +t_matrix = [ + tmax^6 tmax^5 tmax^4 tmax^3 tmax^2 tmax 1; % Q2(tmax) = Qmax + 6*tmax^5 5*tmax^4 4*tmax^3 3*tmax^2 2*tmax 1 0; % Q2'(tmax) = 0 + ti2^6 ti2^5 ti2^4 ti2^3 ti2^2 ti2 1; % Q2(ti2) = Qi2 + 6*5*ti2^4 5*4*ti2^3 4*3*ti2^2 3*2*ti2 2*1 0 0; % Q2''(ti2) = 0 + ti3^6 ti3^5 ti3^4 ti3^3 ti3^2 ti3 1; % Q2(ti3) = Qi3 + 6*5*ti3^4 5*4*ti3^3 4*3*ti3^2 3*2*ti3 2*1 0 0; % Q2''(ti3) = 0 + ts^6 ts^5 ts^4 ts^3 ts^2 ts 1; % Q2(ts) = 0 + ]; + +q_matrix = [ + Qmax; + 0; + Qi2; + 0; + Qi3; + 0; + 0; + ]; + +%Solve for coefficients t_matrix*coeffs=q_matrix: coeffs = t_matrix\q_matrix; +Q2_coeffs = t_matrix\q_matrix; + +%% Find Q3 (reverse flow, third order) + +%Q2_deriv_ts = 2*Q2_coeffs(1).*ts + Q2_coeffs(2); + +t_matrix = [ + ts^3 ts^2 ts 1; % Q3(ts) = 0 + % 4*ts^3 3*ts^2 2*ts 1 0; % Q3'(ts) = Q2'(ts) + 3*tmin^2 2*tmin 1 0; % Q3'(tmin) = 0 + tmin^3 tmin^2 tmin^1 1; % Q3(tmin) = Qmin + td^3 td^2 td 1; % Q3(td) = 0 + %3*td^2 2*td 1 0; % Q3'(td) = 0 + ]; + +q_matrix = [ + 0; + %Q2_deriv_ts; + 0; + Qmin + 0; + ]; + +%Solve for coefficients t_matrix*coeffs=q_matrix: coeffs = t_matrix\q_matrix; +Q3_coeffs = t_matrix\q_matrix; + +%% Calculate template flow curve + +dt=1e-3; + +% Q1, t1 +t1=[0:dt:tmax]; +Q1 = Q1_coeffs(1).*t1.^4 + Q1_coeffs(2).*t1.^3 + Q1_coeffs(3).*t1.^2 +Q1_coeffs(4).*t1 + Q1_coeffs(5); + +% Q2, t2 +t2=[tmax+dt:dt:ts]; +Q2 = Q2_coeffs(1)*t2.^6 + Q2_coeffs(2)*t2.^5 + Q2_coeffs(3).*t2.^4 + Q2_coeffs(4).*t2.^3 + Q2_coeffs(5).*t2.^2 +Q2_coeffs(6).*t2 + Q2_coeffs(7); +% Q2 = Q2_coeffs(1).*t2.^4 + Q2_coeffs(2).*t2.^3 + Q2_coeffs(3).*t2.^2 +Q2_coeffs(4).*t2 + Q2_coeffs(5); +%Q2 = Q2_coeffs(1).*t2.^2 + Q2_coeffs(2).*t2 + Q2_coeffs(3); + +% Q3, t3 +t3 = [ts+dt:dt:td]; +% Q3 = Q3_coeffs(1).*t3.^4 +Q3_coeffs(2).*t3.^3 + Q3_coeffs(3).*t3.^2 + Q3_coeffs(4).*t3 + Q3_coeffs(5); +Q3 = Q3_coeffs(1).*t3.^3 +Q3_coeffs(2).*t3.^2 + Q3_coeffs(3).*t3 + Q3_coeffs(4); + +% Q4, t4 +t4 = [td+dt:dt:1.0]; +Q4 = t4.*0; + +%% Construct template curve +t = [t1,t2,t3,t4]; +Q = [Q1,Q2,Q3,Q4]; + +end + +function Q = Get_Mynard2015_flow_wave + +fs = 1000; % Hz +% Data provided by Mynard: +Q = [0.975173175413631;0.973779853988154;0.972395614614815;0.970995717731558;0.969511227019400;0.967822711189793;0.965786748864051;0.963283288352364;0.960257180172596;0.956733614590217;0.952804019043309;0.948592861750212;0.944220671600988;0.939775612934077;0.935299487236573;0.930788206519929;0.926202977984071;0.921487672252196;0.916588056259775;0.911469209683415;0.906128003680296;0.900598361098229;0.894948479110418;0.889270767746236;0.883666691560787;0.878229797375804;0.873030633851194;0.868106794857485;0.863460040023719;0.859060747248515;0.854858328407404;0.850795093069735;0.846820567387548;0.842903445940403;0.839039020574192;0.835250902526769;0.831586960403603;0.828110482041099;0.824888470942132;0.821979531423770;0.819423828948797;0.817237101401127;0.815409739068083;0.813910764962756;0.812695446475572;0.811714543871594;0.810923016496613;0.810286366332797;0.809783558074059;0.809406383225149;0.809155982868884;0.809049312351120;0.822723666912791;1.02233385165230;1.96658629314415;4.58560140254054;9.85427558739735;18.3723567331533;30.1314774777907;44.5666042279459;60.7946355212591;77.8878867053600;95.0770252268905;111.846390198646;127.934762788699;143.278424134962;157.935102195756;172.016187493348;185.639837609637;198.905789610112;211.886315485302;224.626247569543;237.146494154128;249.448001830952;261.515308275138;273.320033907046;284.824893763383;295.988445536841;306.770268021839;317.135901678616;327.060806548574;336.532774620005;345.552564122539;354.132876926804;362.296079123497;370.071215649353;377.490884042716;384.588435958977;391.395812923550;397.942143214896;404.253068924458;410.350659695562;416.253710063464;421.978206529741;427.537777920319;432.943995528724;438.206455565240;443.332643996137;448.327642700327;453.193777638760;457.930329008757;462.533418553688;466.996162750017;471.309138243523;475.461155370642;479.440285080944;483.235041551993;486.835593235815;490.234863026527;493.429385478842;496.419814845701;499.211018863089;501.811744031372;504.233891257801;506.491488218617;508.599479649849;510.572474215038;512.423584988732;514.163481563606;515.799739601955;517.336534070953;518.774681411257;520.111998663707;521.343917882841;522.464274200170;523.466176452167;524.342869998804;525.088510984828;525.698787922101;526.171347706221;526.506006380627;526.704747502486;526.771530539299;526.711946609556;526.532768110292;526.241442186613;525.845576190021;525.352457228893;524.768639135078;524.099619940398;523.349622557002;522.521481755218;521.616632378229;520.635187375853;519.576089782668;518.437320238385;517.216140141572;515.909351597176;514.513556936185;513.025401511467;511.441787659971;509.760050567731;507.978090122726;506.094456391599;504.108390059734;502.019820234977;499.829327332228;497.538078870921;495.147747545238;492.660421408567;490.078515604694;487.404693896395;484.641806405646;481.792847669950;478.860936563018;475.849317075378;472.761376647828;469.600676913928;466.370990500281;463.076337047776;459.721011868244;456.309601576609;452.846982508583;449.338299567697;445.788925134535;442.204399603282;438.590356794328;434.952438775355;431.296205409574;427.627044124906;423.950085234953;420.270128045542;416.591580412164;412.918414146340;409.254137683546;405.601785901964;401.963925786966;398.342675776211;394.739736069239;391.156426918743;387.593731908661;384.052343427062;380.532707909337;377.035068903213;373.559506534790;370.105972482048;366.674320045660;363.264329314927;359.875727739749;356.508206630724;353.161434222293;349.835065959949;346.528752629132;343.242146850871;339.974908347998;336.726708255579;333.497232626731;330.286185183115;327.093289287159;323.918289074735;320.760949682792;317.621056533014;314.498413683235;311.392841324680;308.304172575322;305.232249788152;302.176920648979;299.138034374586;296.115438333779;293.108975399232;290.118482297792;287.143789164435;284.184720425785;281.241097063450;278.312740302484;275.399476098279;272.501140627695;269.617586923616;266.748691925274;263.894363582487;261.054547078738;258.229230595293;255.418450710163;252.622296983934;249.840915478514;247.074511117000;244.323348894336;241.587754005714;238.868110988727;236.164861986677;233.478504240701;230.809586911346;228.158707317984;225.526506668447;222.913665332752;220.320897695917;217.748946607613;215.198577433230;212.670571703443;210.165720358625;207.684816590472;205.228648295138;202.797990168838;200.393595496125;198.016187701204;195.666451751727;193.345025520643;191.052491223716;188.789367057162;186.556099160881;184.353054028231;182.180511473288;180.038658252078;177.927582416260;175.847268457468;173.797593279242;171.778323012440;169.789110670159;167.829494620601;165.898897841200;163.996627905452;162.121877644825;160.273726422047;158.451141948429;156.652982576222;154.877999996753;153.124842275710;151.392057157989;149.678095575415;147.981315291308;146.299984616011;144.632286127094;142.976320327190;141.330109171368;139.691599394906;138.058665571552;136.429112832201;134.800679174373;133.171037294589;131.537795878214;129.898500285375;128.250629578665;126.591552056964;124.918513546968;123.228701286997;121.519279660594;119.787396713776;118.030173344769;116.244685038415;114.427943132719;112.576879319406;110.688334247474;108.759049349989;106.785660427503;104.764691739498;102.692549897179;100.565517355309;98.3797456114618;96.1312483447445;93.8158947430382;91.4294032575011;88.9673360283976;86.4250942542448;83.7979148138351;81.0808684833106;78.2688601109401;75.3566311223238;72.3387647348645;69.2096942693344;65.9637149614027;62.5949996961145;59.0976191088091;55.4655665094076;51.6927880876767;47.7732188551761;43.7008247436815;39.4696510842022;35.0738773265343;30.5078774208866;25.7662847630790;20.8440598589074;15.7365576638450;10.4395896586277;4.94948395886629;-0.735422487056177;-6.61006110317804;-12.6622828791241;-18.8741551014073;-25.2223446279507;-31.6774795652257;-38.2025309338117;-44.7503098863757;-51.2601554986592;-57.6538083796666;-63.8303716876630;-69.6602108183708;-74.9777007689949;-79.5729897866242;-83.1835808216337;-85.4878655563827;-86.1053603202930;-84.6131464119407;-80.5954995994022;-73.7514724136509;-64.0798633763130;-52.1091746662620;-39.0192868202663;-26.4236251384105;-15.7941270663738;-7.91285846891109;-2.74469604605859;0.293602435264025;1.98007377814065;2.92205567366193;3.49397045416749;3.89008117479282;4.14089208439632;4.20614627486643;4.04493717059770;3.65230704785446;3.06654618725146;2.35815282267805;1.61164891584995;0.908193676387704;0.312993750191313;-0.131483838549379;-0.407114525746058;-0.517743427869374;-0.484134357520946;-0.337500761404327;-0.112833084082376;0.156872389987909;0.444636538227652;0.731345027437622;1.00549206445160;1.26133764803882;1.49627099108680;1.70822087230301;1.89379163630702;2.04750482337735;2.16218836931823;2.23026692820176;2.24552638787934;2.20487245926461;2.10966251151507;1.96632527713331;1.78615156071780;1.58430251438172;1.37821353006803;1.18565666114217;1.02275857288413;0.902257504376651;0.832227903567992;0.815419325838948;0.849258943000078;0.926471019680050;1.03618649105827;1.16536244555750;1.30031059679785;1.42814387876862;1.53798635774857;1.62184185248123;1.67507168268247;1.69648274308898;1.68806788064185;1.65446889571512;1.60224849115926;1.53906274445581;1.47282227801065;1.41092024226895;1.35959019164763;1.32343840995741;1.30517473525675;1.30554512513065;1.32344993220714;1.35621592404900;1.39997894562081;1.45012864222408;1.50176691865472;1.55013711262050;1.59098990128905;1.62086310064297;1.63726410106609;1.63875430171567;1.62494357247146;1.59640897161454;1.55455559570685;1.50143877623741;1.43956630142906;1.37169744439211;1.30065285302460;1.22914600799649;1.15964393278636;1.09426168755604;1.03469201194843;0.982169473485648;0.937466421126849;0.900916576754242;0.872461092336484;0.851711324911019;0.838022391974301;0.830571715975153;0.828437194426511;0.830670286624854;0.836360134370805;0.844685779213896;0.854954550765467;0.866625729579164;0.879319585335726;0.892812809676451;0.907022159158339;0.921978757821491;0.937795948512687;0.954633805326337;0.972663416953261;0.992033828224525;1.01284410678493;1.03512242076436;1.05881332183346;1.08377368490528;1.10977702323459;1.13652523530348;1.16366629882222;1.19081604552159;1.21758195002861;1.24358685111199;1.26849068155330;1.29200857560822;1.31392414863640;1.33409737863406;1.35246646033510;1.36904423843737;1.38390978338493;1.39719607347560;1.40907499283471;1.41974096642944;1.42939455153875;1.43822720054384;1.44640822057111;1.45407470397354;1.46132491496614;1.46821531763466;1.47476114298754;1.48094013869504;1.48669894093813;1.49196136425231;1.49663782766939;1.50063512319714;1.50386578038738;1.50625637879319;1.50775429615074;1.50833254006601;1.50799248071200;1.50676446792542;1.50470646655165;1.50190096972003;1.49845054448812;1.49447242448339;1.49009258936109;1.48543976285306;1.48063972419857;1.47581026734594;1.47105706521158;1.46647060968185;1.46212430881871;1.45807373738226;1.45435696080351;1.45099579024122;1.44799778032830;1.44535875286724;1.44306561926812;1.44109928056824;1.43943740433552;1.43805690958957;1.43693603064433;1.43605587501926;1.43540143560977;1.43496206010104;1.43473141839304;1.43470703956439;1.43488951227804;1.43528145584444;1.43588637346798;1.43670749517974;1.43774670667983;1.43900364339042;1.44047500816853;1.44215414823655;1.44403090376470;1.44609171884197;1.44831998672798;1.45069658631969;1.45320055643842;1.45580984905350;1.45850210192629;1.46125537497052;1.46404880206793;1.46686312043640;1.46968105181609;1.47248752262826;1.47526972300285;1.47801701615651;1.48072071934780;1.48337378498477;1.48597041509377;1.48850564418889;1.49097492473993;1.49337374632552;1.49569731442067;1.49794030833073;1.50009673043004;1.50215985127527;1.50412224791871;1.50597592630257;1.50771251338018;1.50932350081571;1.51080051987820;1.51213562656644;1.51332157683547;1.51435207395019;1.51522197314722;1.51592743274461;1.51646600506683;1.51683666492955;1.51703977759086;1.51707701165433;1.51695120544616;1.51666619753251;1.51622663328266;1.51563775984886;1.51490522148164;1.51403486597555;1.51303257136306;1.51190409986457;1.51065498366048;1.50929044472432;1.50781534874546;1.50623419114788;1.50455111150159;1.50276993125144;1.50089420884152;1.49892730597802;1.49687245884812;1.49473284859790;1.49251166618081;1.49021216766126;1.48783771724494;1.48539181653539;1.48287811963546;1.48030043462400;1.47766271257347;1.47496902595788;1.47222353890944;1.46943047221929;1.46659406611873;1.46371854366174;1.46080807705649;1.45786675868910;1.45489857791480;1.45190740409148;1.44889697580608;1.44587089572787;1.44283263024876;1.43978551276761;1.43673274933238;1.43367742530605;1.43062251176056;1.42757087045167;1.42452525641417;1.42148831753469;1.41846259070050;1.41545049448519;1.41245431861558;1.40947621072178;1.40651816109149;1.40358198630023;1.40066931265464;1.39778156042536;1.39491992977262;1.39208538917569;1.38927866693981;1.38650024618245;1.38375036357629;1.38102901198697;1.37833594693885;1.37567069659738;1.37303257478828;1.37042069645756;1.36783399494897;1.36527124044948;1.36273105902113;1.36021195164343;1.35771231280773;1.35523044825332;1.35276459156949;1.35031291945742;1.34787356556832;1.34544463293838;1.34302420511081;1.34061036425278;1.33820123324222;1.33579484431388;1.33338926016340;1.33098259456667;1.32857300400822;1.32615867997684;1.32373784447988;1.32130875074699;1.31886969005915;1.31641900407923;1.31395510053223;1.31147646950788;1.30898169807164;1.30646948191180;1.30393863372965;1.30138808866182;1.29881690734648;1.29622427726826;1.29360951296356;1.29097205556370;1.28831147197233;1.28562745386192;1.28291981639856;1.28018849649590;1.27743355035738;1.27465515011932;1.27185357956203;1.26902922899795;1.26618258951974;1.26331424686165;1.26042487506438;1.25751523010908;1.25458614360014;1.25163851651538;1.24867331300571;1.24569155419815;1.24269431200759;1.23968270293181;1.23665788186434;1.23362103596021;1.23057337859285;1.22751614349328;1.22445057906192;1.22137794288460;1.21829949650900;1.21521650054114;1.21213021004095;1.20904187013147;1.20595271174608;1.20286394751884;1.19977676786138;1.19669233729080;1.19361179106446;1.19053623215835;1.18746672858958;1.18440431111538;1.18134997126825;1.17830465973955;1.17526928511395;1.17224471292174;1.16923176504156;1.16623121941054;1.16324381003570;1.16027022726762;1.15731111829750;1.15436708785409;1.15143869904904;1.14852647435796;1.14563089670433;1.14275241057533;1.13989142319184;1.13704830578597;1.13422339494885;1.13141699401049;1.12862937441509;1.12586077710418;1.12311141392642;1.12038146909308;1.11767110067176;1.11498044212579;1.11230960387566;1.10965867487975;1.10702772420934;1.10441680261584;1.10182594408854;1.09925516737407;1.09670447746561;1.09417386703982;1.09166331783351;1.08917280196709;1.08670228318944;1.08425171804785;1.08182105698174;1.07941024532497;1.07701922423083;1.07464793150520;1.07229630237125;1.06996427014828;1.06765176686126;1.06535872378557;1.06308507192919;1.06083074245840;1.05859566706718;1.05637977831226;1.05418300991596;1.05200529703488;1.04984657649583;1.04770678698755;1.04558586922764;1.04348376609723;1.04140042277914;1.03933578708579;1.03728981028786;1.03526244848414;1.03325366392776;1.03126342537163;1.02929170672478;1.02733848406693;1.02540373170865;1.02348741823828;1.02158950339000;1.01970993615314;1.01784865411397;1.01600558373497;1.01418064114576;1.01237373309989;1.01058475778510;1.00881360530218;1.00706015770754;1.00532428865248;1.00360586280348;1.00190473526114;1.00022075127348;0.998553746415667;0.996903547212885;0.995269972068214;0.993652832340103;0.992051933470198;0.990467076131119;0.988898057416265;0.987344672099656;0.985806714003158;0.984283977483060;0.982776259028291;0.981283358940195;0.979805083034552;0.978341244292943;0.976891664388993;0.975456175004534;0.974034618864419;0.972626849924471;0.971232531803553;0.969847314708597;0.968446559622980;0.966961576526169;0.965273284904924;0.963238556143108;0.960737398614335;0.957714424958803;0.954194370546731;0.950268164283976;0.946059908881930;0.941690011856661;0.937246781822003;0.932772374536440;0.928263160351216;0.923680796836290;0.918969481829967;0.914075101004032;0.908962603132715;0.903628497931898;0.898106190788554;0.892463314366207;0.886791786457542;0.881192755742685;0.875759694103406;0.870563324949767;0.865641617188617;0.860996810907333;0.856599753215754;0.852400202939444;0.848340613182712;0.844370414994066;0.840457985701078;0.836598141523446;0.832813957473801;0.829152817129408;0.825677676834808;0.822455432486473;0.819544826720973;0.816986377513701;0.814796311551718;0.812965539338525;0.811463529533424;0.810245838926853;0.809263321669889;0.808470844851686;0.807833683488993;0.807330517386983;0.806952875718220;0.806701723506212;0.806589307442645;0.818727985867816;1.00588741144649;1.91128708796076;4.45410595443429;9.61193334647688;18.0006459823640;29.6332314140555;43.9622690940319;60.1137754534786;77.1605569936956;94.3277825133242;111.091698659148;127.183197017379;142.532489199134;157.193532957161;171.275966787995;184.897608484247;198.158660509707;211.132219432564;223.864044632443;236.375957796940;248.669758908944;260.730746615467;272.531165797111;284.034165391563;295.198499111895;305.983681531697;316.354941940750]; +Q(1:52) = 0; +Q(362:end) = 0; +Q = [Q(53:end); Q(1:52)]; + +Q = Q(:)'; +end + +function Qtot_old = Get_parametric_old(dt, Qi, Qmax, Qmin,Qi2, ti,tmax,tmin,ti2, ts, td) + + +%% Q2 = fourth order (for old wave); no horizontal slope at t=0 + +% 15 unknowns +old_LHS_O = [ + % First polynomial curve, Q1 (systolic upslope) + tmax^4 tmax^3 tmax^2 tmax^1 1 0 0 0 0 0 0 0 0 0 0; %Q1(tmax) = Qmax + 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0; %Q1(0) = 0 + 4*tmax^3 3*tmax^2 2*tmax^1 1 0 0 0 0 0 0 0 0 0 0 0; %Q1'(tmax) = 0 + 4*3*ti^2 3*2*ti 2 0 0 0 0 0 0 0 0 0 0 0 0; %Q1''(ti) = 0 + ti^4 ti^3 ti^2 ti 1 0 0 0 0 0 0 0 0 0 0; %Q1(ti) = Qi + % Second polynomial curve, Q2 (systolic downslope) + 0 0 0 0 0 tmax^4 tmax^3 tmax^2 tmax 1 0 0 0 0 0; %Q2(tmax) = Qmax + 0 0 0 0 0 4*tmax^3 3*tmax^2 2*tmax 1 0 0 0 0 0 0; %Q2'(tmax) = 0 + 0 0 0 0 0 ti2^4 ti2^3 ti2^2 ti2 1 0 0 0 0 0; %Q2(ti2) = Qi2 + 0 0 0 0 0 4*3*ti2^2 3*2*ti2 2 0 0 0 0 0 0 0; %Q2'(tmax) = 0 + + 0 0 0 0 0 ts^4 ts^3 ts^2 ts 1 -ts^4 -ts^3 -ts^2 -ts -1; %Q2(ts) = Q3(ts) + 0 0 0 0 0 4*ts^3 3*ts^2 2*ts 1 0 -4*ts^3 -3*ts^2 -2*ts -1 0; %Q2'(ts) = Q3'(ts) + 0 0 0 0 0 0 0 0 0 0 td^4 td^3 td^2 td 1; %Q3(td) = 0 + 0 0 0 0 0 0 0 0 0 0 4*td^3 3*td^2 2*td 1 0; %Q3'(td) = 0 + 0 0 0 0 0 0 0 0 0 0 tmin^4 tmin^3 tmin^2 tmin 1; %Q3(tmin) = Qmin + 0 0 0 0 0 0 0 0 0 0 4*tmin^3 3*tmin^2 2*tmin 1 0 %Q3'(tmin) = 0 + ]; + +%RHS +old_RHS_O = [ + Qmax; + 0; + 0; + 0; + Qi; + Qmax; + 0; + Qi2; + 0; + 0; + 0; + 0; + 0; + Qmin; + 0 +]; + +% Pete's editing + +% 15 unknowns +LHS_O = [ + % First polynomial curve, Q1 (systolic upslope) - fourth order polynomial + tmax^4 tmax^3 tmax^2 tmax^1 1 0 0 0 0 0 0 0 0 0 0; %Q1(tmax) = Qmax + 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0; %Q1(0) = 0 + 4*tmax^3 3*tmax^2 2*tmax^1 1 0 0 0 0 0 0 0 0 0 0 0; %Q1'(tmax) = 0 + 4*3*ti^2 3*2*ti 2 0 0 0 0 0 0 0 0 0 0 0 0; %Q1''(ti) = 0 + ti^4 ti^3 ti^2 ti 1 0 0 0 0 0 0 0 0 0 0; %Q1(ti) = Qi + % Second polynomial curve, Q2 (systolic downslope) - fourth order polynomial + 0 0 0 0 0 tmax^4 tmax^3 tmax^2 tmax 1 0 0 0 0 0; %Q2(tmax) = Qmax + 0 0 0 0 0 4*tmax^3 3*tmax^2 2*tmax 1 0 0 0 0 0 0; %Q2'(tmax) = 0 + 0 0 0 0 0 ti2^4 ti2^3 ti2^2 ti2 1 0 0 0 0 0; %Q2(ti2) = Qi2 + 0 0 0 0 0 4*3*ti2^2 3*2*ti2 2 0 0 0 0 0 0 0; %Q2''(ti2) = 0 + 0 0 0 0 0 ts^4 ts^3 ts^2 ts 1 -ts^4 -ts^3 -ts^2 -ts -1; %Q2(ts) = 0 % Changed: used to be Q2(ts) = Q3(ts) + % Second and third polynomial curves + 0 0 0 0 0 5*ts^4 4*ts^3 3*ts^2 2*ts 1 -4*ts^3 -3*ts^2 -2*ts -1 0; %Q2'(ts) - Q3'(ts) = 0 + % Third polynomial curve, Q3 (reverse flow) - fifth order polynomial + 0 0 0 0 0 0 0 0 0 0 ts^4 ts^3 ts^2 ts 1; %Q3(ts) = 0 % Added + 0 0 0 0 0 0 0 0 0 0 td^4 td^3 td^2 td 1; %Q3(td) = 0 + % 0 0 0 0 0 0 0 0 0 0 4*td^3 3*td^2 2*td 1 0; %Q3'(td) = 0 + 0 0 0 0 0 0 0 0 0 0 tmin^4 tmin^3 tmin^2 tmin 1; %Q3(tmin) = Qmin + 0 0 0 0 0 0 0 0 0 0 4*tmin^3 3*tmin^2 2*tmin 1 0 %Q3'(tmin) = 0 + ]; + +%RHS +RHS_O = [ + Qmax; + 0; + 0; + 0; + Qi; + Qmax; + 0; + Qi2; + 0; + 0; + 0; + 0; + 0; + Qmin; + 0 +]; + +%Solve system A*X=B: x = A\B; +clear X; +X = old_LHS_O\old_RHS_O; + + +%% Equation of flow curve solution - OLD +dt=1e-3; +%Q1, t1 +t1=[0:dt:tmax]; +Q1 = X(1).*t1.^4 + X(2).*t1.^3 + X(3).*t1.^2 +X(4).*t1 + X(5); + +%Q2,t2 +t2=[tmax+dt:dt:ts]; +% old +% Q2 = X(6).*t2.^4 + X(7).*t2.^3 + X(8).*t2.^2 + X(9).*t2 + X(10); +% new +Q2 = X(6).*t2.^4 + X(7).*t2.^3 + X(8).*t2.^2 + X(9).*t2 + X(10); + +%Q3,t3 +t3 = [ts+dt:dt:td]; +% old +% Q3 = X(11).*t3.^4 + X(12).*t3.^3 + X(13).*t3.^2 + X(14).*t3 + X(15); +Q3 = X(11).*t3.^4 + X(12).*t3.^3 + X(13).*t3.^2 + X(14).*t3 + X(15); + +%Q4, t4 +t4 = [td+dt:dt:1.0]; +Q4 = t4.*0; + +Qtot_old = [Q1, Q2, Q3, Q4]; + +end + +function Qtot_young = Get_parametric_young(dt, Qi, Qmax, Qmin, ti,tmax,tmin, ts, td) + + +%% Q2:second order, no horizontal slope = 0 at t=0 - YOUNG wave + +% [P14 P13 P12 P11 P10 P22 P21 P20 P34 P33 P32 P31 P30] +LHS_Y = [ + tmax^4 tmax^3 tmax^2 tmax^1 1 0 0 0 0 0 0 0 0; %Q1(tmax) = Qmax + 0 0 0 0 1 0 0 0 0 0 0 0 0; %Q1(0) = 0 +% 0 0 0 1 0 0 0 0 0 0 0 0 0; %Q1'(0) = 0 + 4*tmax^3 3*tmax^2 2*tmax^1 1 0 0 0 0 0 0 0 0 0; %Q1'(tmax) = 0 + 4*3*ti^2 3*2*ti 2 0 0 0 0 0 0 0 0 0 0; %Q1''(ti) =0 + ti^4 ti^3 ti^2 ti 1 0 0 0 0 0 0 0 0; %Q1(ti) = Qi + 0 0 0 0 0 tmax^2 tmax 1 0 0 0 0 0; %Q2(tmax)=Qmax + 0 0 0 0 0 2*tmax 1 0 0 0 0 0 0; %Q2'(tmax)=0 + 0 0 0 0 0 ts^2 ts 1 -ts^4 -ts^3 -ts^2 -ts -1; %Q2(ts)=Q3(ts) + 0 0 0 0 0 2*ts 1 0 -4*ts^3 -3*ts^2 -2*ts -1 0; %Q2'(ts)=Q3'(ts) + 0 0 0 0 0 0 0 0 td^4 td^3 td^2 td 1; %Q3(td) = 0 + 0 0 0 0 0 0 0 0 4*td^3 3*td^2 2*td 1 0; %Q3'(td)=0 + 0 0 0 0 0 0 0 0 tmin^4 tmin^3 tmin^2 tmin 1; %Q3(tmin) = Qmin + 0 0 0 0 0 0 0 0 4*tmin^3 3*tmin^2 2*tmin 1 0 %Q3'(tmin) = 0 + ]; + +%RHS +RHS_Y = [ + Qmax; + 0; +% 0; %Q1'(0) = 0 + 0; + 0; + Qi; + Qmax; + 0; + 0; + 0; + 0; + 0; + Qmin; + 0 +]; + +%Solve system A*X=B: x = A\B; +X = LHS_Y\RHS_Y; + +%% Equation of flow curve solution - YOUNG +%Q1, t1 +t1=[0:dt:tmax]; +Q1 = X(1).*t1.^4 + X(2).*t1.^3 + X(3).*t1.^2 +X(4).*t1 + X(5); + +%Q2,t2 +t2=[tmax+dt:dt:ts]; +Q2 = X(6).*t2.^2 + X(7).*t2 + X(8); + +%Q3,t3 +t3 = [ts+dt:dt:td]; +Q3 = X(9).*t3.^4 + X(10).*t3.^3 + X(11).*t3.^2 + X(12).*t3 + X(13); + +%Q4, t4 +t4 = [td+dt:dt:1.0]; +Q4 = t4.*0; + +Qtot_young = [Q1, Q2, Q3, Q4]; + +end + +function inflow = adjust_sampling_frequency(inflow) + +old_t = inflow.t; +inflow.t = 0:(1/inflow.input_params.fs):inflow.t(end); +inflow.v = interp1(old_t, inflow.v, inflow.t); + +end + +function inflow = calc_characteristics_inflow_wave(inflow) + +% NB: inflow.v is in m3 per sec + +% Sampling freq (Hz) +chars.fs = inflow.input_params.fs; + +% Duration of cardiac cycle (secs) +chars.T = (length(inflow.t)-1)/inflow.input_params.fs; + +% Heart rate (bpm) +chars.HR = 60/chars.T; + +% Stoke volume (in ml) +chars.SV = sum(inflow.v)*(1/chars.fs)*1000*1000; + +% Cardiac output (in l/min) +chars.CO = chars.HR*chars.SV/1000; + +% LVET (in ms) +end_systole_el = find(inflow.v(1:end-1)>0 & inflow.v(2:end) <=0, 1); +chars.LVET = inflow.t(end_systole_el); + +% Forward volume (in ml) +chars.vol_forward = sum(inflow.v(inflow.v>0))*(1/chars.fs)*1000*1000; + +% Regurgitation Volume +chars.Reg_Vol = abs(sum(inflow.v(inflow.v<0)))*(1/chars.fs)*1000*1000; + +% Proportion regurgitation (%) +chars.perc_reg = 100*chars.Reg_Vol/chars.vol_forward; + +% Measure of contractility +[chars.max_dq_dt, max_contr_el] = max(diff(inflow.v(1:end_systole_el))); +chars.max_dq_dt = chars.max_dq_dt/(1/inflow.input_params.fs); + +% Maximum flow rate +chars.Qmax = max(inflow.v); + +% Additional timings: +% - Time of systolic peak +[~, sys_peak_el] = max(inflow.v); +chars.T_Peak_Flow = inflow.t(sys_peak_el); +% - Time of max regurgitation +[max_reg, max_reg_el] = min(inflow.v); +if max_reg < 0 + chars.T_Min_Flow = inflow.t(max_reg_el); +else + chars.T_Min_Flow = nan; +end +% - Time of end of regurgitation +if max_reg < 0 + end_reg_el = find(inflow.v(1:end-1)<0 & inflow.v(2:end) ==0, 1); + chars.T_dia = inflow.t(end_reg_el); +else + chars.T_dia = nan; +end +% - Time of max gradient of systolic upslope +chars.T_max_contr = inflow.t(max_contr_el); + +inflow.chars = orderfields(chars); + +end + +function plot_figures(inflow) + +% plot figure if requested +if inflow.input_settings.do_plot + + paper_size = [900 600]; + + % Final inflow waveform in ml/s + fig_handles = findobj('Type', 'figure'); + if ~inflow.input_settings.plot_multiple || isempty(fig_handles) + figure('Position',[600 400 paper_size]) + end + clear figHandles + set(gca,'fontsize',28) + hold on + plot([inflow.t(1), inflow.t(end)], [0,0], '--', 'Color', 0.2*ones(1,3)); + plot(inflow.t,inflow.v*1e6,'k','linewidth',2); + plot(inflow.t(end),inflow.v(end)*1e6,'ok','linewidth',2); + ylabel('Q (ml/s)') + xlabel('time (s)') + + %- adjust color if multiple plots + if inflow.input_settings.plot_multiple + h_lines = findall(gcf, 'Type', 'line'); + color_range = [0,0.75]; + if length(h_lines) > 1 + rel_colors = linspace(color_range(1), color_range(2), length(h_lines)); + for s = 1 : length(h_lines) + h_lines(s).Color = rel_colors(s)*[1,1,1]; + end + end + end + + if inflow.input_settings.save_plot + save_plot(gcf, paper_size, inflow.input_settings.plot_name, inflow.input_settings.file_path) + end + +end + +end + +function save_plot(h_fig, paper_size, filename, filepath) + +savepath = [filepath, filename]; +set(gcf,'color','w'); +set(gcf,'PaperUnits','centimeters'); +set(gcf,'PaperSize', [paper_size(1), paper_size(2)]./40); +set(gcf,'PaperPosition',[0 0 paper_size(1) paper_size(2)]./40); +print(gcf,'-dpdf',savepath) +print(gcf,'-dpng',savepath) + +end +","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/Additional Functions/PulseAnalyse10.m",".m","94443","2749","function [cv_inds, fid_pts, pulses, sigs] = PulseAnalyse10(S, options) +% PULSEANALYSE Extracts cardiovascular (CV) indices from pulse waves. +% +% Inputs: +% +% S - a pulsatile signal, consisting of either a signal pulse, or a +% signal containing several pulses. S should be a structure, containing +% a vector of amplitudes, S.v, and the sampling frequency (in Hz), S.fs, +% and optionally the subject's height in metres, S.ht. +% options - (optional) a structure of options, which may contain any of: +% options.exclude_low_quality_data - a logical (true or false) +% options.do_plot - a logical (true or false) +% +% Outputs: +% +% cv_inds - a structure containing the calculate cardiovascular +% indices. For instance, cv_inds.AI.v is the value of the +% augmentation index (AI). If the input S contains +% several pulses, then cv_inds.AI.v is the median AI +% value, and cv_inds.AI.raw is a vector of raw values for +% each pulse. +% fid_pts - a structure containing the indices of the fiducial points. +% For instance, fid_pts.dic provides the indices of the +% dicrotic notch(es). +% pulses - a structure containing information on the pulses: +% pulses.peaks - the indices of systolic peaks +% pulses.onsets - the indices of pulse onsets (i.e. beginning of systole) +% pulses.quality - a logical indicating the signal quality of each pulse (true indicates high quality) +% S_filt - the filtered pulsatile signal to which the ""fid_pts"" and +% ""pulses"" indices correspond. +% +% Exemplary usage: +% +% cv_inds = PulseAnalyse(S) extracts CV indices from the pulsatile signal, S. +% cv_inds = PulseAnalyse(S, options) uses options to specify the analysis. +% [cv_inds, fid_pts, pulses, S_filt] = PulseAnalyse(___) also outputs fiducial points, pulse locations, and the filtered signal. +% +% For further information please see the accompanying manual. +% +% This script contains items either copied or modified from the RRest +% toolbox which is covered by the GNU public licence (link). +% +% Peter H. Charlton, King's College London, August 2017 + +%% Setup + +% Setup options +if nargin < 2 + options = struct; +end +options = setup_options(options); + +% Setup universal parameters +up = setup_up(options); + +% Determine whether this is a single pulse, or several pulses +no_of_pulses = determine_no_of_pulses(S, up); + +% Make amplitudes into a column vector +S.v = S.v(:); + +if sum(strcmp(fieldnames(S), 'ht')) + ht = S.ht; +end + +%% Pre-processing + +% Pre-processing is peformed according to whether this is a single pulse or multiple pulses. +switch no_of_pulses + + case 'multiple' + + % Eliminate very low frequency content + if options.do_filter + try + S_evlf = elim_vlfs(S, up); + catch + S_evlf = S; + fprintf('Signal too short to eliminate very low frequencies\n') + end + + % Eliminate very high frequency content + S_filt = elim_vhfs(S_evlf, up); + else + S_filt = S; + end + + % Identify individual pulse waves + [pulses.peaks, pulses.onsets, ~] = adaptPulseSegment(S_filt.v,S.fs); + + % Assess signal quality + pulses.quality = assess_signal_quality(S_filt, pulses.peaks); + + case 'single' + + if options.do_filter + % Eliminate high frequency content + S_evhf = elim_vhfs2(S, up); + + % Eliminate low frequency content + S_elim_lf = eliminate_low_freq_from_single_beat(S_evhf, up); + else + S_elim_lf = S; + end + + % Ensure that signal commences at start of systole + S_filt = align_pulse(S_elim_lf, up); + S = align_pulse(S, up); + + % Generate ""pulses"" information + pulses = generate_pulses_for_single_beat(S_filt); + +end + +%% Calculate derivatives + +sigs = calc_derivs2(S, S_filt, no_of_pulses, up); +% derivs = calc_derivs(S_filt, no_of_pulses, up); + +%% Identify fiducial points + +if exist('ht', 'var') + sigs.ht = ht; +end + +if ~options.annotate + try + % Find fiducial points + fid_pts = identify_fiducial_pts(sigs, pulses.onsets, up, no_of_pulses, options); + catch + fprintf('\n Couldn''t identify fiducial points') + + [fid_pts.a, fid_pts.b, fid_pts.c, fid_pts.d, fid_pts.e, fid_pts.f, fid_pts.p1pk, fid_pts.p2pk, fid_pts.p1in, fid_pts.t2t, fid_pts.s, fid_pts.dic, fid_pts.dia, fid_pts.ms] = deal(nan(length(pulses.onsets)-1,1)); + fid_pts.f1 = pulses.onsets(1:end-1); + fid_pts.f2 = pulses.onsets(2:end); + end +else + % Annotate fiducial points + fid_pts = annotate_fiducial_pts(S_filt, pulses.onsets, derivs, up, no_of_pulses); +end + +%% Calculate CV indices + +cv_inds = calc_stiffness_inds(sigs, pulses, fid_pts, options); + +%% Plot the fiducial points +if options.do_plot + plot_fiducial_points(sigs, pulses, fid_pts, no_of_pulses, options) + plot_cv_inds(sigs, pulses, fid_pts, cv_inds, no_of_pulses, options) +end + +%% Make a demo plot +if options.do_demo_plot + make_demo_plot(S_filt, derivs, pulses, fid_pts, cv_inds, no_of_pulses, options) +end + +end + +function options = setup_options(options) + +if isempty(fieldnames(options)) | ~strcmp(fieldnames(options), 'do_plot') + options.do_plot = 1; +end + +if ~strcmp(fieldnames(options), 'exclude_low_quality_data') + options.exclude_low_quality_data = 1; +end +if ~strcmp(fieldnames(options), 'do_plot') + options.do_plot = 1; +end +if ~strcmp(fieldnames(options), 'plot_third_deriv') + options.plot_third_deriv = 1; +end +if ~strcmp(fieldnames(options), 'annotate') + options.annotate = 0; +end +if ~strcmp(fieldnames(options), 'manual_adjustment') + options.manual_adjustment = 0; +end +if ~strcmp(fieldnames(options), 'close_figures') + options.close_figures = 1; +end +if ~strcmp(fieldnames(options), 'do_filter') + options.do_filter = 1; +end +if ~strcmp(fieldnames(options), 'save_folder') + options.save_folder = ''; +end +if ~strcmp(fieldnames(options), 'save_file') + options.save_file = ''; +end +if ~strcmp(fieldnames(options), 'do_demo_plot') + options.do_demo_plot = 0; +end +if ~strcmp(fieldnames(options), 'demo_plot_wave') + options.demo_plot_wave = 'orig'; +end + +if options.do_demo_plot + options.do_plot = 0; +end + +end + +function up = setup_up(options) + +if options.close_figures + close all +end + +%% Analysis settings + +% Threshold signal duration to distinguish between a single pulse or multiple pulses: +up.analysis.max_duration_of_single_pulse = 2.5; % in secs + +% Filter characteristics: Eliminate VLFs (below resp freqs): For 4bpm cutoff +up.paramSet.elim_vlf.Fpass = 0.157; % in Hz +up.paramSet.elim_vlf.Fstop = 0.02; % in Hz (0.157 and 0.02 provide a - 3dB cutoff of 0.0665 Hz) +up.paramSet.elim_vlf.Dpass = 0.05; +up.paramSet.elim_vlf.Dstop = 0.01; + +% Filter characteristics: Eliminate VHFs (above frequency content of signals) +% up.paramSet.elim_vhf.Fpass = 38.5; % in HZ +% up.paramSet.elim_vhf.Fstop = 33.12; % in HZ (33.12 and 38.5 provide a -3 dB cutoff of 35 Hz) +up.paramSet.elim_vhf.Fpass = 20; % in HZ +up.paramSet.elim_vhf.Fstop = 15; % in HZ +up.paramSet.elim_vhf.Dpass = 0.05; +up.paramSet.elim_vhf.Dstop = 0.01; + +% No of times to repeat a single pulse to perform VHF filtering +up.paramSet.no_pulse_repeats = 5; + +end + +function no_of_pulses = determine_no_of_pulses(S, up) +% DETERMINE_NO_OF_PULSES Determines whether this is a single pulse wave, +% of a pulsatile signal containing multiple pulse waves. + +signal_duration = (length(S.v)-1)/S.fs; + +% If duration of signal is greater than a threshold then assume this is +% multiple pulse waves: +if signal_duration > up.analysis.max_duration_of_single_pulse + no_of_pulses = 'multiple'; +else + no_of_pulses = 'single'; +end + +end + +function s_filt = elim_vlfs(s, up) +%% Filter pre-processed signal to remove frequencies below resp +% Adapted from RRest + +%% Eliminate nans +s.v(isnan(s.v)) = mean(s.v(~isnan(s.v))); + +%% Make filter +flag = 'scale'; +[N,Wn,BETA,TYPE] = kaiserord([up.paramSet.elim_vlf.Fstop up.paramSet.elim_vlf.Fpass]/(s.fs/2), [1 0], [up.paramSet.elim_vlf.Dstop up.paramSet.elim_vlf.Dpass]); +b = fir1(N, Wn, TYPE, kaiser(N+1, BETA), flag); +AMfilter = dfilt.dffir(b); + +%% Check frequency response +% % Gives a -3 dB cutoff at ? Hz, using: +% freqz(AMfilter.Numerator) +% norm_cutoff_freq = 0.0266; % insert freq here from plot +% cutoff_freq = norm_cutoff_freq*(fs/2); + +s_filt.v = filtfilt(AMfilter.numerator, 1, s.v); +s_filt.v = s.v-s_filt.v; +s_filt.fs = s.fs; +end + +function s_filt = elim_vhfs(s, up) +%% Filter signal to remove VHFs +% Adapted from RRest + +s_filt.fs = s.fs; + +%% Eliminate nans +s.v(isnan(s.v)) = mean(s.v(~isnan(s.v))); + +%% Check to see if sampling freq is at least twice the freq of interest +if (up.paramSet.elim_vhf.Fpass/(s.fs/2)) >= 1 + % then the fs is too low to perform this filtering + s_filt.v = s.v; + return +end + +%% Create filter +% parameters for the low-pass filter to be used +flag = 'scale'; +[N,Wn,BETA,TYPE] = kaiserord([up.paramSet.elim_vhf.Fstop up.paramSet.elim_vhf.Fpass]/(s.fs/2), [1 0], [up.paramSet.elim_vhf.Dstop up.paramSet.elim_vhf.Dpass]); +b = fir1(N, Wn, TYPE, kaiser(N+1, BETA), flag); +AMfilter = dfilt.dffir(b); + +%% Check frequency response +% Gives a -3 dB cutoff at cutoff_freq Hz, using: +% freqz(AMfilter.Numerator) +% norm_cutoff_freq = 0.139; % insert freq here from plot +% cutoff_freq = norm_cutoff_freq*(fs/2); + +%% Remove VHFs +s_dt=detrend(s.v); +s_filt.v = filtfilt(AMfilter.numerator, 1, s_dt); +end + +function s_filt = elim_vhfs2(s, up) +%% Filter signal to remove VHFs +% Adapted from RRest +% Adapted for single pulses + +s_filt.fs = s.fs; + +%% Eliminate nans +s.v(isnan(s.v)) = mean(s.v(~isnan(s.v))); + +%% Repeat pulse +s.v = repmat(s.v(:), [up.paramSet.no_pulse_repeats,1]); + +%% Check to see if sampling freq is at least twice the freq of interest +if (up.paramSet.elim_vhf.Fpass/(s.fs/2)) >= 1 + % then the fs is too low to perform this filtering + s_filt.v = s.v; + return +end + +%% Create filter +% parameters for the low-pass filter to be used +flag = 'scale'; +[N,Wn,BETA,TYPE] = kaiserord([up.paramSet.elim_vhf.Fstop up.paramSet.elim_vhf.Fpass]/(s.fs/2), [1 0], [up.paramSet.elim_vhf.Dstop up.paramSet.elim_vhf.Dpass]); +b = fir1(N, Wn, TYPE, kaiser(N+1, BETA), flag); +AMfilter = dfilt.dffir(b); + +%% Check frequency response +% Gives a -3 dB cutoff at cutoff_freq Hz, using: +% freqz(AMfilter.Numerator) +% norm_cutoff_freq = 0.067; % insert freq here from plot +% cutoff_freq = norm_cutoff_freq*(s.fs/2); + +%% Remove VHFs +s_dt=detrend(s.v); +s_filt.v = filtfilt(AMfilter.numerator, 1, s_dt); + +%% Extract original pulse (from repeated pulses) +len_of_each_pulse = length(s.v)/up.paramSet.no_pulse_repeats; +start_pulse_no = floor(up.paramSet.no_pulse_repeats/2); +end_pulse_no = ceil(up.paramSet.no_pulse_repeats/2); +rel_els = (start_pulse_no*len_of_each_pulse)+1 : end_pulse_no*len_of_each_pulse; +s_filt.v = s_filt.v(rel_els); + +end + +function [peaks,onsets,clipp] = adaptPulseSegment(y,Fs,annot) +%ADAPTPULSESEGMENT perform adaptive pulse segmentation and artifact detection +%in ppg signals +% [peaks,onsets,artif] = adaptPulseSegment(y,annot) +% +% Inputs: +% y vector, ppg signal [Lx1] or [1xL], in which L = length(signal) +% Fs scalar, sampling frequency in Hz +% annot vector, timestamps (in samples) with location of the peaks +% +% Outputs: +% peaks vector, locations of peaks (in samples) +% onsets vector, locations of onsets of the beats (in samples) +% artif vector, locations of peaks classified as artefacts +% +% References: +% Karlen et al., Adaptive Pulse Segmentation and Artifact Detection in +% Photoplethysmography for Mobile Applications, 34th Internat. Conf. IEEE-EMBS 2012 +% +% Written by Marco A. Pimentel + +doOptimise = 1; +doPlot = 0; +if nargin < 3 + % no annotations are provided, therefore, no optimisation will take + % place + doOptimise = 0; +end + + +% The algorithm in the paper is applied to signals sampled at 125 Hz... +% We do not resample our signal +%ys = resample(y,125,Fs); +%Fs = 125; +% if Fs ~= 300 +% ys = resample(y,300,Fs); +% Fs = 300; +% else + ys = y; +% end + +% The paper is not clear about the selection of the range of search for m +% We define the range of m to be between [0.005 - 0.100] secs (5ms to 100ms) +% We define ""m"" in terms of samples +opt.bounds = 0.005:0.005:0.100; +opt.m = unique(ceil(opt.bounds*Fs)); + +opt.perf = zeros(length(opt.m),4); % store results of performance for each m + +if doOptimise + % Perform optimisation + for i = 1 : length(opt.m) + % Determine peaks and beat onsets + [linez,linezSig] = pulseSegment(ys,Fs,opt.m(i)); + % Calculate performance of the peak detection + opt.perf(i,:) = evalPerf(annot,linez(:,2)); + end + +else + % Do not perform optimization; fix m + opt.m = 10; + [peaks,artifs,clipp,linez,linezSig] = pulseSegment(ys,Fs,opt.m); +end + +if doPlot + colData = {'g','y','r'}; + figure; + h(1) = subplot(211); + plot(ys); hold on; + for i = 1 : size(linez,1) + %if linezSig(i) > -1 + plot(linez(i,:),ys(linez(i,:)),'-x','Color',colData{linezSig(i)+2}); + %end + end + + h(2) = subplot(212); + plot(ys,'g'); hold on; + for i = 1 : size(peaks,1) + plot(peaks(i,:),ys(peaks(i,:)),'-xr'); + end + if ~isempty(artifs) + for i = 1 : size(artifs,1) + plot(artifs(i,:),ys(artifs(i,:)),'--^b'); + end + end + if ~isempty(clipp) + for i = 1 : size(clipp,1) + plot(clipp(i,:),ys(clipp(i,:)),'-om'); + end + end + linkaxes(h,'x'); + +end + +% Correct for the downsmapling performed during the peak detection +onsets = peaks(:,1); +peaks = peaks(:,2); +for i = 1 : size(peaks,1) + [~,ind] = min(ys(max([1 onsets(i)-opt.m]):min([length(ys) onsets(i)+opt.m]))); + onsets(i) = max([1 onsets(i)-opt.m]) + ind(1) - 1; + [~,ind] = max(ys(max([1 peaks(i)-opt.m]):min([length(ys) peaks(i)+opt.m]))); + peaks(i) = max([1 peaks(i)-opt.m]) + median(ind) - 1; +end + +% Correct minimum value of onset of the beat +for i = 2 : length(onsets) + [~,ind] = min(ys(peaks(i-1):peaks(i))); + onsets(i) = peaks(i-1) + ind - 1; +end + +end + +function [peaks,artifs,clipp,linez,linezSig] = pulseSegment(ys,Fs,m) +% Perform pulse segmentation in ys given m +% Inputs: +% ys vector, with ppg signal +% m scalar, with the length of each line (read paper for details) +% +% Outputs: +% linez 2-column vector, with location of beat onsets and peaks +% linezSig vector, with label of the slope of each line segment +% 1 - positive slope; -1 - negative slope; 0 - constant +% + +% split signal in different segments +nseg = floor(length(ys)/m); % number of segments +% nseg = round(length(ys)/m); % number of segments +% intialize loop variables +seg = 1; % segment counter +z = 1; % line counter +segInLine = 1; % line controler +linez = zeros(nseg,2); linez(1,:) = [1,m]; +% slope of segment/line +a = zeros(nseg,1); a(1) = slope(ys,linez(1,:)); +% ""classify"" line segment according to the slope +linezSig = zeros(nseg,1); linezSig(1) = sign(a(1)); +% Start loop over segments +z = z + 1; seg = seg + 1; +for i = 2 : nseg % loop over segments + linez(z,:) = [(seg-1)*m+1 seg*m]; + try + a(z) = slope(ys,linez(z,:)); + catch + a = 1; + end + linezSig(z) = sign(a(z)); + if sign(a(z)) == sign(a(z-1)) + linez(z-1,:) = [(seg-1-segInLine)*m+1 seg*m]; + seg = seg + 1; + segInLine = segInLine + 1; + else + z = z + 1; + seg = seg + 1; + segInLine = 1; + end +end + +% remove extra spaces created in output variables +linezSig(sum(linez,2)==0,:) = []; +linez(sum(linez,2)==0,:) = []; + +% Apply adaptive threshold algorithm +% For this algorithm to work, we need to first find a valide line segment +% in order to intialize the thresholds! In order to this, we define a flag +% to control the intialization in the main loop +FOUND_L1 = 0; + +% The algorithm includes the definition of 4 adaptation parameters +% We define the following adaptation parameters +% a = | a_fast_low a_fast_high | +% | a_slow_low a_slow_high | +% +a = [0.5 1.6; ... + 0.6 2.0]; + +% Define fixed thresholds described in the paper +ThT = 0.03 * Fs; % Duration of the line +ThIB = 0.24 * Fs; % Interbeat invertal (240 ms) + +% Define parameters used in the main loop +alpha = zeros(size(linez,1),1); +for i = 1 : size(linez,1) + alpha(i) = slope(ys,linez(i,:)); % slopes of line segments +end +theta = diff(ys(linez),[],2); +durat = diff(linez,[],2); % duration of line segments (in samples) + +% remove lines that do not have the necessary duration +linez(durat0); +try + wind = wind(1:10); +catch + wind = wind; +end +ThAlow = prctile(wind,95)*0.6; +ThAhigh = prctile(wind,95)*1.8; +peaks = []; +for z = 1 : size(linez,1)-1 % loop over line segments + if FOUND_L1 + if alpha(z) > 0 && ... % slope must be positive + alpha(z-1) ~= 0 && ... % peaks before or after clipping are artefactual + alpha(z+1) ~= 0 + if theta(z) >= ThAlow && theta(z) <= ThAhigh && ... + linez(z,2) >= peaks(end,2) + ThIB + ThAlow = (ThAlow + theta(z)*a(2,1))/2; + ThAhigh = theta(z) * a(2,2); + FLAG = 0; + currTheta = [currTheta; theta(z)]; + peaks = [peaks; linez(z,:)]; + else + if FLAG > 0 + ThAlow = (ThAlow + min(currTheta(max([1 end-4]):end))*a(1,1))/2; + ThAhigh = max(currTheta(max([1 end-4]):end)) * a(1,2); + %ThAlow = (ThAlow + theta(z)*a(1,1))/2; + %ThAhigh = theta(z) * a(1,2); + end + FLAG = FLAG + 1; + artifs = [artifs; linez(z,:)]; + end + elseif theta(z) > 0 && ... + ((theta(z-1) ~= 0 || horiz(z-1) ~= 0) && ... + (theta(z+1) ~= 0 || horiz(z+1) ~= 0)) + if theta(z) >= ThAlow && theta(z) <= ThAhigh && ... + linez(z,2) >= peaks(end,2) + ThIB + ThAlow = (ThAlow + theta(z)*a(2,1))/2; + ThAhigh = theta(z) * a(2,2); + FLAG = 0; + currTheta = [currTheta; theta(z)]; + peaks = [peaks; linez(z,:)]; + else + if FLAG > 0 + %ThAlow = (ThAlow + currTheta*a(1,1))/2; + %ThAhigh = currTheta * a(1,2); + ThAlow = (ThAlow + min(currTheta(max([1 end-4]):end))*a(1,1))/2; + ThAhigh = max(currTheta(max([1 end-4]):end)) * a(1,2); + %ThAlow = (ThAlow + theta(z)*a(1,1))/2; + %ThAhigh = theta(z) * a(1,2); + end + FLAG = FLAG + 1; + artifs = [artifs; linez(z,:)]; + end + elseif theta(z) == 0 && horiz(z) == 0 + artifs = [artifs; linez(z,:)]; + clipp = [clipp; linez(z,:)]; + end + else + if alpha(z) > 0 && durat(z) >= ThT && ... + theta(z) >= ThAlow && theta(z) <= ThAhigh + FOUND_L1 = 1; + ThAlow = theta(z)*0.5; + ThAhigh = theta(z)*2.0; + peaks = linez(z,:); % loaction of onsets and peaks + currTheta = theta(z); + end + end +end + +end + +function out = horizontalLine(ys,linez,Fs) +% Get horizontal lines from signal given linez +out = zeros(size(linez,1),1); +for i = 1 : size(linez,1) + out(i) = median(abs(diff(ys(linez(i,1):linez(i,2))))); + % check duration of the peaks + if out(i) == 0 && diff(linez(i,:)) <= 0.200*Fs + out(i) = 0.1; + end +end + +end + +function out = slope(ys,interv) +start = interv(1); stop = interv(2); +out = sum(diff(ys([start:stop])))/(stop-start); +%out = median(gradient(ys(start:stop))); +end + +function quality = assess_signal_quality(s, pulse_inds) +% ASSESS_SIGNAL_QUALITY Assesses the signal quality of each beat of the +% pulsatile signal. +% Inputs: +% s - pulsatile signal, a structure containing s.v (a +% vector of values), and s.fs (sampling frequency in Hz). +% pulse_inds - indices of the pulse peaks +% +% Outputs: +% quality - the signal quality of each beat (1 indicates high +% quality, 0 low quality). +% +% Adapted from RRest +% +% Reference: This function uses an adaptation of the signal quality index +% for the photoplethysmogram described in: +% Orphanidou, C. et al., 2015. Signal-quality indices for the electrocardiogram and photoplethysmogram: derivation and applications to wireless monitoring. IEEE Journal of Biomedical and Health Informatics, 19(3), pp.832–8. Available at: http://www.ncbi.nlm.nih.gov/pubmed/25069129. + +%% Setup +s.t = [0:length(s.v)-1]/s.fs; + +%% Segment into windows of 10s duration +win_durn = 10; % in secs +win.deb = s.t(1):(win_durn-2):s.t(end); +win.fin = win.deb + win_durn; + +high_quality_pulse_inds = []; +for win_no = 1 : length(win.deb) + + % identify data for this window + + rel_els = s.t >= win.deb(win_no) & s.t <= win.fin(win_no); + first_el = find(rel_els,1); + curr_sig.v = s.v(rel_els); + curr_sig.t = s.t(rel_els); clear rel_els + curr_sig.t = curr_sig.t - curr_sig.t(1); + curr_sig.pulse_ind_inds = find(s.t(pulse_inds) >= win.deb(win_no) & s.t(pulse_inds) <= win.fin(win_no)); + curr_pulse_inds = pulse_inds(curr_sig.pulse_ind_inds) - first_el + 1; + + % find beat-to-beat interval + + beat_to_beat_interval = median(diff(curr_sig.t(curr_pulse_inds))); + beat_to_beat_samples = round(beat_to_beat_interval*s.fs); clear beat_to_beat_interval + + % find a template beat + ts = []; + rel_els = curr_pulse_inds>beat_to_beat_samples/2 & ... + curr_pulse_inds+floor(beat_to_beat_samples/2) 0.86; + + high_quality_pulse_inds = [high_quality_pulse_inds, curr_sig.used_pulse_ind_inds(high_quality_beats)]; + + % % calculate template using only high-quality beats + % templ = mean(ts(r2>0.86,:),1); %threshold = 0.66 for ECG, 0.86 for PPG; % ecg cross-correlation threshold value (for sqi) + +end + +high_quality_pulse_inds = unique(high_quality_pulse_inds); +quality = false(length(pulse_inds),1); +for ind = 1 : length(quality) + if intersect(high_quality_pulse_inds, ind) + quality(ind) = true; + end +end +end + +function sigs = calc_derivs2(sig, s_filt, no_of_pulses, ~) + +switch no_of_pulses + + case 'multiple' + + % calculate derivatives + derivs.first = fsg521(sig.v)*sig.fs; + derivs.second = fsg521(derivs.first)*sig.fs; + derivs.third = fsg521(derivs.second)*sig.fs; + +% % calculate derivatives of filtered signal +% derivs.f_first = savitzky_golay(s_filt.v, 1, 9); +% derivs.f_second = savitzky_golay(derivs.f_first, 1, 9); +% derivs.f_third = savitzky_golay(derivs.f_second, 1, 9); + + case 'single' + + % repeat this single pulse several times + no_pulses = 3; % number of times to repeat pulse + sig.v = repmat(sig.v, [no_pulses,1]); + s_filt.v = repmat(s_filt.v, [no_pulses,1]); + + % calculate derivatives of orig signal + derivs.first = savitzky_golay(sig.v, 1, 5)*sig.fs; + derivs.second = savitzky_golay(derivs.first, 1, 5)*sig.fs; + derivs.third = savitzky_golay(derivs.second, 1, 5)*sig.fs; + +% % calculate derivatives of filtered signal +% derivs.f_first = savitzky_golay(s_filt.v, 1, 9); +% derivs.f_second = savitzky_golay(derivs.f_first, 1, 9); +% derivs.f_third = savitzky_golay(derivs.f_second, 1, 9); + + % select derivative values corresponding to the original pulse + orig_len = length(sig.v)/no_pulses; + orig_els = (floor(no_pulses/2)*orig_len)+1 : ((floor(no_pulses/2)+1)*orig_len); + derivs.first = derivs.first(orig_els); + derivs.second = derivs.second(orig_els); + derivs.third = derivs.third(orig_els); +% derivs.f_first = derivs.f_first(orig_els); +% derivs.f_second = derivs.f_second(orig_els); +% derivs.f_third = derivs.f_third(orig_els); +end + +sigs.fs = sig.fs; +sigs.s = sig.v; +sigs.s_filt = s_filt.v; +sigs.derivs = derivs; + +end + +function deriv = savitzky_golay(sig, deriv_no, win_size) + +%% assign coefficients +% From: https://en.wikipedia.org/wiki/Savitzky%E2%80%93Golay_filter#Tables_of_selected_convolution_coefficients +% which are calculated from: A., Gorry (1990). ""General least-squares smoothing and differentiation by the convolution (Savitzky?Golay) method"". Analytical Chemistry. 62 (6): 570?3. doi:10.1021/ac00205a007. + +switch deriv_no + case 0 + % - smoothing + switch win_size + case 5 + coeffs = [-3, 12, 17, 12, -3]; + norm_factor = 35; + case 7 + coeffs = [-2, 3, 6, 7, 6, 3, -2]; + norm_factor = 21; + case 9 + coeffs = [-21, 14, 39, 54, 59, 54, 39, 14, -21]; + norm_factor = 231; + otherwise + error('Can''t do this window size') + end + case 1 + % - first derivative + switch win_size + case 5 + coeffs = -2:2; + norm_factor = 10; + case 7 + coeffs = -3:3; + norm_factor = 28; + case 9 + coeffs = -4:4; + norm_factor = 60; + otherwise + error('Can''t do this window size') + end + + case 2 + % - second derivative + switch win_size + case 5 + coeffs = [2,-1,-2,-1,2]; + norm_factor = 7; + case 7 + coeffs = [5,0,-3,-4,-3,0,5]; + norm_factor = 42; + case 9 + coeffs = [28,7,-8,-17,-20,-17,-8,7,28]; + norm_factor = 462; + otherwise + error('Can''t do this window size') + end + + case 3 + % - third derivative + switch win_size + case 5 + coeffs = [-1,2,0,-2,1]; + norm_factor = 2; + case 7 + coeffs = [-1,1,1,0,-1,-1,1]; + norm_factor = 6; + case 9 + coeffs = [-14,7,13,9,0,-9,-13,-7,14]; + norm_factor = 198; + otherwise + error('Can''t do this window size') + end + + case 4 + % - fourth derivative + switch win_size + case 7 + coeffs = [3,-7,1,6,1,-7,3]; + norm_factor = 11; + case 9 + coeffs = [14,-21,-11,9,18,9,-11,-21,14]; + norm_factor = 143; + otherwise + error('Can''t do this window size') + end + + otherwise + error('Can''t do this order of derivative') +end + +if rem(deriv_no, 2) == 1 + coeffs = -1*coeffs; +end + +A = [1,0]; +filtered_sig = filter(coeffs, A, sig); +s=length(sig); +half_win_size = floor(win_size*0.5); +deriv=[filtered_sig(win_size)*ones(half_win_size,1);filtered_sig(win_size:s);filtered_sig(s)*ones(half_win_size,1)]; +deriv = deriv/norm_factor; + +end + +function derivs = calc_derivs(sig, no_of_pulses, up) + +switch no_of_pulses + + case 'multiple' + + % calculate derivatives + derivs.first = fsg521(sig.v); + derivs.second = fsg521(derivs.first); + derivs.third = fsg521(derivs.second); + + case 'single' + + % repeat this single pulse several times + no_pulses = 5; % number of times to repeat pulse + sig.v = repmat(sig.v, [no_pulses,1]); + + % calculate derivatives + derivs.first = fsg521(sig.v); + derivs.second = fsg521(derivs.first); + derivs.third = fsg521(derivs.second); + + % select derivative values corresponding to the original pulse + orig_len = length(sig.v)/no_pulses; + orig_els = (floor(no_pulses/2)*orig_len)+1 : ((floor(no_pulses/2)+1)*orig_len); + derivs.first = derivs.first(orig_els); + derivs.second = derivs.second(orig_els); + derivs.third = derivs.third(orig_els); + +end + +derivs.fs = sig.fs; + +end + +function dx=fsg521(x) + +% Savitsky-Golay filter function +% dx=fsg521(x) +% 5 point SavGol filter, 2nd order polynomial, 1st derivative +% input x +% output dx +% corrected for time shift +% +% Adapted from Marie Willemet's code + +C=[0.2,0.1]; + +for i=1:2; + B(i)=C(i); +end +B(3)=0.0; +for i=4:5; + B(i)=-C(6-i); +end +A=[1,0]; + +s=length(x); +dx=filter(B,A,x); +dx=[dx(5)*ones(2,1);dx(5:s);dx(s)*ones(2,1)]; + +end + +function pts = identify_fiducial_pts(sigs, onsets, up, no_of_pulses, options) +% IDENTIFY_FIDUCIAL_PTS Identifies fiducial points on each wave of a +% pulsatile signal. +% +% Inputs: +% sig - pulsatile signal, a structure containing .v (a +% vector of values), and .fs (sampling frequency in Hz). +% onsets - indices of the pulse onsets +% derivs - a structure containing .first, .second and .third +% derivatives of sig +% +% Outputs: +% pts - a structure containing the indices of the fiducial +% points for each beat (a nan indicates that a fiducial +% point could not be identified). +% + + +%% find fiducial points + +% setup variables +fid_pt_names = {'a', 'b', 'c', 'd', 'e', 'f', 's', 'dia', 'dic', 'p1pk', 'p2pk', 'p1in', 'p2in', 'ms', 'f1', 'f2'}; +for fid_pt_no = 1 : length(fid_pt_names) + eval(['pts.' fid_pt_names{fid_pt_no} ' = nan(length(onsets)-1,1);']) +end + +% setup buffer zones +buffer_tol.deb = 0.005; % in secs +buffer_tol.fin = 0.2; % in proportion of beat +buffer_p1 = [0.1, 0.18]; % in secs + +for pulse_no = 1 : length(onsets)-1 + + % extract data for this pulse + curr_els = onsets(pulse_no):onsets(pulse_no+1); + curr.f_sig = sigs.s_filt(curr_els); + curr.sig = sigs.s(curr_els); + + if strcmp(no_of_pulses, 'multiple') + + old.v = curr.sig; old.fs = sigs.fs; + % Eliminate low frequency content + temp = eliminate_low_freq_from_single_beat(old, up); + + % Ensure that signal commences at start of systole + temp2 = align_pulse(temp, up); + curr.sig = temp2.v; + end + + % calculate derivatives + curr.derivs.first = sigs.derivs.first(curr_els); + curr.derivs.second = sigs.derivs.second(curr_els); + curr.derivs.third = sigs.derivs.third(curr_els); +% curr.derivs.f_first = sigs.derivs.f_first(curr_els); +% curr.derivs.f_second = sigs.derivs.f_second(curr_els); +% curr.derivs.f_third = sigs.derivs.f_third(curr_els); + + % find buffers + initial_buffer = floor(buffer_tol.deb * sigs.fs); % in samples + end_buffer = length(curr.sig) - ceil(buffer_tol.fin * length(curr.sig)); % in samples + + % find f1 and f2 + temp_f1 = 1; + temp_f2 = length(curr.sig); + + % find s + temp_s = identify_s(curr); + + % find ms + temp_ms = identify_ms(curr); + + % find a + temp_a = identify_a(curr, initial_buffer); + + if isempty(temp_a) + continue + end + + % find b + temp_b = identify_b(curr, temp_a); + + if isempty(temp_b) + continue + end + + % find p1 + p1_buffer = floor(buffer_p1 .* sigs.fs); % in samples + temp_p1 = identify_p1(curr, temp_b, temp_ms, p1_buffer, no_of_pulses, sigs.fs, up); + + % find e + redo_log = 0; + temp_e = identify_e(curr, temp_s, temp_ms, temp_b, end_buffer, redo_log); + + if options.manual_adjustment + if sum(strcmp(options, 'e')) + temp_e = options.man_e; + else + temp_e = 270; + end + end + + if isempty(temp_e) + [temp_f, temp_c, temp_d, temp_dic, temp_dia, temp_p2] = deal(nan); + else + + % find c + temp_c = identify_c(curr, temp_b, temp_e); + + if isempty(temp_c) + redo_log = 1; + old_temp_e = temp_e; + temp_e = identify_e(curr, temp_s, temp_ms, end_buffer, redo_log); + end + + % find c + temp_c = identify_c(curr, temp_b, temp_e); + + % find f + temp_f = identify_f(curr, temp_e, end_buffer); + + % find dic + temp_dic = identify_dic(curr,temp_e); + + % find dia + temp_dia = identify_dia(curr, temp_dic, temp_e, end_buffer); + + if isempty(temp_c) + [temp_d, temp_p2] = deal(nan); + else + % find d + temp_d = identify_d(curr, temp_c, temp_e); + + % find p2 + temp_p2 = identify_p2(curr, temp_d, temp_p1, temp_dic); + + end + + end + + % retain timings of original p1 and p2 estimates + temp_p1in = temp_p1; temp_p2in = temp_p2; + + % make p1 or p2 coincident with the systolic peak + [~, rel_el] = min(abs(temp_s-[temp_p1,temp_p2])); + if rel_el == 1 + temp_p1 = temp_s; + else + temp_p2 = temp_s; + end + + if ~isnan(temp_p2) & ~isnan(temp_p1) + % make sure p2 is at a peak if necessary + pks = find_pks_trs(curr.sig, 'pk'); + cutoff = mean([temp_p1, temp_p2]); + possible_pks = find(pks > cutoff & pks < temp_e & curr.sig(pks) > curr.sig(temp_p2)); + if ~isempty(possible_pks) + [~, temp_el] = max(curr.sig(pks(possible_pks))); + temp_p2 = pks(possible_pks(temp_el)); + end + % make sure p1 is at a peak if necessary + pks = find_pks_trs(curr.sig, 'pk'); + cutoff = mean([temp_p1, temp_p2]); + possible_pks = find(pks < cutoff & pks > temp_ms & curr.sig(pks) > curr.sig(temp_p1)); + if ~isempty(possible_pks) + [~, temp_el] = max(curr.sig(pks(possible_pks))); + temp_p1 = pks(possible_pks(temp_el)); + end + end + + % store p1pk and p2pk + temp_p1pk = temp_p1; + temp_p2pk = temp_p2; + + % store points + for fid_pt_no = 1 : length(fid_pt_names) + eval(['curr_temp_el = temp_' fid_pt_names{fid_pt_no} ';']); + if ~isnan(curr_temp_el) + eval(['pts.' fid_pt_names{fid_pt_no} '(pulse_no) = curr_temp_el + curr_els(1)-1;']) + else + eval(['pts.' fid_pt_names{fid_pt_no} '(pulse_no) = nan;']) + end + end + + + clear curr temp* curr_els empty_log + +end +clear pulse_no + + +%% Ensure only pts are provided for those pulses with all pts available +pt_names = fieldnames(pts); +include_pulse = true(size(pts.dia)); +for pt_name_no = 1 : length(pt_names) + eval(['curr_pt_measures = pts.' pt_names{pt_name_no} ';']); + include_pulse(isnan(curr_pt_measures)) = false; +end +for pt_name_no = 1 : length(pt_names) + if strcmp(pt_names{pt_name_no}, 'f1') || strcmp(pt_names{pt_name_no}, 'f2') + continue + end + eval(['pts.' pt_names{pt_name_no} '(~include_pulse) = nan;']); +end + +end + +function temp_s = identify_s(curr) + +[~, temp_s] = max(curr.sig); + +end + +function temp_a = identify_a(curr, initial_buffer) + +[~,filtered_ms] = max(curr.derivs.first); + +pks = find_pks_trs(curr.derivs.second, 'pk'); +rel_pks = pks(pks > initial_buffer & pks < filtered_ms); +if isempty(rel_pks) && sum(pks<=initial_buffer) > 0 % Added in PulseAnalyse5 + rel_pks = pks(find(pks <= initial_buffer, 1, 'last')); +end +[~, temp_el] = max(curr.derivs.second(rel_pks)); +temp_a = rel_pks(temp_el); + +end + +function temp_e = identify_e(curr, temp_s, temp_ms, temp_b, end_buffer, redo_log) + +% Find local maxima in the second derivative +pks = find_pks_trs(curr.derivs.second, 'pk'); +% Set an upper bound of 60 % of the PW duration +upper_bound = 0.6*length(curr.sig); % const from: https://en.wikipedia.org/wiki/QT_interval#/media/File:QT_interval_corrected_for_heart_rate.png +% Set a lower bound of 'ms' +lower_bound = temp_ms; +% Identify the highest local maximum in the second derivative between these two bounds +rel_pks = pks(pks >= lower_bound & pks <= upper_bound); +[~, max_el] = max(curr.derivs.second(rel_pks)); +% If this is the first local maximum in this search region ... +if max_el == 1 + % work out whether this has detected the ""c"" wave + % - find out if there's an inflection point between ""b"" and this + temp_trs = find_pks_trs(curr.derivs.third, 'tr'); + no_infl = sum(temp_trs > temp_b & temp_trs < rel_pks(max_el)); + % - if not then take the next peak + if no_infl == 0 + % if there is 1 peak in this search region ... + if length(rel_pks) < max_el+1 % Added in PulseAnalyse5 + % then take the next peak (slightly above the upper bound + orig_el = find(pks >= lower_bound & pks <= upper_bound); + rel_pks = pks(orig_el:orig_el+1); + end + rel_pk = rel_pks(max_el+1); + else + rel_pk = rel_pks(max_el); + end +else + rel_pk = rel_pks(max_el); +end +temp_e = rel_pk; + +end + +function temp_f = identify_f(curr, temp_e, end_buffer) + +lower_bound = temp_e; +upper_bound = end_buffer; +trs = find_pks_trs(curr.derivs.second, 'tr'); +possible_els = trs(trs >= lower_bound & trs <= upper_bound); + +if isempty(possible_els) % Added in PulseAnalyse5 + possible_els = trs(find(trs >=lower_bound, 1)); +end + +if isempty(possible_els) + temp_f = nan; +else + temp_f = possible_els(1); +end + +end + +function temp_b = identify_b(curr, temp_a) + +% find b (PulseAnalyse6 onwards) + +% Find local minima in second derivative +trs = find_pks_trs(curr.derivs.second, 'tr'); +% define an upper bound as 25% of the duration of the signal +upper_bound = 0.25*length(curr.sig); +% find local minima between 'a' and this upper bound +temp = find(trs > temp_a & curr.derivs.second(trs) < 0 & trs < upper_bound); +% Identify the lowest of these local minima +[~, rel_el] = min(curr.derivs.second(trs(temp))); +temp = temp(rel_el); +temp_b = trs(temp); clear temp + +end + +function temp_d = identify_d(curr, temp_c, temp_e) + +% Identify ""d"" as the lowest minimum of the second deriv between ""c"" and ""e"" +trs = find_pks_trs(curr.derivs.second, 'tr'); +possible_trs = find(trs > temp_c & trs < temp_e); +if ~isempty(possible_trs) + temp = trs(possible_trs); + [~, temp_el] = min(curr.derivs.second(temp)); + temp_d = temp(temp_el); clear temp +else + % unless there isn't a minimum, in which case it's an inflection, and + % ""d"" is the same as ""c"" + temp_d = temp_c; +end + +end + +function temp_c = identify_c(curr, temp_b, temp_e) + +% Identify C as the highest local maximum on the second derivative between ""b"" and ""e"" +pks = find_pks_trs(curr.derivs.second, 'pk'); +temp = find(pks > temp_b & pks < temp_e); +[~, rel_tr_el] = max(curr.derivs.second(pks(temp))); +temp_c = pks(temp(rel_tr_el)); clear temp rel_tr_el pks + +% If there aren't any peaks that satisfy this criterion ... +if isempty(temp_c) + % then identify C as the lowest local minimum on the third derivative + % after ""b"" and before ""e"" + trs = find_pks_trs(curr.derivs.third, 'tr'); + temp = find(trs > temp_b & trs < temp_e); + [~, rel_tr_el] = min(curr.derivs.third(trs(temp))); + if ~isempty(rel_tr_el) + temp_c = trs(temp(rel_tr_el)); clear temp rel_tr_el trs + end +end + +end + +function temp_dic = identify_dic(curr,temp_e) + +temp_dic = temp_e; + +end + +function temp_dia = identify_dia(curr, temp_dic, temp_e, end_buffer) + +% if there is a diastolic peak, then use that: +% - first peak in signal after ""dic"" +pks = find_pks_trs(curr.sig, 'pks'); +temp_dia = pks(find(pks > temp_dic & pks < end_buffer, 1)); + +% if not, then ... +% % I tried (i) take first peak on first derivative after ""e"" +if isempty(temp_dia) + pks = find_pks_trs(curr.derivs.first, 'pks'); + temp_dia = pks(find(pks > temp_e & pks < end_buffer, 1)); +end +% % But the problem is that the first derivative isn't necessarily a peak at +% % the diastolic peak - it can be an inflection point. So: +% (ii) the soonest out of (a) first peak on first derivative after ""e"" +% (b) first min on third derivative after ""e"" +% if isempty(temp_dia) +% pks = find_pks_trs(curr.derivs.first, 'pks'); +% temp_dia1 = pks(find(pks > temp_e, 1)); +% trs = find_pks_trs(curr.derivs.third, 'trs'); +% temp_dia2 = trs(find(trs > temp_e, 1)); +% temp_dia = min([temp_dia1, temp_dia2]); +% end + + +end + +function temp_ms = identify_ms(curr) + +% find max slope in DPPG +[~, temp_ms] = max(curr.derivs.first); + +end + +function temp_p1 = identify_p1(curr, temp_b, temp_ms, buffer_p1, no_of_pulses, fs, up) + +% find p1 + +% find local minima in the first derivative +fd_trs = find_pks_trs(curr.derivs.first, 'tr'); +% find local maxima in the second derivative +sd_pks = find_pks_trs(curr.derivs.second, 'pk'); + +% Find the first local minimum in the first derivative after 0.1 s +current_buffer = buffer_p1(1); +temp = find(fd_trs > current_buffer,1); +% Find the second local minimum (or failing that, the first) in the first derivative after 'b' +temp2 = find(fd_trs > temp_b, 2); +if length(temp2) > 1 + temp2 = temp2(2); +end +% Take whichever comes first: +if temp2 < temp + temp = temp2; +end +temp_p1 = fd_trs(temp); + +% If this value for p1 is after the buffer of 0.18 s ... +if temp_p1 > buffer_p1(2) + curr.derivs.fourth = savitzky_golay(curr.derivs.third, 1, 9); + % Then find the first local minimum in the fourth derivative after 0.1 s + fd_trs = find_pks_trs(curr.derivs.fourth, 'tr'); + temp = find(fd_trs > current_buffer,1); + temp_p1 = fd_trs(temp); clear temp +end + +% If this value for p1 is after the buffer of 0.18 s ... +if temp_p1 > buffer_p1(2) + % Then find the last local minimum in the first derivative before 0.18 s + temp_p1 = fd_trs(find(fd_trs <= current_buffer,1,'last')); +end + +end + +function temp_p2 = identify_p2(curr, temp_d, temp_p1, temp_dic) + +% Find ""p2"" from the minimum value of the third derivative immediately before ""d"" +td_trs = find_pks_trs(curr.derivs.third, 'tr'); +temp = find(td_trs < temp_d,1,'last'); clear d_pks +temp_p2 = td_trs(temp); + +% unless c=d, in which case p2 will now be before p1, so take the minimum +% value of the third derivative immediately after ""d"" +if temp_p2 < temp_p1 + temp_p2 = td_trs(find(td_trs temp_p2 & pks < temp_dic); +if length(temp) == 1 + temp_p2 = pks(temp); +elseif length(temp) == 2 + temp_p2 = pks(temp(2)); +elseif length(temp) > 1 + fprintf('\nCheck this') +end +clear pks + +end + +function pts = annotate_fiducial_pts(sig, onsets, derivs, up, no_of_pulses) +% IDENTIFY_FIDUCIAL_PTS Used to annotate fiducial points on each wave of a +% pulsatile signal. +% +% Inputs: +% sig - pulsatile signal, a structure containing .v (a +% vector of values), and .fs (sampling frequency in Hz). +% onsets - indices of the pulse onsets +% derivs - a structure containing .first, .second and .third +% derivatives of sig +% +% Outputs: +% pts - a structure containing the indices of the fiducial +% points for each beat (a nan indicates that a fiducial +% point could not be identified). +% + + +%% annotate fiducial points + +[pts.a, pts.b, pts.c, pts.d, pts.e, pts.f, pts.s, pts.dia, pts.dic, pts.p1, pts.p2, pts.ms, pts.f1, pts.f2] = deal(nan(length(onsets)-1,1)); +switch no_of_pulses + case 'multiple' + start_pulse = 100; + end_pulse = 100; + case 'single' + start_pulse = 1; + end_pulse = length(onsets)-1; +end +for pulse_no = start_pulse : end_pulse + + %% extract data for this pulse + curr_els = onsets(pulse_no):onsets(pulse_no+1); + curr.sig.v = sig.v(curr_els); + curr.derivs.first = derivs.first(curr_els); + curr.derivs.second = derivs.second(curr_els); + curr.derivs.third = derivs.third(curr_els); + + %% Plot waves + + %- setup + paper_size = [600,1050]; + figure('Position', [50,50, paper_size]) + ftsize = 16; lwidth = 2; + pp_annot = 0.8; + rt_annot = -0.02; + curr.sig.t = [0:length(curr.sig.v)-1]/sig.fs; + + h_b(1) = subplot('Position', [0.21,0.78,0.78,0.21]); + + % plot baseline curve + plot(curr.sig.t, curr.sig.v, 'LineWidth', lwidth); hold on, + + % set limits + curr_range = range(curr.sig.t); + xlim([curr.sig.t(1)-0.1*curr_range, curr.sig.t(end)+0.1*curr_range]) + + % set labels + ylab = ylabel('sig', 'FontSize', ftsize, 'Rotation', 0); + set(ylab, 'Units', 'Normalized', 'Position', [-0.18, 0.5, 0]); + set(gca, 'FontSize', ftsize -2) + set(gca, 'XTick', 0:0.25:1, 'XTickLabel', {}) + box off + + %- plot first derivative + h_b(2) = subplot('Position', [0.21,0.54,0.78,0.21]); + + % Plot x-axis + plot([-10, 10], [0,0], '--k'); hold on + + % plot baseline curve + plot(curr.sig.t, curr.derivs.first, 'LineWidth', lwidth); hold on, + + % set limits + curr_range = range(curr.sig.t); + xlim([curr.sig.t(1)-0.1*curr_range, curr.sig.t(end)+0.1*curr_range]) + ylims = ylim; curr_range = range(curr.derivs.first); + ylim([min(curr.derivs.first)-0.05*curr_range, max(curr.derivs.first)+0.15*curr_range]) + + % set labels + ylab = ylabel('DPPG', 'FontSize', ftsize, 'Rotation', 0); + set(ylab, 'Units', 'Normalized', 'Position', [-0.18, 0.5, 0]); + set(gca, 'FontSize', ftsize -2) + set(gca, 'XTick', 0:0.25:1, 'XTickLabel', {}) + box off + + %- plot Second derivative + h_b(3) = subplot('Position', [0.21,0.30,0.78,0.21]); + + % Plot x-axis + plot([-10, 10], [0,0], '--k'); hold on + + % plot baseline curve + curr_color = 0.4*0.5*[1,2,1]; + plot(curr.sig.t, curr.derivs.second, 'LineWidth', lwidth); hold on, + + % set limits + curr_range = range(curr.sig.t); + xlim([curr.sig.t(1)-0.1*curr_range, curr.sig.t(end)+0.1*curr_range]) + ylims = ylim; curr_range = range(curr.derivs.second); + ylim([min(curr.derivs.second)-0.05*curr_range, max(curr.derivs.second)+0.15*curr_range]) + + % set labels + ylab = ylabel('2nd D', 'FontSize', ftsize, 'Rotation', 0); + set(ylab, 'Units', 'Normalized', 'Position', [-0.18, 0.5, 0]); + set(gca, 'FontSize', ftsize -2, 'XTick', 0:0.25:1, 'XTickLabel', {}) + box off + + %- plot Third derivative + h_b(4) = subplot('Position', [0.21,0.06,0.78,0.21]); + + % Plot x-axis + plot([-10, 10], [0,0], '--k'); hold on + + % plot baseline curve + curr_color = 0.4*0.5*[1,2,1]; + plot(curr.sig.t, curr.derivs.third, 'LineWidth', lwidth); hold on, + + % set limits + curr_range = range(curr.sig.t); + xlim([curr.sig.t(1)-0.1*curr_range, curr.sig.t(end)+0.1*curr_range]) + ylims = ylim; curr_range = range(curr.derivs.third); + ylim([min(curr.derivs.third)-0.05*curr_range, max(curr.derivs.third)+0.15*curr_range]) + + % set labels + xlabel('Time [s]', 'FontSize', ftsize) + ylab = ylabel('3rd D', 'FontSize', ftsize, 'Rotation', 0); + set(ylab, 'Units', 'Normalized', 'Position', [-0.18, 0.5, 0]); + set(gca, 'FontSize', ftsize -2, 'XTick', 0:0.25:1) + box off + + linkaxes(h_b, 'x') + shg + + %% Annotation + + happy_with_annotations = false; + while ~happy_with_annotations + pts.a = 4; + pts.b = 13; + pts.c = 22; + pts.d = 35; + pts.e = 44; + pts.f = 53; + pts.s = 33; + pts.dia = 49; + pts.dic = 45; + pts.p1 = 17; + pts.p2 = 33; + pts.ms = 5; + pts.f1 = 1; + pts.f2 = 57; +% pt_names = fieldnames(pts); +% for pt_no = 1 : length(pt_names) +% % Update title +% axes(h_b(1)) +% title(['Annotate pt ' pt_names{pt_no}]) +% % Perform Annotation +% [temp,~] = ginput(1); +% % Find closest point to annotated time +% [~, temp2] = min(abs(curr.sig.t-temp)); +% % Store this annotation +% eval(['pts.' pt_names{pt_no} '(pulse_no) = temp2 + curr_els(1)-1;']); +% clear temp temp2 +% end + + %% Check that you are happy with these points + + % original pulse signal + axes(h_b(1)) + rel_pts = {'s', 'dia', 'dic', 'f1', 'f2', 'p1', 'p2'}; + vspace0 = 0.08*range(ylim); + for pt_name_no = 1 : length(rel_pts) + eval(['curr_el = pts.' rel_pts{pt_name_no} ';']) + plot(curr.sig.t(curr_el), curr.sig.v(curr_el), 'or') + curr_text = rel_pts{pt_name_no}; + hspace0 = 0;ftsize = 12; + text(curr.sig.t(curr_el)+hspace0, curr.sig.v(curr_el)+vspace0 , curr_text,'FontSize', ftsize, 'Color', 'r', 'HorizontalAlignment', 'center'); + end + + % first derivative + axes(h_b(2)) + rel_pts = {'ms'}; + vspace0 = 0.08*range(ylim); + for pt_name_no = 1 : length(rel_pts) + eval(['curr_el = pts.' rel_pts{pt_name_no} ';']) + plot(curr.sig.t(curr_el), curr.derivs.first(curr_el), 'or') + curr_text = rel_pts{pt_name_no}; + hspace0 = 0;ftsize = 12; + text(curr.sig.t(curr_el)+hspace0, curr.derivs.first(curr_el)+vspace0 , curr_text,'FontSize', ftsize, 'Color', 'r', 'HorizontalAlignment', 'center'); + end + + % second derivative + axes(h_b(3)) + rel_pts = {'a', 'b', 'c', 'd', 'e', 'f'}; + vspace0 = 0.08*range(ylim); + for pt_name_no = 1 : length(rel_pts) + eval(['curr_el = pts.' rel_pts{pt_name_no} ';']) + plot(curr.sig.t(curr_el), curr.derivs.second(curr_el), 'or') + curr_text = rel_pts{pt_name_no}; + hspace0 = 0;ftsize = 12; + text(curr.sig.t(curr_el)+hspace0, curr.derivs.second(curr_el)+vspace0 , curr_text,'FontSize', ftsize, 'Color', 'r', 'HorizontalAlignment', 'center'); + end + + % third derivative + axes(h_b(4)) + rel_pts = {'a', 'b', 'c', 'd', 'e', 'f'}; + vspace0 = 0.08*range(ylim); + for pt_name_no = 1 : length(rel_pts) + eval(['curr_el = pts.' rel_pts{pt_name_no} ';']) + plot(curr.sig.t(curr_el), curr.derivs.third(curr_el), 'or') + curr_text = rel_pts{pt_name_no}; + hspace0 = 0;ftsize = 12; + text(curr.sig.t(curr_el)+hspace0, curr.derivs.third(curr_el)+vspace0 , curr_text,'FontSize', ftsize, 'Color', 'r', 'HorizontalAlignment', 'center'); + end + + choice = questdlg('Are these annotations ok?', ... + 'Yes','No'); + % Handle response + switch choice + case 'Yes' + happy_with_annotations = true; + case 'No' + case 'Cancel' + error('User stopped script') + end + + end + close all + clear curr temp* trs curr_els happy_with_annotations + +end +clear pulse_no + +end + +function buttonDownCallback(o,e) +p = get(gca,'CurrentPoint'); +p = p(1,1:2); +title( sprintf('(%g,%g)',p) ) +end + +function Click_CallBack2(a) + +switch get(ancestor(a,'figure'),'SelectionType') + + case 'normal' %left click + point = get(a,'CurrentPoint'); + load(annotations_filepath); + [pk_anns.t,inds]=unique([pk_anns.t; point(1,1)+start_time]); + pk_anns.v=[pk_anns.v; point(1,2)]; pk_anns.v = pk_anns.v(inds); + [pk_anns.t, inds] = sort(pk_anns.t); + pk_anns.v = pk_anns.v(inds); + save(annotations_filepath, 'pk_anns'); + + case 'alt' % right click + point = get(a,'CurrentPoint'); + load(annotations_filepath); + [pk_anns.t,inds]=unique([pk_anns.t; point(1,1)]); + pk_anns.v=[pk_anns.v; point(1,2)]; pk_anns.v = pk_anns.v(inds); + [pk_anns.t, inds] = sort(pk_anns.t); + pk_anns.v = pk_anns.v(inds); + save(annotations_filepath, 'pk_anns'); + + case 'extend' % right click whilst holding down shift + load(annotations_filepath) + pk_anns.t = pk_anns.t(1:(end-1)); + pk_anns.v = pk_anns.v(1:(end-1)); + save(annotations_filepath, 'pk_anns'); + +end + +cla(axis_h) +plot(pk_anns.t-start_time,pk_anns.v, 'ro','LineWidth',4) + +end + +function trs = find_pks_trs(sig,type) + +if strcmp(type, 'tr') + sig = -sig; +end + +temp1 = find(sig(2:end-1) > sig(1:(end-2)) & sig(2:end-1) > sig(3:end) ); + +temp2 = find(sig(2:end-2) > sig(1:(end-3)) & sig(2:end-2)== sig(3:(end-1)) & sig(3:end-1) > sig(4:end) ); + +temp = unique([temp1; temp2]); + +trs = temp+1; + +end + +function stiff_inds = calc_stiffness_inds(sigs, pulses, pts, options) +% CALC_STIFFNESS_INDS Calculates stiffness indices from a pulsatile +% signal. +% +% Inputs: +% sig - pulsatile signal, a structure containing .v (a +% vector of values), and .fs (sampling frequency in Hz). +% derivs - a structure containing .first, .second and .third +% derivatives of sig +% pulses - a structure containing pulses.quality, a logical +% indicating the signal quality of each pulse (true +% indicates high quality). +% pts - a structure containing the indices of the fiducial +% points for each beat. +% +% Outputs: +% stiff_inds - a structure containing the stiffness indices for +% each beat (a nan indicates that the stiffness index for that beat +% could not be identified). +% + +%% Setup + +% create time vector +sigs.t = [0:length(sigs.s)-1]'/sigs.fs; + +% find out whether a height measurement has been provided +if sum(strcmp(fieldnames(sigs), 'ht')) + ht_provided = 1; +else + ht_provided = 0; +end + +% calculate additional features +T = nan(size(pts.f2)); +good_els = ~isnan(pts.s); +T(good_els) = sigs.t(pts.f2(good_els)) - sigs.t(pts.f1(good_els)); + +% make vectors for each stiffness index (in case there are nans in the pts indices) +si_names = {'delta_t', 'CT', 'SI', 'CT_div_h', 'prop_s', 't_sys', 't_dia', 't_ratio', 'prop_delta_t', 't_p1_dia', 't_p2_dia', 'AI', 'AP', 'RI', 'RI_p1', 'RI_p2', 'ratio_p2_p1', 'A1', 'A2', 'IPA', 'ms', 'ms_div_amp', 'b_div_a', 'c_div_a', 'd_div_a', 'e_div_a', 'a_div_amp', 'b_div_amp', 'c_div_amp', 'd_div_amp', 'e_div_amp', 'AGI', 'AGI_inf', 'AGI_mod', 't_b_c', 't_b_d', 'slope_b_c', 'slope_b_d', 'IPAD', 'k'}; +for name_no = 1 : length(si_names) + eval(['stiff_inds.' si_names{name_no} ' = nan(length(pts.f1),1);']); +end + +%% Find values of each stiffness index for each beat + +% calculate SIs which can be found from existing pts on pulsatile signal (timings) +stiff_inds.delta_t(good_els) = sigs.t(pts.dia(good_els)) - sigs.t(pts.s(good_els)); +stiff_inds.CT(good_els) = sigs.t(pts.s(good_els)) - sigs.t(pts.f1(good_els)); +if ht_provided + stiff_inds.SI(good_els) = sigs.ht./stiff_inds.delta_t(good_els); + stiff_inds.CT_div_h(good_els) = stiff_inds.CT(good_els)./sigs.ht; +end +stiff_inds.prop_s(good_els) = stiff_inds.CT(good_els)./T(good_els); +stiff_inds.t_sys(good_els) = sigs.t(pts.dic(good_els)) - sigs.t(pts.f1(good_els)); +stiff_inds.t_dia(good_els) = sigs.t(pts.f2(good_els)) - sigs.t(pts.dic(good_els)); +stiff_inds.t_ratio(good_els) = (sigs.t(pts.s(good_els)) - sigs.t(pts.f1(good_els)))./stiff_inds.t_sys(good_els); +stiff_inds.prop_delta_t(good_els) = stiff_inds.delta_t(good_els)./T(good_els); +stiff_inds.t_p1_dia(good_els) = sigs.t(pts.dia(good_els)) - sigs.t(pts.p1pk(good_els)); +stiff_inds.t_p2_dia(good_els) = sigs.t(pts.dia(good_els)) - sigs.t(pts.p2pk(good_els)); + +% calculate SIs which can be found from existing pts on pulsatile signal (amplitudes) +stiff_inds.AI(good_els) = 100*(sigs.s(pts.p2pk(good_els)) - sigs.s(pts.p1in(good_els)))./ (sigs.s(pts.s(good_els)) - sigs.s(pts.f1(good_els))); +stiff_inds.AP(good_els) = sigs.s(pts.p2pk(good_els)) - sigs.s(pts.p1in(good_els)); +stiff_inds.RI(good_els) = (sigs.s(pts.dia(good_els)) - sigs.s(pts.f1(good_els))) ./ (sigs.s(pts.s(good_els)) - sigs.s(pts.f1(good_els))); +stiff_inds.RI_p1(good_els) = (sigs.s(pts.dia(good_els)) - sigs.s(pts.f1(good_els))) ./ (sigs.s(pts.p1pk(good_els)) - sigs.s(pts.f1(good_els))); +stiff_inds.RI_p2(good_els) = (sigs.s(pts.dia(good_els)) - sigs.s(pts.f1(good_els))) ./ (sigs.s(pts.p2pk(good_els)) - sigs.s(pts.f1(good_els))); +stiff_inds.ratio_p2_p1(good_els) = (sigs.s(pts.p2pk(good_els)) - sigs.s(pts.f1(good_els))) ./ (sigs.s(pts.p1in(good_els)) - sigs.s(pts.f1(good_els))); + +% calculate additional SIs which require additional pulse wave analysis +for beat_no = 1:length(pts.f1) + + if isnan(pts.s(beat_no)) + continue + end + + % find pulse amplitude + curr_amp = sigs.s(pts.s(beat_no)) - sigs.s(pts.f1(beat_no)); + + % find areas + baseline = linspace(sigs.s(pts.f1(beat_no)), sigs.s(pts.f2(beat_no)), pts.f2(beat_no) - pts.f1(beat_no)+1); baseline = baseline(:); + rel_pts = pts.f1(beat_no) : pts.dic(beat_no); + baseline_pts = rel_pts - pts.f1(beat_no) + 1; + stiff_inds.A1(beat_no) = sum(sigs.s(rel_pts) - baseline(baseline_pts))/( sigs.fs*curr_amp); + rel_pts = pts.dic(beat_no) : pts.f2(beat_no); + baseline_pts = rel_pts - pts.f1(beat_no) + 1; + stiff_inds.A2(beat_no) = sum(sigs.s(rel_pts) - baseline(baseline_pts))/(sigs.fs*curr_amp); + +end +stiff_inds.IPA(good_els) = stiff_inds.A2(good_els) ./ stiff_inds.A1(good_els); +clear beat_no rel_beats + +% calculate SIs from first derivative (amplitudes) +if sum(good_els)>0 + stiff_inds.ms(good_els) = sigs.derivs.first(pts.ms(good_els)); + stiff_inds.ms_div_amp(good_els) = sigs.derivs.first(pts.ms(good_els)) ./ (sigs.s(pts.s(good_els)) - sigs.s(pts.f1(good_els))); +end + +% Calculate SIs from second derivative (amplitudes) +stiff_inds.b_div_a(good_els) = sigs.derivs.second(pts.b(good_els)) ./ sigs.derivs.second(pts.a(good_els)); +stiff_inds.c_div_a(good_els) = sigs.derivs.second(pts.c(good_els)) ./ sigs.derivs.second(pts.a(good_els)); +stiff_inds.d_div_a(good_els) = sigs.derivs.second(pts.d(good_els)) ./ sigs.derivs.second(pts.a(good_els)); +stiff_inds.e_div_a(good_els) = sigs.derivs.second(pts.e(good_els)) ./ sigs.derivs.second(pts.a(good_els)); +stiff_inds.a_div_amp(good_els) = sigs.derivs.second(pts.a(good_els)) ./ (sigs.s(pts.s(good_els)) - sigs.s(pts.f1(good_els))); +stiff_inds.b_div_amp(good_els) = sigs.derivs.second(pts.b(good_els)) ./ (sigs.s(pts.s(good_els)) - sigs.s(pts.f1(good_els))); +stiff_inds.c_div_amp(good_els) = sigs.derivs.second(pts.c(good_els)) ./ (sigs.s(pts.s(good_els)) - sigs.s(pts.f1(good_els))); +stiff_inds.d_div_amp(good_els) = sigs.derivs.second(pts.d(good_els)) ./ (sigs.s(pts.s(good_els)) - sigs.s(pts.f1(good_els))); +stiff_inds.e_div_amp(good_els) = sigs.derivs.second(pts.e(good_els)) ./ (sigs.s(pts.s(good_els)) - sigs.s(pts.f1(good_els))); + +stiff_inds.AGI(good_els) = ( sigs.derivs.second(pts.b(good_els)) - sigs.derivs.second(pts.c(good_els)) - sigs.derivs.second(pts.d(good_els)) - sigs.derivs.second(pts.e(good_els)) )./sigs.derivs.second(pts.a(good_els)); +stiff_inds.AGI_inf(good_els) = ( sigs.derivs.second(pts.b(good_els)) - sigs.derivs.second(pts.e(good_els)) )./sigs.derivs.second(pts.a(good_els)); +stiff_inds.AGI_mod(good_els) = ( sigs.derivs.second(pts.b(good_els)) - sigs.derivs.second(pts.c(good_els)) - sigs.derivs.second(pts.d(good_els)) )./sigs.derivs.second(pts.a(good_els)); + +stiff_inds.t_b_c(good_els) = sigs.t(pts.c(good_els)) - sigs.t(pts.b(good_els)); +stiff_inds.t_b_d(good_els) = sigs.t(pts.d(good_els)) - sigs.t(pts.b(good_els)); + +% Calculate SIs from second derivative (slopes) +pt1.t = sigs.t(pts.b(good_els)); +pt1.v = sigs.derivs.second(pts.b(good_els)); +pt2.t = sigs.t(pts.c(good_els)); +pt2.v = sigs.derivs.second(pts.c(good_els)); +stiff_inds.slope_b_c(good_els) = ((pt2.v - pt1.v)./sigs.derivs.second(pts.a(good_els)))./(pt2.t-pt1.t); +pt2.t = sigs.t(pts.d(good_els)); +pt2.v = sigs.derivs.second(pts.d(good_els)); +stiff_inds.slope_b_d(good_els) = ((pt2.v - pt1.v)./sigs.derivs.second(pts.a(good_els)))./(pt2.t-pt1.t); + +% combined +stiff_inds.IPAD(good_els) = stiff_inds.IPA(good_els) + (sigs.derivs.second(pts.d(good_els)) ./ sigs.derivs.second(pts.a(good_els))); +if sum(good_els)>0 + stiff_inds.k(good_els) = (sigs.derivs.second(pts.s(good_els))) ./ (( sigs.s(pts.s(good_els)) - sigs.s(pts.ms(good_els)) ) ./ (sigs.s(pts.s(good_els)) - sigs.s(pts.f1(good_els))) ); +end + +%% Calculate median values of each stiffness index + +stiff_ind_names = fieldnames(stiff_inds); + +% if selected, then calculate the median CV indices using only high quality beats +if options.exclude_low_quality_data + rel_beats = pulses.quality; +else + rel_beats = true(size(pulses.onsets)); +end +rel_beats = rel_beats(1:end-1); + +% Find median values of each index +for stiff_ind_no = 1 : length(stiff_ind_names) + + % Find median value if there are multiple beats + if length(pts.f1) > 1 + eval(['curr_stiff_ind_data.raw = stiff_inds.' stiff_ind_names{stiff_ind_no} ';']) + curr_stiff_ind_data.v = nanmedian(curr_stiff_ind_data.raw(rel_beats)); + else + eval(['curr_stiff_ind_data.v = stiff_inds.' stiff_ind_names{stiff_ind_no} ';']) + end + + % store result + eval(['stiff_inds.' stiff_ind_names{stiff_ind_no} ' = curr_stiff_ind_data;']) + +end +clear curr_stiff_ind_data stiff_ind_no rel_beats stiff_ind_names + +end + +function S_elim_lf = eliminate_low_freq_from_single_beat(sig, up) + +% Correct for low frequency baseline drift in a single beat + +diff_1 = sig.v(2) - sig.v(1); +desired_val_end = sig.v(1) - diff_1; +correction_line = linspace(0, sig.v(end)-desired_val_end, length(sig.v)); +S_elim_lf.v = sig.v - correction_line'; +S_elim_lf.fs = sig.fs; + +end + +function S_aligned = align_pulse(sig, up) + +% Ensure that signal commences at start of systole + +[~, align_el] = min(sig.v); +S_aligned.v = sig.v([align_el:end, 1:(align_el-1)]); +S_aligned.fs = sig.fs; + +% add on one additional point so that you can define a second onset +S_aligned.v(end+1) = S_aligned.v(1); + +end + +function pulses = generate_pulses_for_single_beat(S_filt) + +% Generate ""pulses"" information for a single-beat input signal + +pulses.onsets = [1, length(S_filt.v)]; +pulses.quality = [true, false]; +[~, pulses.peaks] = max(S_filt.v); +pulses.peaks(end+1) = length(S_filt.v); + +end + +function plot_fiducial_points(sigs, pulses, fid_pts, no_of_pulses, options) +% make plot of individual beat if needed + +sig.v = sigs.s; +sig.fs = sigs.fs; +derivs = sigs.derivs; + +%- setup +paper_size = [600,1050]; +figure('Position', [50,50, paper_size]) +ftsize = 16; lwidth = 2; +pp_annot = 0.8; +rt_annot = -0.02; +sig.t = [0:length(sig.v)-1]/sig.fs; + +if options.plot_third_deriv + y_inc = 0.23; + n_sub = 4; + ftsize = ftsize + 2; +else + y_inc = 0.31; + n_sub = 3; +end +y_offset = 0.08; + +%- plot sig +h_b(1) = subplot('Position', [0.21,y_offset+(n_sub-1)*y_inc,0.78,y_inc-0.01]); + +% identify relevant beat +if strcmp(no_of_pulses, 'single') + beat_no = 1; +elseif length(fid_pts.f2) < 101 + beat_no = 2; +else + beat_no = 100; +end +rel_els = fid_pts.f1(beat_no) : fid_pts.f2(beat_no); +curr_sig.t = sig.t(rel_els)-sig.t(rel_els(1)); +curr_sig.sig = subtract_baseline(sig.v(rel_els)); +[curr_sig.sig, scale_factor] = normalise(curr_sig.sig); + +% plot baseline curve +plot(curr_sig.t, curr_sig.sig, 'LineWidth', lwidth); hold on, + +% % add dashed lines +% plot(sig.t(fid_pts(1))*[1,1], [rt_annot, sig.v(fid_pts(1))], '--', 'color', 0.6*ones(1,3)) +% plot(sig.t(fid_pts(2))*[1,1], [rt_annot, sig.v(fid_pts(2))], '--', 'color', 0.6*ones(1,3)) +% plot([sig.t(fid_pts(1)),pp_annot], sig.v(fid_pts(1))*ones(1,2), '--', 'color', 0.6*ones(1,3)) +% plot([sig.t(fid_pts(2)),pp_annot], sig.v(fid_pts(2))*ones(1,2), '--', 'color', 0.6*ones(1,3)) + +% plot salient points +pt_names = {'dia', 'dic', 's', 'p1', 'p2'}; +hspace0 = 0; +for pt_no = 1 : length(pt_names) + eval(['curr_pt.el = fid_pts.' pt_names{pt_no} '(beat_no) - fid_pts.f1(beat_no)+1;']); + if isnan(curr_pt.el) + continue + end + + % plot point + curr_pt.v = curr_sig.sig(curr_pt.el); + curr_pt.t = curr_sig.t(curr_pt.el); + plot(curr_pt.t, curr_pt.v, 'or') + + % annotate point + curr_text = pt_names{pt_no}; + vspace0 = 0.08; + switch curr_text + case {'dia','p2'} + hspace0 = 0.04; + if (strcmp(curr_text, 'p2') || strcmp(curr_text, 'p2in')) && curr_pt.el < (fid_pts.s(beat_no) - fid_pts.f1(beat_no)+1) + hspace0 = -0.04; + elseif (strcmp(curr_text, 'p1') || strcmp(curr_text, 'p1in')) + hspace0 = 0; + end + case 'dic' + hspace0 = -0.01; + vspace0 = -0.08; + case {'f1', 'p1','p1in'} + hspace0 = -0.04; + case 's' + hspace0 = 0; + end + text(curr_sig.t(curr_pt.el)+hspace0, curr_sig.sig(curr_pt.el)+vspace0 , curr_text,'FontSize', ftsize, 'Color', 'r', 'HorizontalAlignment', 'center'); + +end + +% set limits +ylim([-0.08, 1.2]) +curr_range = range(curr_sig.t); +xlim([curr_sig.t(1)-0.1*curr_range, curr_sig.t(end)+0.1*curr_range]) + +% set labels +ylab = ylabel('PW', 'FontSize', ftsize, 'Rotation', 0); +set(ylab, 'Units', 'Normalized', 'Position', [-0.13, 0.5, 0]); +set(gca, 'FontSize', ftsize -2, 'YTick', []) +set(gca, 'XTick', 0:0.25:1, 'XTickLabel', {}) +box off + +%- plot first derivative +h_b(2) = subplot('Position', [0.21,y_offset+(n_sub-2)*y_inc,0.78,y_inc - 0.01]); + +curr_sig.derivs.first = derivs.first(rel_els)/scale_factor; + +% Plot x-axis +plot([-10, 10], [0,0], '--k'); hold on + +% plot baseline curve +plot(curr_sig.t, curr_sig.derivs.first, 'LineWidth', lwidth); hold on, + +% plot salient points +pt_names = {'ms', 'dia'}; +curr_range = range(curr_sig.derivs.first); +vspace0 = 0.08*curr_range; +hspace0 = 0.05; +for pt_no = 1 : length(pt_names) + eval(['curr_fid_pt = fid_pts.' pt_names{pt_no} '(beat_no);']) + if isnan(curr_fid_pt) + continue + end + curr_pt.el = curr_fid_pt - fid_pts.f1(beat_no)+1; + if isnan(curr_pt.el) + continue + end + + % plot point + curr_pt.v = curr_sig.derivs.first(curr_pt.el); + curr_pt.t = curr_sig.t(curr_pt.el); + plot(curr_pt.t, curr_pt.v, 'or') + + % annotate point + curr_text = pt_names{pt_no}; + text(curr_sig.t(curr_pt.el)+hspace0, curr_sig.derivs.first(curr_pt.el)+vspace0 , curr_text,'FontSize', ftsize, 'Color', 'r', 'HorizontalAlignment', 'center'); + +end + +% set limits +curr_range = range(curr_sig.t); +xlim([curr_sig.t(1)-0.1*curr_range, curr_sig.t(end)+0.1*curr_range]) +ylims = ylim; curr_range = range(curr_sig.derivs.first); +ylim([min(curr_sig.derivs.first)-0.05*curr_range, max(curr_sig.derivs.first)+0.15*curr_range]) +%ylim([-0.05 0.15]) + +% set labels +ylab = ylabel({'1st','derivative'}, 'FontSize', ftsize, 'Rotation', 0); +set(ylab, 'Units', 'Normalized', 'Position', [-0.13, 0.5, 0]); +set(gca, 'FontSize', ftsize -2, 'YTick', []) +set(gca, 'XTick', 0:0.25:1, 'XTickLabel', {}) +set(gca, 'YTick', 0, 'YTickLabel', {'0'}); +box off + + +%- plot Second derivative +h_b(3) = subplot('Position', [0.21,y_offset+(n_sub-3)*y_inc,0.78,y_inc - 0.01]); + +curr_sig.derivs.second = derivs.second(rel_els)/scale_factor; + +% Plot x-axis +plot([-10, 10], [0,0], '--k'); hold on + +% plot baseline curve +curr_color = 0.4*0.5*[1,2,1]; +plot(curr_sig.t, curr_sig.derivs.second, 'LineWidth', lwidth); hold on, + +% plot salient points +pt_names = {'a', 'b', 'c', 'd', 'e', 'f'}; +curr_range = range(curr_sig.derivs.second); +vspace_const = 0.08; +hspace0 = 0; +for pt_no = 1 : length(pt_names) + eval(['curr_pt.el = fid_pts.' pt_names{pt_no} '(beat_no) - fid_pts.f1(beat_no)+1;']); + if isnan(curr_pt.el) + continue + end + + % plot point + curr_pt.v = curr_sig.derivs.second(curr_pt.el); + curr_pt.t = curr_sig.t(curr_pt.el); + plot(curr_pt.t, curr_pt.v, 'or') + + % annotate point + curr_text = pt_names{pt_no}; + switch curr_text + case {'a','c', 'e'} + vspace0 = (1.3*vspace_const)*curr_range; + case {'b', 'd', 'f'} + vspace0 = -1*vspace_const*curr_range; + end + text(curr_sig.t(curr_pt.el), curr_sig.derivs.second(curr_pt.el)+vspace0 , curr_text,'FontSize', ftsize, 'Color', 'r', 'HorizontalAlignment', 'center'); + +end + +% set limits +curr_range = range(curr_sig.t); +xlim([curr_sig.t(1)-0.1*curr_range, curr_sig.t(end)+0.1*curr_range]) +ylims = ylim; curr_range = range(curr_sig.derivs.second); +ylim([min(curr_sig.derivs.second)-0.05*curr_range, max(curr_sig.derivs.second)+0.15*curr_range]) +%ylim([-0.025 0.025]) + +% set labels +ylab = ylabel({'2nd','derivative'}, 'FontSize', ftsize, 'Rotation', 0); +set(ylab, 'Units', 'Normalized', 'Position', [-0.13, 0.5, 0]); +set(gca, 'FontSize', ftsize -2, 'XTick', 0:0.25:1, 'YTick', []) +box off +if ~options.plot_third_deriv + xlabel('Time [s]', 'FontSize', ftsize) +else + set(gca, 'XTickLabel', {}) +end +set(gca, 'YTick', 0, 'YTickLabel', {'0'}); + +if options.plot_third_deriv +%- plot Third derivative +h_b(4) = subplot('Position', [0.21,y_offset+(n_sub-4)*y_inc,0.78,y_inc-0.01]); + +curr_sig.derivs.third = derivs.third(rel_els)/scale_factor; + +% Plot x-axis +plot([-10, 10], [0,0], '--k'); hold on + +% plot baseline curve +curr_color = 0.4*0.5*[1,2,1]; +plot(curr_sig.t, curr_sig.derivs.third, 'LineWidth', lwidth); hold on, + +% plot salient points +pt_names = {'p1', 'p2'}; +curr_range = range(curr_sig.derivs.third); +vspace_const = 0.08; +hspace0 = 0; +for pt_no = 1 : length(pt_names) + eval(['curr_pt.el = fid_pts.' pt_names{pt_no} '(beat_no) - fid_pts.f1(beat_no)+1;']); + if isnan(curr_pt.el) + continue + end + + % plot point + curr_pt.v = curr_sig.derivs.third(curr_pt.el); + curr_pt.t = curr_sig.t(curr_pt.el); + plot(curr_pt.t, curr_pt.v, 'or') + + % annotate point + curr_text = pt_names{pt_no}; + switch curr_text + case {'p1'} + vspace0 = vspace_const*curr_range; + case {'p2'} + vspace0 = -1*vspace_const*curr_range; + end + text(curr_sig.t(curr_pt.el), curr_sig.derivs.third(curr_pt.el)+vspace0 , curr_text,'FontSize', ftsize, 'Color', 'r', 'HorizontalAlignment', 'center'); + +end + +% set limits +curr_range = range(curr_sig.t); +xlim([curr_sig.t(1)-0.1*curr_range, curr_sig.t(end)+0.1*curr_range]) +ylims = ylim; curr_range = range(curr_sig.derivs.third); +ylim([min(curr_sig.derivs.third)-0.05*curr_range, max(curr_sig.derivs.third)+0.15*curr_range]) +%ylim([-0.025 0.025]) + +% set labels +xlabel('Time [s]', 'FontSize', ftsize) +ylab = ylabel({'3rd','derivative'}, 'FontSize', ftsize, 'Rotation', 0); +set(ylab, 'Units', 'Normalized', 'Position', [-0.13, 0.5, 0]); +set(gca, 'FontSize', ftsize -2, 'XTick', 0:0.25:1, 'YTick', []) +box off +end + + +linkaxes(h_b, 'x') +shg + +if ~isempty(options.save_folder) + savepath = [options.save_folder, options.save_file, 'fid_pts']; + set(gcf,'color','w'); + set(gcf,'PaperUnits','centimeters'); + set(gcf,'PaperSize', [paper_size(1), paper_size(2)]./40); + set(gcf,'PaperPosition',[0 0 paper_size(1) paper_size(2)]./40); + print(gcf,'-dpdf',savepath) +end +shg + +end + +function plot_cv_inds(sigs, pulses, fid_pts, cv_inds, no_of_pulses, options) +% make plot of individual beat + + +sig.v = sigs.s; +sig.fs = sigs.fs; +derivs = sigs.derivs; + +%- setup figure +paper_size = [600,1050]; +figure('Position', [550,50, paper_size]) +fig_props.ftsize = 16; fig_props.lwidth = 2; +pp_annot = 0.8; +rt_annot = -0.02; +sig.t = [0:length(sig.v)-1]/sig.fs; + +if options.plot_third_deriv + fig_props.y_inc = 0.23; + fig_props.n_sub = 4; + fig_props.ftsize = fig_props.ftsize + 2; +else + fig_props.y_inc = 0.31; + fig_props.n_sub = 3; +end +fig_props.y_offset = 0.08; +fig_props.plot_third_deriv = options.plot_third_deriv; + +%- identify relevant beat +if strcmp(no_of_pulses, 'single') + beat_no = 1; +else + beat_no = 4; +end +rel_els = fid_pts.f1(beat_no) : fid_pts.f2(beat_no); +curr_sig.t = sig.t(rel_els)-sig.t(rel_els(1)); +curr_sig.sig = subtract_baseline(sig.v(rel_els)); +[curr_sig.sig, scale_factor] = normalise(curr_sig.sig); +curr_sig.derivs.first = derivs.first(rel_els)/scale_factor; +curr_sig.derivs.second = derivs.second(rel_els)/scale_factor; +curr_sig.derivs.third = derivs.third(rel_els)/scale_factor; + +% Plot signal + +pts_to_plot = {'s', 'dic', 'dia'}; +include_time_axis = 1; +plot_sig(curr_sig, fid_pts, cv_inds, fig_props, beat_no, pts_to_plot, include_time_axis) +% add dashed lines +% delta T +plot(curr_sig.t(fid_pts.s)*[1,1], [rt_annot, curr_sig.sig(fid_pts.s)], '--', 'color', 0.6*ones(1,3)) +plot(curr_sig.t(fid_pts.dia)*[1,1], [rt_annot, curr_sig.sig(fid_pts.dia)], '--', 'color', 0.6*ones(1,3)) +% RI +plot([curr_sig.t(fid_pts.s),curr_sig.t(fid_pts.f2)], 0*ones(1,2), '--', 'color', 0.6*ones(1,3)) +plot([curr_sig.t(fid_pts.dia),curr_sig.t(fid_pts.f2)], curr_sig.sig(fid_pts.dia)*ones(1,2), '--', 'color', 0.6*ones(1,3)) +% t_dia +plot(curr_sig.t(fid_pts.dic)*ones(1,2), [curr_sig.sig(fid_pts.dic), 0.98], '--', 'color', 0.6*ones(1,3)) +plot(curr_sig.t(fid_pts.f2)*ones(1,2), [0, 0.98], '--', 'color', 0.6*ones(1,3)) + +% - DeltaT +normalised1 = coords_to_pos(curr_sig.t(fid_pts.s), 0); +normalised2 = coords_to_pos(curr_sig.t(fid_pts.dia), 0); +ah = annotation('doublearrow',[normalised1(1),normalised2(1)],[normalised1(2),normalised2(2)]); +text(mean([curr_sig.t(fid_pts.s),curr_sig.t(fid_pts.s),curr_sig.t(fid_pts.dia)]), 0.05, '\DeltaT','FontSize', fig_props.ftsize, 'Color', 'k', 'HorizontalAlignment', 'center', 'VerticalAlignment', 'bottom'); +% - RI +t_val = curr_sig.t(end) + 0.05*range(curr_sig.t); +normalised1 = coords_to_pos(curr_sig.t(end), 0); +normalised2 = coords_to_pos(curr_sig.t(end), curr_sig.sig(fid_pts.dia)); +ah = annotation('doublearrow',[normalised1(1),normalised2(1)],[normalised1(2),normalised2(2)]); +text(t_val+0.02, curr_sig.sig(fid_pts.dia)/2, 'RI','FontSize', fig_props.ftsize, 'Color', 'k','HorizontalAlignment','center','VerticalAlignment', 'middle'); +% - CT +normalised1 = coords_to_pos(0, 0); +normalised2 = coords_to_pos(curr_sig.t(fid_pts.s), 0); +ah = annotation('doublearrow',[normalised1(1),normalised2(1)],[normalised1(2),normalised2(2)]); +text(curr_sig.t(fid_pts.s)/1.6, 0.0+0.05, 'CT','FontSize', fig_props.ftsize, 'Color', 'k','HorizontalAlignment','center','VerticalAlignment', 'bottom'); +% - t_dia +t_val = mean([curr_sig.t(fid_pts.dic), curr_sig.t(fid_pts.f2)]); +normalised1 = coords_to_pos(curr_sig.t(fid_pts.dic), 0.98); +normalised2 = coords_to_pos(curr_sig.t(fid_pts.f2), 0.98); +ah = annotation('doublearrow',[normalised1(1),normalised2(1)],[normalised1(2),normalised2(2)]); +text(t_val, 0.98+0.02, 't_{dia}','FontSize', fig_props.ftsize, 'Color', 'k','HorizontalAlignment','center','VerticalAlignment', 'bottom'); + +% Plot first derivative + +pts_to_plot = {'ms'}; +plot_first_deriv(curr_sig, fid_pts, cv_inds, fig_props, beat_no, pts_to_plot) + +% add dashed lines +plot([-0.01, curr_sig.t(fid_pts.ms)], curr_sig.derivs.first(fid_pts.ms)*ones(1,2), '--', 'color', 0.6*ones(1,3)) + +% - ms +t_val = -0.015; +normalised1 = coords_to_pos(t_val, 0); +normalised2 = coords_to_pos(t_val, curr_sig.derivs.first(fid_pts.ms)); +ah = annotation('doublearrow',[normalised1(1),normalised2(1)],[normalised1(2),normalised2(2)]); +text(1.2*t_val, 0.5*curr_sig.derivs.first(fid_pts.ms), 'ms','FontSize', fig_props.ftsize, 'Color', 'k','HorizontalAlignment','right','VerticalAlignment', 'bottom'); + +% Plot second derivative + +pts_to_plot = {'b', 'd'}; +plot_second_deriv(curr_sig, fid_pts, cv_inds, fig_props, beat_no, pts_to_plot, options) + +% add line +plot([curr_sig.t(fid_pts.b), curr_sig.t(fid_pts.d)], [curr_sig.derivs.second(fid_pts.b), curr_sig.derivs.second(fid_pts.d)], '-k', 'LineWidth', 2) +text(curr_sig.t(fid_pts.b), 0.75*max(curr_sig.derivs.second), 'slope_{b-d}','FontSize', fig_props.ftsize, 'Color', 'k','HorizontalAlignment','left'); + +if options.plot_third_deriv + pts_to_plot = {''}; + plot_third_deriv(curr_sig, fid_pts, cv_inds, fig_props, beat_no, pts_to_plot) +end + +if ~isempty(options.save_folder) + savepath = [options.save_folder, options.save_file, 'cv_inds']; + set(gcf,'color','w'); + set(gcf,'PaperUnits','centimeters'); + set(gcf,'PaperSize', [paper_size(1), paper_size(2)]./40); + set(gcf,'PaperPosition',[0 0 paper_size(1) paper_size(2)]./40); + print(gcf,'-dpdf',savepath) +end +shg + +end + +function make_demo_plot(sig, derivs, pulses, fid_pts, cv_inds, no_of_pulses, options) +% make demo plot of identifying fiducial points and taking feature +% measurements + +%- setup +paper_size = [1000,350]; +figure('Position', [50,50, paper_size]) +ftsize = 13; lwidth = 2; +pp_annot = 0.8; +rt_annot = -0.02; +sig.t = [0:length(sig.v)-1]/sig.fs; + +%% Plot Fiducial Points + +subplot(1,2,1) + +% identify relevant beat +if strcmp(no_of_pulses, 'single') + beat_no = 1; +elseif length(fid_pts.f2) < 101 + beat_no = 2; +else + beat_no = 100; +end +rel_els = fid_pts.f1(beat_no) : fid_pts.f2(beat_no); +curr_sig.t = sig.t(rel_els)-sig.t(rel_els(1)); +curr_sig.sig = subtract_baseline(sig.v(rel_els)); +[curr_sig.sig, scale_factor] = normalise(curr_sig.sig); + +% plot baseline curve +if strcmp(options.demo_plot_wave, '2nd_deriv') + rel_sig = derivs.second; + init_vspace = 0.05*range(rel_sig); +else + rel_sig = curr_sig.sig; + init_vspace = 0.08; +end +plot([-10, 10], [0,0], '--k'), hold on +plot(curr_sig.t, rel_sig, 'LineWidth', lwidth); hold on, + +% plot salient points +if strcmp(options.demo_plot_wave, '2nd_deriv') + pt_names = {'a', 'b', 'c', 'd', 'e'}; +else + pt_names = {'dia', 'dic', 's', 'f1', 'f2'}; +end +hspace0 = 0; +for pt_no = 1 : length(pt_names) + eval(['curr_pt.el = fid_pts.' pt_names{pt_no} '(beat_no) - fid_pts.f1(beat_no)+1;']); + if isnan(curr_pt.el) + continue + end + + % plot point + curr_pt.v = rel_sig(curr_pt.el); + curr_pt.t = curr_sig.t(curr_pt.el); + plot(curr_pt.t, curr_pt.v, 'or') + + % annotate point + curr_text = pt_names{pt_no}; + vspace0 = init_vspace; + switch curr_text + case {'a', 'c', 'e'} + hspace0 = 0; + case {'b', 'd'} + hspace0 = 0; + vspace0 = -1*init_vspace; + case {'dia','p2'} + hspace0 = 0.04; + if strcmp(curr_text, 'p2') && curr_pt.el < (fid_pts.s(beat_no) - fid_pts.f1(beat_no)+1) + hspace0 = -0.04; + elseif strcmp(curr_text, 'p2') + hspace0 = 0; + end + case 'dic' + hspace0 = -0.01; + vspace0 = -1*init_vspace; + case {'f1', 'p1'} + hspace0 = -0.04; + case 'f2' + hspace0 = 0.04; + case 's' + hspace0 = 0; + end + text(curr_sig.t(curr_pt.el)+hspace0, rel_sig(curr_pt.el)+vspace0 , curr_text,'FontSize', ftsize, 'Color', 'r', 'HorizontalAlignment', 'center'); + +end + +% set limits +if strcmp(options.demo_plot_wave, '2nd_deriv') + temp = [min(rel_sig), max(rel_sig)]; + ylim([temp(1) - 0.15*range(temp), temp(2)+0.15*range(temp)]) +else + ylim([-0.08, 1.2]) +end +curr_range = range(curr_sig.t); +xlim([curr_sig.t(1)-0.1*curr_range, curr_sig.t(end)+0.1*curr_range]) + +% set labels +if strcmp(options.demo_plot_wave, '2nd_deriv') + ylab = ylabel('PW''''', 'FontSize', ftsize, 'Rotation', 0); +else + ylab = ylabel({'PW', '[au]'}, 'FontSize', ftsize, 'Rotation', 0); +end +set(ylab, 'Units', 'Normalized', 'Position', [-0.13, 0.5, 0]); +set(gca, 'FontSize', ftsize -2, 'YTick', []) +xlabel('Time [s]', 'FontSize', ftsize) +box off + +%% Plot CV Indices + +subplot(1,2,2) + +if strcmp(options.demo_plot_wave, '2nd_deriv') + rel_sig = rel_sig/rel_sig(fid_pts.a); +end + +% Plot signal +plot([-10, 10], [0,0], '--k'), hold on +plot(curr_sig.t, rel_sig, 'LineWidth', lwidth); hold on, + +% plot salient points +hspace0 = 0; +for pt_no = 1 : length(pt_names) + eval(['curr_pt.el = fid_pts.' pt_names{pt_no} '(beat_no) - fid_pts.f1(beat_no)+1;']); + if isnan(curr_pt.el) + continue + end + + % plot point + curr_pt.v = rel_sig(curr_pt.el); + curr_pt.t = curr_sig.t(curr_pt.el); + plot(curr_pt.t, curr_pt.v, 'or') + +end + +% set limits +if strcmp(options.demo_plot_wave, '2nd_deriv') + temp = [min(rel_sig), max(rel_sig)]; + ylims = [temp(1) - 0.15*range(temp), temp(2)+0.15*range(temp)]; +else + ylims = [-0.08, 1.2]; +end +ylim(ylims) +curr_range = range(curr_sig.t); +xlims = [curr_sig.t(1)-0.1*curr_range, curr_sig.t(end)+0.1*curr_range]; +xlim(xlims) + +% add dashed lines +% - a +%plot(curr_sig.t(fid_pts.a)*[1,1], [0, rel_sig(fid_pts.a)], '--', 'color', 0.6*ones(1,3)) + +y_offset = 0.07*range(ylim); +y_temp = 0.1*y_offset; +% - b +normalised1 = coords_to_pos(curr_sig.t(fid_pts.b), 0); +normalised2 = coords_to_pos(curr_sig.t(fid_pts.b), rel_sig(fid_pts.b)); +ah = annotation('doublearrow',[normalised1(1),normalised2(1)],[normalised1(2),normalised2(2)]+y_temp); +ylim(ylims), xlim(xlims) +text(curr_sig.t(fid_pts.b), -y_offset+rel_sig(fid_pts.b), 'b/a','FontSize', ftsize, 'Color', 'k', 'HorizontalAlignment', 'center'); +ylim(ylims), xlim(xlims) +% - d +normalised1 = coords_to_pos(curr_sig.t(fid_pts.d), 0); +normalised2 = coords_to_pos(curr_sig.t(fid_pts.d), rel_sig(fid_pts.d)); +ah = annotation('doublearrow',[normalised1(1),normalised2(1)],[normalised1(2),normalised2(2)]+y_temp); +ylim(ylims), xlim(xlims) +text(curr_sig.t(fid_pts.d), -y_offset+rel_sig(fid_pts.d), 'd/a','FontSize', ftsize, 'Color', 'k', 'HorizontalAlignment', 'center'); +ylim(ylims), xlim(xlims) +% - e +normalised1 = coords_to_pos(curr_sig.t(fid_pts.e), 0); +normalised2 = coords_to_pos(curr_sig.t(fid_pts.e), rel_sig(fid_pts.e)); +ah = annotation('doublearrow',[normalised1(1),normalised2(1)],[normalised1(2),normalised2(2)]+y_temp); +ylim(ylims), xlim(xlims) +text(curr_sig.t(fid_pts.e), y_offset+rel_sig(fid_pts.e), 'e/a','FontSize', ftsize, 'Color', 'k', 'HorizontalAlignment', 'center'); +ylim(ylims), xlim(xlims) + +% set labels +ylab = ylabel('PW''''/a', 'FontSize', ftsize, 'Rotation', 0); +set(ylab, 'Units', 'Normalized', 'Position', [-0.13, 0.5, 0]); +set(gca, 'FontSize', ftsize -2, 'YTick', []) +xlabel('Time [s]', 'FontSize', ftsize) +box off + +%% Save Figure + +if ~isempty(options.save_folder) + savepath = [options.save_folder, options.save_file, 'demo_plot']; + set(gcf,'color','w'); + set(gcf,'PaperUnits','centimeters'); + set(gcf,'PaperSize', [paper_size(1), paper_size(2)]./40); + set(gcf,'PaperPosition',[0 0 paper_size(1) paper_size(2)]./40); + print(gcf,'-dpdf',savepath) + print(gcf,'-depsc',savepath) +end + +end + +function normalised = coords_to_pos(x_coord, y_coord) + +pos = get(gca, 'Position'); +normalised(1) = (x_coord - min(xlim))/diff(xlim) * pos(3) + pos(1); +normalised(2) = (y_coord - min(ylim))/diff(ylim) * pos(4) + pos(2); + +end + +function plot_sig(curr_sig, fid_pts, cv_inds, fig_props, beat_no, pts_to_plot, include_time_axis) +%- plot sig + +if nargin < 6 + pts_to_plot = {'dia', 'dic', 's', 'p1', 'p2'}; +end + +h_b(1) = subplot('Position', [0.21,fig_props.y_offset+(fig_props.n_sub-1)*fig_props.y_inc,0.78,fig_props.y_inc-0.01]); + +plot(curr_sig.t, curr_sig.sig, 'LineWidth', fig_props.lwidth); hold on, + +% plot salient points +pt_names = intersect({'dia', 'dic', 's', 'p1', 'p2'}, pts_to_plot); +for pt_no = 1 : length(pt_names) + eval(['curr_pt.el = fid_pts.' pt_names{pt_no} '(beat_no) - fid_pts.f1(beat_no)+1;']); + if isnan(curr_pt.el) + continue + end + + % plot point + curr_pt.v = curr_sig.sig(curr_pt.el); + curr_pt.t = curr_sig.t(curr_pt.el); + plot(curr_pt.t, curr_pt.v, 'or') + + % annotate point + curr_text = pt_names{pt_no}; + vspace0 = 0.08; + hspace0 = 0; + switch curr_text + case {'dia','p2'} + hspace0 = 0.04; + if strcmp(curr_text, 'p2') && curr_pt.el < (fid_pts.s(beat_no) - fid_pts.f1(beat_no)+1) + hspace0 = -0.04; + end + vspace0 = 0.11; + case 'dic' + hspace0 = 0; + vspace0 = -0.11; + case {'f1', 'p1'} + hspace0 = -0.04; + case 's' + hspace0 = 0; + vspace0 = 0.11; + end + text(curr_sig.t(curr_pt.el)+hspace0, curr_sig.sig(curr_pt.el)+vspace0 , curr_text,'FontSize', fig_props.ftsize, 'Color', 'r', 'HorizontalAlignment', 'center'); + +end + +% set limits +ylim([-0.08, 1.2]) +curr_range = range(curr_sig.t); +xlim([curr_sig.t(1)-0.1*curr_range, curr_sig.t(end)+0.1*curr_range]) + +% set labels +ylab = ylabel('PW', 'FontSize', fig_props.ftsize, 'Rotation', 0); +set(ylab, 'Units', 'Normalized', 'Position', [-0.13, 0.5, 0]); +set(gca, 'FontSize', fig_props.ftsize -2, 'YTick', []) +if include_time_axis + xlabel('Time [s]', 'FontSize', fig_props.ftsize) + set(gca, 'XTick', 0:0.25:1) +else + set(gca, 'XTick', 0:0.25:1, 'XTickLabel', {}) +end +box off + +end + +function plot_first_deriv(curr_sig, fid_pts, cv_inds, fig_props, beat_no, pts_to_plot) +%- plot first derivative + +if nargin < 6 + pts_to_plot = {'ms' , 'dia'}; +end + +h_b(2) = subplot('Position', [0.21,fig_props.y_offset+(fig_props.n_sub-2)*fig_props.y_inc,0.78,fig_props.y_inc-0.01]); + + +% Plot x-axis +plot([-10, 10], [0,0], '--k'); hold on + +% plot first derivative +plot(curr_sig.t, curr_sig.derivs.first, 'LineWidth', fig_props.lwidth); hold on, + +% plot salient points +pt_names = intersect({'ms', 'dia'}, pts_to_plot); +curr_range = range(curr_sig.derivs.first); +vspace0 = 0.08*curr_range; +hspace0 = 0.05; +for pt_no = 1 : length(pt_names) + eval(['curr_pt.el = fid_pts.' pt_names{pt_no} '(beat_no) - fid_pts.f1(beat_no)+1;']); + if isnan(curr_pt.el) + continue + end + + % plot point + curr_pt.v = curr_sig.derivs.first(curr_pt.el); + curr_pt.t = curr_sig.t(curr_pt.el); + plot(curr_pt.t, curr_pt.v, 'or') + + % annotate point + curr_text = pt_names{pt_no}; + text(curr_sig.t(curr_pt.el)+hspace0, curr_sig.derivs.first(curr_pt.el)+vspace0 , curr_text,'FontSize', fig_props.ftsize, 'Color', 'r', 'HorizontalAlignment', 'center'); + +end + +% set limits +curr_range = range(curr_sig.t); +xlim([curr_sig.t(1)-0.1*curr_range, curr_sig.t(end)+0.1*curr_range]) +ylims = ylim; curr_range = range(curr_sig.derivs.first); +ylim([min(curr_sig.derivs.first)-0.05*curr_range, max(curr_sig.derivs.first)+0.15*curr_range]) + +% set labels +ylab = ylabel({'1st','derivative'}, 'FontSize', fig_props.ftsize, 'Rotation', 0); +set(ylab, 'Units', 'Normalized', 'Position', [-0.13, 0.5, 0]); +set(gca, 'FontSize', fig_props.ftsize -2, 'YTick', 0, 'YTickLabel', {'0'}) +set(gca, 'XTick', 0:0.25:1, 'XTickLabel', {}) + +box off + +end + +function plot_second_deriv(curr_sig, fid_pts, cv_inds, fig_props, beat_no, pts_to_plot, options) + +%- plot Second derivative + +if nargin < 6 + pts_to_plot = {'a', 'b', 'c', 'd', 'e', 'f'}; +end + +h_b(3) = subplot('Position', [0.21,fig_props.y_offset+(fig_props.n_sub-3)*fig_props.y_inc,0.78,fig_props.y_inc-0.01]); + + +% Plot x-axis +plot([-10, 10], [0,0], '--k'); hold on + +% plot second derivative +plot(curr_sig.t, curr_sig.derivs.second, 'LineWidth', fig_props.lwidth); hold on, + +% plot salient points +pt_names = intersect({'a', 'b', 'c', 'd', 'e', 'f'}, pts_to_plot); +curr_range = range(curr_sig.derivs.second); +vspace_const = 0.08; +hspace0 = 0; +for pt_no = 1 : length(pt_names) + eval(['curr_pt.el = fid_pts.' pt_names{pt_no} '(beat_no) - fid_pts.f1(beat_no)+1;']); + if isnan(curr_pt.el) + continue + end + + % plot point + curr_pt.v = curr_sig.derivs.second(curr_pt.el); + curr_pt.t = curr_sig.t(curr_pt.el); + plot(curr_pt.t, curr_pt.v, 'or') + + % annotate point + curr_text = pt_names{pt_no}; + switch curr_text + case {'a','c', 'e'} + vspace0 = (1.35*vspace_const)*curr_range; + case {'b', 'd', 'f'} + vspace0 = -1.2*vspace_const*curr_range; + end + text(curr_sig.t(curr_pt.el), curr_sig.derivs.second(curr_pt.el)+vspace0 , curr_text,'FontSize', fig_props.ftsize, 'Color', 'r', 'HorizontalAlignment', 'center'); + +end + +% set limits +curr_range = range(curr_sig.t); +xlim([curr_sig.t(1)-0.1*curr_range, curr_sig.t(end)+0.1*curr_range]) +ylims = ylim; curr_range = range(curr_sig.derivs.second); +ylim([min(curr_sig.derivs.second)-0.05*curr_range, max(curr_sig.derivs.second)+0.15*curr_range]) + +% set labels +ylab = ylabel({'2nd', 'derivative'}, 'FontSize', fig_props.ftsize, 'Rotation', 0); +set(ylab, 'Units', 'Normalized', 'Position', [-0.13, 0.5, 0]); +set(gca, 'FontSize', fig_props.ftsize -2, 'XTick', 0:0.25:1, 'YTick', 0, 'YTickLabel', {'0'}) +if options.plot_third_deriv + set(gca, 'XTickLabel', {}) +else + xlabel('Time [s]', 'FontSize', fig_props.ftsize) +end +box off + +end + +function plot_third_deriv(curr_sig, fid_pts, cv_inds, fig_props, beat_no, pts_to_plot) + +%- plot Third derivative + +if nargin < 6 + pts_to_plot = {'p1', 'p2'}; +end + +h_b(4) = subplot('Position', [0.21,fig_props.y_offset+(fig_props.n_sub-4)*fig_props.y_inc,0.78,fig_props.y_inc-0.01]); + +% Plot x-axis +plot([-10, 10], [0,0], '--k'); hold on + +% plot third derivative +curr_sig.derivs.third(1:8) = nan; +curr_sig.derivs.third(end-7:end) = nan; +plot(curr_sig.t, curr_sig.derivs.third, 'LineWidth', fig_props.lwidth); hold on, + +% plot salient points +pt_names = intersect({'p1', 'p2'}, pts_to_plot); +curr_range = range(curr_sig.derivs.third); +vspace_const = 0.11; +hspace0 = 0; +for pt_no = 1 : length(pt_names) + eval(['curr_pt.el = fid_pts.' pt_names{pt_no} '(beat_no) - fid_pts.f1(beat_no)+1;']); + if isnan(curr_pt.el) + continue + end + + % plot point + curr_pt.v = curr_sig.derivs.third(curr_pt.el); + curr_pt.t = curr_sig.t(curr_pt.el); + plot(curr_pt.t, curr_pt.v, 'or') + + % annotate point + curr_text = pt_names{pt_no}; + switch curr_text + case {'p1'} + vspace0 = vspace_const*curr_range; + case {'p2'} + vspace0 = -1*vspace_const*curr_range; + end + text(curr_sig.t(curr_pt.el), curr_sig.derivs.third(curr_pt.el)+vspace0 , curr_text,'FontSize', fig_props.ftsize, 'Color', 'r', 'HorizontalAlignment', 'center'); + +end + +% set limits +curr_range = range(curr_sig.t); +xlim([curr_sig.t(1)-0.1*curr_range, curr_sig.t(end)+0.1*curr_range]) +ylims = ylim; curr_range = range(curr_sig.derivs.third); +ylim([min(curr_sig.derivs.third)-0.05*curr_range, max(curr_sig.derivs.third)+0.15*curr_range]) + +% set labels +xlabel('Time [s]', 'FontSize', fig_props.ftsize) +ylab = ylabel({'3rd', 'derivative'}, 'FontSize', fig_props.ftsize, 'Rotation', 0); +set(ylab, 'Units', 'Normalized', 'Position', [-0.13, 0.5, 0]); +set(gca, 'FontSize', fig_props.ftsize -2, 'XTick', 0:0.25:1, 'YTick', []) +box off + +end + +function subtracted = subtract_baseline(sig) + +baseline = linspace(sig(1),sig(end),length(sig)); + +subtracted = sig(:) - baseline(:); + +end + +function [norm, scale_factor] = normalise(sig) + +norm = sig - min(sig); +scale_factor = max(norm); +norm = norm / scale_factor; + +end","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/Additional Functions/Harmonics.m",".m","3895","159","%::::::::::::::::::::::::::::::::% +% HARMONICS OF AN INPUT FUNCTION % +%::::::::::::::::::::::::::::::::% +% +% Jordi Alastruey +% King's College London +% January 2014 + +function [FT,H_amp,H_ph] = Harmonics(func,NHarm,fmt,OutputFile,T) + +%NHarm: Number of harmonics plotted +%func: Input function +%SF: Sampling frequency + +format compact + +n_pts = length(func); +FT=0; +func_cal=0; + +%% Fourier transform +clear k j i +for k=1:n_pts, + omega(k)=2*pi*(k-1)/n_pts; % omega + FT(k)=0; + for j=1:n_pts, + FT(k)=FT(k)+func(j)*exp(-i*omega(k)*(j-1))/n_pts; + end; +end; +%% Inverse Fourier transform +clear j k i +for j=1:n_pts, + func_cal(j)=0; + for k=1:n_pts, + func_cal(j)=func_cal(j)+FT(k)*exp(i*omega(j)*(k-1)); + end; +end; +clear j k i +%% Magnitude and phase of FT +mFT= abs(FT); % modulus of FT +phFT = angle(FT); % phase angle of FT +%% Plot of the intensity +if (fmt==1) +figure +plot (omega(1:round(n_pts/2))/2/pi*n_pts, mFT(1:round(n_pts/2))) +grid +xlabel('Harmonic'); +ylabel('Intensity'); +end +%% Check if the initial function is obtained from the harmonics calculated +if (fmt==1) +figure +plot (omega/2/pi*n_pts, func_cal,'b', omega/2/pi*n_pts, func, 'r'); +xlabel('Sample'); +ylabel('Value'); +legend('calculated','initial function') +grid +end +%% Calculation of the harmonics +H = zeros(round(n_pts/2-1),n_pts); +H(1,:) = FT(1); % DC frequency +for j=2:n_pts/2-1, + for k=1:n_pts, + H(j,k)=2*FT(j)*exp(i*omega(k)*(j-1)); + end; +end; +%% Plot the harmonic indicated in H(?,:) (H(1,:) corresponds to DC, H(2,:) to 1st harmonic, and so on) +if (fmt==1) +figure +plot (omega/2/pi*n_pts, H(2,:), omega/2/pi*n_pts, func); +legend('harmonic','initial function') +grid +xlabel('Sample'); +ylabel('Value'); +end +%% Check if the harmonics are well-calculated +HT = H(1,:); +for j=2:round(n_pts/2)-1, + HT(1,:) = HT(1,:) + H(j,:); % The summation of all the harmonics should yield the original sample vector +end +if (fmt==1) +figure +plot (omega/2/pi*n_pts, HT,'b', omega/2/pi*n_pts, func, 'r'); +xlabel('Sample'); +ylabel('Value'); +legend('calculated from harmonics','initial function') +grid +end +%% Check the function generated by the first NHarm harmonics +HT = H(1,:); +for j=2:NHarm, + HT(1,:) = HT(1,:) + H(j,:); % The summation of all the harmonics should yield the original sample vector +end +if (fmt==1) +figure +plot (omega/2/pi*n_pts, HT,'b', omega/2/pi*n_pts, func, 'r'); +xlabel('Sample'); +ylabel('Value'); +legend('calculated from NHarm harmonics','initial function') +grid +end +%% Amplitude and phase angle of each harmonic +% func = H_amp(j)*sin(2*pi*j/T + H_ph(j)) +H_ph = zeros(1,round(n_pts/2-1)); +H_amp = zeros(1,round(n_pts/2-1)); +for j=1:round(n_pts/2)-1, + H_ph(j) = atan(-real(FT(j+1))/imag(FT(j+1))); % Phase angle + H_amp(j) = 2*real(FT(j+1))/sin(H_ph(j)); % Amplitude +end; +%% Display the function for 1D Nektar for the first NHarm harmonics +%clc +if (fmt==1) +fprintf('bc=%0.5g\n',FT(1)) +for j=1:NHarm +if(H_amp(j)>0) + if(H_ph(j)>0) + fprintf('+%0.5g*sin(%d*PI*t/T+%0.5g)',H_amp(j),2*j,H_ph(j)) + else + fprintf('+%0.5g*sin(%d*PI*t/T%0.5g)',H_amp(j),2*j,H_ph(j)) + end +else + if(H_ph(j)>0) + fprintf('%0.5g*sin(%d*PI*t/T+%0.5g)',H_amp(j),2*j,H_ph(j)) + else + fprintf('%0.5g*sin(%d*PI*t/T%0.5g)',H_amp(j),2*j,H_ph(j)) + end +end +end +fprintf('\n\n') +FT = FT(1); +end + +%% Display the amplitude and phase for the first NHarm harmonics +% in the right format for an input .bcs file for Nektar 1-D +fid = 1; % Print results on the screen by default +if (nargin > 3) + fid = fopen(OutputFile,'wt'); +end + +if (fmt==0) && (fid==1) + fprintf(fid,'Harmonics calculated\n'); +else + if (nargin == 5) + fprintf(fid,'%d %0.5g %0.5g\n',NHarm, T, FT(1)); + else + fprintf(fid,'%d [To be replaced with T] %0.5g\n',NHarm, FT(1)); + end + + for j=1:NHarm + fprintf(fid,'%0.5g %0.5g\n',H_amp(j),H_ph(j)); + end +end + +if (nargin > 3) + fclose(fid); +end + + +","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/Additional Functions/Harmonics_filter.m",".m","655","31","%:::::::::::::::::::::::::::::::::% +% FILTER WAVEFORM USING HARMONICS % +%:::::::::::::::::::::::::::::::::% +% +% Jordi Alastruey +% King's College London +% January 2014 + +function [tfunc,funcf] = Harmonics_filter(tfunc,func,SR,fmt,OutputFile) + +T = tfunc(end) + tfunc(2)-tfunc(1); % Cardiac period in s +NHarm = round((length(func)-1.1)/2); + +if (nargin == 5) + [FT,H_amp,H_ph] = Harmonics(func(1:end),NHarm,fmt,OutputFile,T); +else + [FT,H_amp,H_ph] = Harmonics(func(1:end),NHarm,fmt); +end + +tfunc = 0:1/SR:T; +funcf = FT(1); +for j=1:NHarm + funcf = funcf + H_amp(j)*sin(2*j*pi*tfunc/T + H_ph(j)); +end + + + +%-- Freq file: +% NHarm T FT(1) +% [H_amp(:) H_ph(:)] +","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/Additional Functions/ConvertHistoryFiles.m",".m","35853","955","function savepath = ConvertHistoryFiles(up) +% Convert .his files created by Nektar into Matlab format. +% Inputs: up.dir - the directory containing .his (and optionally +% .lum) files. If this is not specified then +% the user is prompted to select the +% directory manually. +% up.filename - a cell containing the filename(s) of .his +% files to be imported. If this is not +% specified then all .his files within the +% chosen directory are imported. +% up.all_beats - a logical indicating whether data should be +% extracted from all beats (= true), or just +% the final beat of the simulation (= false). +% all inputs are optional +% +% Outputs: history_files_data.m - a single Matlab file containing the +% data from all of the imported .his files, +% saved in the chosen directory. +% +% Accompanying Article: +% This code is provided to facilitate reproduction of the Pulse Wave +% Database described in: +% Charlton P.H. et al. Modelling arterial pulse waves in healthy +% ageing: in silico evaluation of haemodynamics and +% cardiovascular indices, ~~ under review ~~ +% DOI: ~~ tbc ~~ +% Further information on the pwdb Pulse Wave Database is provided in +% this article and at the project website: +% https://peterhcharlton.github.io/pwdb +% +% Author: Peter H. Charlton +% +% Licence: +% Permission is hereby granted, free of charge, to any person obtaining a copy +% of this software and associated documentation files (the ""Software""), to deal +% in the Software without restriction, including without limitation the rights +% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +% copies of the Software, and to permit persons to whom the Software is +% furnished to do so, subject to the following conditions: +% +% The above copyright notice and this permission notice shall be included in all +% copies or substantial portions of the Software. +% +% THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +% SOFTWARE. +% +% Copyright (C) 2018 King's College London +% +% Contributed to by: Marie Willemet, Jordi Alastruey, and Peter H. Charlton +% v.1.0 + + +% setup universal parameters +if nargin == 0, up = struct; end +up = setup_up(up); + +% order files according to simulation number +up.filename = order_according_to_sim(up.filename); + +% convert files into matlab data +[data_from_files, filename_root] = convert_files_into_matlab_data(up); + +% Eliminate non-relevant files +[data_from_files, filename_root, up] = eliminate_non_relevant_files(up, data_from_files, filename_root); + +% separate data according to filename root +data = separate_data_according_to_filename_root(data_from_files, filename_root, up); + +% Eliminate unwanted data +data = eliminate_unwanted_data(data, up); + +% Ensure that single pulse waves are continuous +data = make_pulse_waves_continuous(data, up); + +% save data in matlab file +savepath = [up.save_dir, 'history_files_data']; +save(savepath, 'data', '-v7.3') % use v.7.3 for large files (> 2 GB) + +end + +function up = setup_up(up) + +% Update dir field if necessary +if sum(strcmp(fieldnames(up), 'dir')) && ~strcmp(up.dir(end), filesep) + up.dir = [up.dir, filesep]; +end + +% Identify missing fields +required_fields = {'dir', 'filename', 'all_beats', 'all_data', 'required_domains', 'required_distance_els', 'required_signals', 'save_dir', 'ds_factor', 'continuous_waves', 'find_pw_els'}; +current_fields = fieldnames(up); +missing_fields = setxor(required_fields, current_fields); +% make sure required_domains comes before required_distance_els: +rel_el = find(strcmp(missing_fields, 'required_domains')); +missing_fields = [missing_fields(rel_el); missing_fields([1:rel_el-1, rel_el+1:end])]; + +% Fill in missing fields +for field_no = 1 : length(missing_fields) + curr_missing_field = missing_fields{field_no}; + switch curr_missing_field + case 'dir' + up.dir = uigetdir('', 'Please select the directory containing files for analysis'); + if ~up.dir + error('No directory selected') + end + if ~strcmp(up.dir(end), filesep) + up.dir = [up.dir, filesep]; + end + case 'filename' + temp = dir([up.dir, '*.his']); + if ~isempty(temp) + up.filename = extractfield(temp, 'name'); + else + error('There aren''t any .his files in this directory') + end + case 'all_beats' + up.all_beats = true; + case 'all_data' + up.all_data = true; + case 'required_domains' + %up.required_domains = [1, 15, 21, 22, 42, 46, 49, 84, 87, 112]; + % this extracts points approx every 2cm along aortic-root - digital path + %up.required_domains = [1, 2, 14, 15, 19, 21, 22, 42, 46, 49, 84, 87, 108, 112]; + % this is a further extended set + up.required_domains = [1, 2, 7, 14, 16, 18, 19, 27, 28, 35, 37, 108, 39, 41, 42, 15, 84, 87, 21, 22, 112, 44, 46, 49, 72,79,65,96,71,3,4]; + case 'required_distance_els' + % for the original set + %up.required_distance_els = {1, [], [], 2, [], 2, 3, 2, 1, 3, 3, 2, [], 3}; + % for the extended set + up.required_distance_els = {1, 2, 3, 2, 3, 2, 2, 2, 2, 2, 2, 3, 1, 3, 2, 2, 3, 3, 2, 3, 3, 2, 2, 3, 3, 2, 2, 2, 2,2,2}; + % this extracts points approx every 2cm along aortic-root - digital path + rel_path_domains = [1,2,14,19,21,22,108,112]; + % this extracts points approx every 2cm along aortic-root - digital and aortic-root - foot and aortic-root - brain paths + rel_path_domains = [1,2,14,19,21,22,108,112, 18,27,28,35,37,39,41,42,44,46,49,15,16,79,65,96,71]; + % Extracts right subclavian + rel_path_domains = [rel_path_domains,3,4]; + for dom_no = 1 : length(rel_path_domains) + rel_el = find(up.required_domains == rel_path_domains(dom_no)); + up.required_distance_els{rel_el} = 'all'; + end + clear dom_no rel_el rel_path_domains + + case 'required_signals' + up.required_signals = {'P', 'U', 'A', 'Q1D', 'Q_out'}; %{'P', 'Pe', 'U', 'Q', 'A', 'Q1D', 'Q_out'}; %{'P', 'Pe', 'U', 'Q', 'A', 'Q1D', 'Q_out'}; % {'P', 'Pe', 'U', 'Q', 'A'}; + case 'save_dir' + up.save_dir = up.dir; + case 'ds_factor' + up.ds_factor = 1; + case 'continuous_waves' + up.continuous_waves = 1; + case 'find_pw_els' + up.find_pw_els = 0; + end +end + +end + +function ordered_filenames = order_according_to_sim(filenames) + +counter = 0; +for s = 1 : length(filenames) + if strcmp(filenames{s}(1:4), 'sim_') + counter = counter+1; + end +end +dont_use = true; +sim_nos = nan(length(filenames),1); +if counter == length(filenames) + dont_use = false; + for s = 1 : length(filenames) + temp = strfind(filenames{s}, '_'); + if length(temp) ~=2 + dont_use = true; + else + sim_nos(s) = str2double(filenames{s}(temp(1)+1:temp(2)-1)); + end + clear temp + end +end +clear counter s + +if ~dont_use + [~, order] = sort(sim_nos); + ordered_filenames = filenames(order); +end +clear dont_use order sim_nos + +end + +function [data_from_files, filename_root] = convert_files_into_matlab_data(up) + +counter_no = 0; +for file_no = 1 : length(up.filename) + curr_file = up.filename{file_no}; + + % see if this file should be skipped + if ~up.all_data + temp1 = strfind(curr_file, '_'); temp1 = temp1(end); + temp2 = strfind(curr_file, '.'); temp2 = temp2(end); + seg_no = str2double(curr_file(temp1+1:temp2)); + if ~sum(seg_no == up.required_domains) + temp = strfind(curr_file, '_'); + %filename_root{file_no,1} = curr_file(1:temp(end)-1); clear temp curr_file temp1 temp2 seg_no + continue + end + clear temp temp1 temp2 seg_no + end + + % Import data from this history file + fprintf(['\n - ' curr_file]) + curr_file_path =[up.dir, curr_file]; + temp = ReadHistoryFiles(curr_file_path, up); + temp = downsample_data(temp, up); + data_from_files{file_no} = temp; clear temp field_no temp_fields + + % see if there is any lumped parameter data for this file + temp1 = strfind(curr_file, '_'); temp1 = temp1(end); + temp2 = strfind(curr_file, '.'); temp2 = temp2(end); + trial_lum_name = [up.dir, curr_file(1:temp1-1), '_out_' curr_file(temp1+1:temp2), 'lum']; + if exist(trial_lum_name, 'file') + lum_data_from_files = ReadLumpedFiles(trial_lum_name, up); clear trial_lum_name + lum_data_from_files = downsample_data(lum_data_from_files, up); + fields = fieldnames(lum_data_from_files); fields = fields(~strcmp(fields,'fs')); + for field_no = 1 : length(fields) + eval(['data_from_files{file_no}.' fields{field_no} ' = lum_data_from_files.' fields{field_no} ';']); + end + clear fields lum_data_from_files + end + + % Extract data for a single beat if required + if ~up.all_beats + data_from_files{file_no} = Extract_data_for_single_beat(data_from_files{file_no}, curr_file, up); + end + + % store filename root + temp = strfind(curr_file, '_'); + filename_root{file_no,1} = curr_file(1:temp(end)-1); clear temp curr_file_path + clear curr_file +end +clear file_no + +end + +function [data_from_files, filename_root, up] = eliminate_non_relevant_files(up, data_from_files, filename_root) + +if ~up.all_data + rel_files = ~cellfun(@isempty, filename_root); + filename_root = filename_root(rel_files); + data_from_files = data_from_files(rel_files); + up.filename = up.filename(rel_files); + clear rel_files +end + +end + +function data = eliminate_unwanted_data(data, up) + +sims = fieldnames(data); +if ~up.all_data + + for sim_no = 1 : length(sims) + curr_sim = sims{sim_no}; + eval(['sim_data = data.' curr_sim ';']) + + % eliminate unwanted signals + curr_signals = fieldnames(sim_data); + curr_signals = setxor(curr_signals, {'domain_no', 'distances', 'fs', 'units', 'start_sample'}); + unwanted_signals = setxor(curr_signals, up.required_signals); clear curr_signals + for sig_no = 1 : length(unwanted_signals) + if sum(strcmp(fieldnames(sim_data), unwanted_signals{sig_no})) + sim_data = rmfield(sim_data, unwanted_signals{sig_no}); + end + end + clear unwanted_signals + actual_signals = intersect(fieldnames(sim_data), up.required_signals); + + % eliminated unwanted domains + curr_domains = extractfield(sim_data, 'domain_no'); + [~,req_rows,~] = intersect(curr_domains, up.required_domains); clear curr_domains + sim_data = sim_data(req_rows); clear req_rows + + % eliminate unwanted measurement points + for domain_el = 1 : length(sim_data) + curr_domain = sim_data(domain_el).domain_no; + req_measurement_points = up.required_distance_els{up.required_domains == curr_domain}; clear curr_domain + % skip if all measurement points are to be extracted from this domain + if ischar(req_measurement_points) && strcmp(req_measurement_points, 'all') + continue + end + % Remove unwanted signal values + for signal_no = 1 : length(actual_signals) + curr_signal = actual_signals{signal_no}; + if ~sum(strcmp(curr_signal, {'Q1D', 'Q_out', 'P1D', 'PC'})) + eval(['sim_data(domain_el).' curr_signal ' = sim_data(domain_el).' curr_signal '(:,req_measurement_points);']) + else + eval(['sim_data(domain_el).' curr_signal ' = sim_data(domain_el).' curr_signal ';']) + end + clear curr_signal + end + clear signal_no + % Remove unwanted distances + sim_data(domain_el).distances = sim_data(domain_el).distances(req_measurement_points); + % Remove unwanted start samples + sim_data(domain_el).start_sample = sim_data(domain_el).start_sample(req_measurement_points); + clear req_measurement_points + end + clear domain_el + + % store reduced data + eval(['data.' curr_sim ' = sim_data;']) + + end + +end + +end + +function temp = downsample_data(temp, up) + +% downsample data +temp_fields = fieldnames(temp); +temp_fields = temp_fields(~strcmp(temp_fields, 'fs') & ~strcmp(temp_fields, 'distances')); +for field_no = 1 : length(temp_fields) + eval(['curr_field_data = temp.' temp_fields{field_no} ';']); + if up.ds_factor ~=1 + new_field_data = downsample(curr_field_data, up.ds_factor); + eval(['temp.' temp_fields{field_no} ' = new_field_data;']); + end + clear new_field_data curr_field_data +end + +% re-calculate sampling frequency +temp.fs = temp.fs/up.ds_factor; + +end + +function data = separate_data_according_to_filename_root(data_from_files, filename_root, up) + +% Identify filename roots +filename_root = strrep(filename_root,'-','_'); +[filename_roots, els, ~] = unique(filename_root); +[~, order] = sort(els); +filename_roots = filename_roots(order); + +char_filename_roots = filename_roots; +for s = 1 : length(filename_roots) + if ~isstrprop(filename_roots{s}(1),'alpha') + char_filename_roots{s} = ['sim_' filename_roots{s}]; + end +end +clear s + +for filename_root_no = 1 : length(filename_roots) + rel_files = find(strcmp(filename_root, filename_roots{filename_root_no})); + + for rel_file_no = 1 : length(rel_files) + + % store domain no + domain_no = up.filename{rel_files(rel_file_no)}; + temp = strfind(domain_no, '_'); + temp2 = strfind(domain_no, '.his'); + domain_no = str2double(domain_no(temp(end)+1:temp2-1)); + eval(['data.' char_filename_roots{filename_root_no} '(rel_file_no).domain_no = domain_no;']) + clear domain_no temp temp2 + + % store each variable's data in turn (including units) + temp = data_from_files{rel_files(rel_file_no)}; + vars = fieldnames(temp); + units = struct; + for var_no = 1 : length(vars) + eval(['data.' char_filename_roots{filename_root_no} '(rel_file_no).' vars{var_no} ' = temp.' vars{var_no} ';']) + eval(['units.' vars{var_no} ' = find_units(''' vars{var_no} ''');']); + end + eval(['data.' char_filename_roots{filename_root_no} '(rel_file_no).units = units;']); + clear units vars var_no temp + + end + clear rel_file_no rel_files + + % sort data according to domain no + eval(['rel_data = data.' char_filename_roots{filename_root_no} ';']) + domain_nos = extractfield(rel_data, 'domain_no'); + [~, rel_order] = sort(domain_nos); + rel_data = rel_data(rel_order); + eval(['data.' char_filename_roots{filename_root_no} ' = rel_data;']) + clear rel_data rel_order domain_nos + +end +clear filename_root_no filename_roots filename_root data_from_files char_filename_roots + +end + +function history_file_data = ReadHistoryFiles(curr_file_path, up) + +% Identify header lines and measurement points: +fid = fopen(curr_file_path); +header_line_log = true; line_no = 0; history_file_data.distances = []; +while header_line_log + curr_line = fgetl(fid); + line_no = line_no + 1; + if ~strcmp(curr_line(1), '#') + header_line_log = false; + end + if strcmp(curr_line(3:8), 'Point ') + history_file_data.distances(end+1) = str2double(curr_line(16:23)); + end + if strcmp(curr_line(1:3), '# t') + header_text = strrep(curr_line, '(x,t)', ''); + header_text = strrep(header_text, ' ', ''); + header_text = strrep(header_text, '#', ''); + headers = textscan(header_text, '%s', 'Delimiter', ','); + headers = headers{1}; clear header_text + end +end +fclose all; +no_header_lines = line_no - 1; +clear curr_line header_line_log fid line_no + + +% Import Nektar data: +raw = importdata(curr_file_path, ' ', no_header_lines); + +raw = raw.data; +for col_no = 1 : length(headers) + eval(['ext_data.' headers{col_no} ' = raw(:,col_no);']); +end +history_file_data.fs = 1/median(diff(unique(ext_data.t))); +history_file_data.fs = round(1e6*history_file_data.fs)/1e6; +t_col = strcmp(headers, 't'); +point_col = strcmp(headers, 'point'); +points = raw(:, point_col); +raw = raw(:, ~t_col & ~point_col); +headers = headers(~t_col & ~point_col); + +% Separate data according to each measurement location: +for header_no = 1 : length(headers) + curr_header = headers{header_no}; + temp = raw(:,header_no); + header_data = nan(ceil(length(temp)/length(history_file_data.distances)), length(history_file_data.distances)); + for point_no = 1 : length(history_file_data.distances) + point_temp = temp(points == point_no); + header_data(1:length(point_temp),point_no) = point_temp; + clear point_temp + end + clear temp + eval(['history_file_data.' curr_header ' = header_data;']); clear header_data +end + +end + +function lumped_file_data = ReadLumpedFiles(curr_file_path, up) + +% Identify header lines and measurement points: +fid = fopen(curr_file_path); +header_line_log = true; line_no = 0; +while header_line_log + curr_line = fgetl(fid); + line_no = line_no + 1; + if ~strcmp(curr_line(1), '#') + header_line_log = false; + end + if strcmp(curr_line(1:3), '# t') + header_text = curr_line; + header_text = strrep(header_text, '# ', ''); + old_len = 0; + while length(header_text) ~= old_len + old_len = length(header_text); + header_text = strrep(header_text, ' ', ' '); + end + header_text = strrep(header_text, ' ', ','); + headers = textscan(header_text, '%s', 'Delimiter', ','); + headers = headers{1}; clear header_text + end +end +fclose all; +no_header_lines = line_no - 1; +clear curr_line header_line_log fid line_no + + +% Import Nektar data: +raw = importdata(curr_file_path, ' ', no_header_lines); +raw = raw.data; +for col_no = 1 : length(headers) + eval(['ext_data.' headers{col_no} ' = raw(:,col_no);']); +end +lumped_file_data.fs = 1/median(diff(unique(ext_data.t))); +lumped_file_data.fs = round(1e6*lumped_file_data.fs)/1e6; +t_col = strcmp(headers, 't'); +raw = raw(:, ~t_col); +headers = headers(~t_col); + +% Extract each variable +for header_no = 1 : length(headers) + curr_header = headers{header_no}; + eval(['lumped_file_data.' curr_header ' = raw(:,header_no);']); clear header_data +end + +end + +function units = find_units(var_name) + +switch var_name + case 'P' + units = 'Pa'; + case 'PC' + units = 'Pa'; + case 'P1D' + units = 'Pa'; + case 'Pe' + units = 'Pa'; + case 'Pext' + units = 'Pa'; + case 'U' + units = 'm/s'; + case 'Q' + units = 'm3/s'; + case 'Q_out' + units = 'm3/s'; + case 'Q1D' + units = 'm3/s'; + case 'A' + units = 'm2'; + case 'distances' + units = 'm'; + case 'fs' + units = 'Hz'; + case 'start_sample' + units = 'no samples'; +end + +end + +function new_data_from_file = Extract_data_for_single_beat(data_from_file, curr_file, up) + +pulse_wave_duration_in_samples = nan; + +% cycle through each measurement point +for measurement_pt_no = 1 : length(data_from_file.distances) + clear beat_onsets minima a keep_minima rel_els heights heights_thresh keep_minima minima_no + + % identify start and end of final complete beat + + % Find minima in pressure (P) + a = data_from_file.P(:,measurement_pt_no); + fs = data_from_file.fs; + + + % Find relevant indices + use_original_method = 0; + if use_original_method + [relevant_inds, pulse_wave_duration_in_samples] = find_rel_inds_using_orig_method(a, fs, measurement_pt_no, pulse_wave_duration_in_samples); + else + [relevant_inds, pulse_wave_duration_in_samples] = find_rel_inds_using_new_method(a,fs, measurement_pt_no, pulse_wave_duration_in_samples); + end + + % extract and store relevant part of signal (i.e. last compelete beat) + vars = fieldnames(data_from_file); + for var_no = 1 : length(vars) + curr_var = vars{var_no}; + if strcmp(curr_var, 'fs') || strcmp(curr_var, 'distances') + eval(['new_data_from_file.' curr_var ' = data_from_file.' curr_var ';']); + continue + end + if ~sum(strcmp(curr_var, {'P1D', 'Q1D', 'Q_out', 'PC'})) + eval(['new_data_from_file.' curr_var '(:,measurement_pt_no) = data_from_file.' curr_var '(relevant_inds,measurement_pt_no);']); + else + eval(['new_data_from_file.' curr_var ' = data_from_file.' curr_var '(relevant_inds,1);']); + end + end + + + % Note the time of this beat onset + new_data_from_file.start_sample(measurement_pt_no) = relevant_inds(1); + +end + +if ~exist('new_data_from_file', 'var') + a = 1; +end + +end + +function [relevant_inds, pulse_wave_duration_in_samples] = find_rel_inds_using_orig_method(a, fs, measurement_pt_no, pulse_wave_duration_in_samples) +minima = 1 + find( ... + a(3:end-1)>a(2:end-2) & a(1:end-3)>a(2:end-2) | ... + (a(4:end)>a(3:end-1) & a(1:end-3)>a(2:end-2) & a(3:end-1) == a(2:end-2)) ... + ); + +% Eliminate repeated minima (or those which are very close to each other) +% - repeated +keep_minima = true(size(minima)); +for minima_no = 2:length(minima) + if minima(minima_no) == minima(minima_no-1)+1 + keep_minima(minima_no) = false; + end +end +minima = minima(keep_minima); +% - close to each other +keep_minima = true(size(minima)); +for minima_no = 1:length(minima)-1 + diffs = minima - minima(minima_no); + tol_samps = fs * 0.03; % within 0.030 s + if sum(diffs > 0 & diffs < tol_samps) + keep_minima(minima_no) = false; + end +end +minima = minima(keep_minima); + +% determine how high each minimum is in relation to the previous 3 s of +% data +time_int = 1.5; % in secs +heights = nan(length(minima),1); +for minimum_no = 1 : length(minima) + prev_time_int.deb = minima(minimum_no) - round(time_int*fs); + prev_time_int.fin = minima(minimum_no); + if prev_time_int.deb <= 0 + heights(minimum_no) = nan; + else + heights(minimum_no) = (a(minima(minimum_no))-min(a(prev_time_int.deb:prev_time_int.fin)))/range(a(prev_time_int.deb:prev_time_int.fin)); + end +end + +heights_inc = 0.06; +heights_thresh = 0.175-heights_inc; +successful_extraction = 0; +while ~successful_extraction && heights_thresh < 0.5 + heights_thresh = heights_thresh+heights_inc; + + % identify reliable beat onsets according to amplitude + rel_els = heights 0.5 | isnan(max_heights); + beat_onsets = beat_onsets(rel_els); + + % check that the last two beat onsets are a similar time apart + if range(beat_onsets(end-1:end)) < 0.95*range(beat_onsets(end-2:end-1)) + beat_onsets = beat_onsets(1:end-1); + end + + % check that there is some upslope after the final beat onset + if a(beat_onsets(end)) == max(a(beat_onsets(end):end)) + beat_onsets = beat_onsets(1:end-1); + end + + % check that there is sufficient signal in the relevant data for this + % last complete beat + if measurement_pt_no ~= 1 + curr_relevant_inds = beat_onsets(end-1):beat_onsets(end-1)+pulse_wave_duration_in_samples-1; + if curr_relevant_inds(end) > length(a) + beat_onsets = beat_onsets(1:end-1); + end + clear curr_relevant_inds + end + + % identify two last beat onsets: + if ~isempty(beat_onsets) + last_beat_onsets = beat_onsets(end-1:end); + else + last_beat_onsets = [1, length(a)]; + fprintf('\n ---- Couldn''t find a reliable complete beat, so outputting all data') + end + + % Identify relevant indices for the last complete beat + if measurement_pt_no == 1 + relevant_inds = last_beat_onsets(1):last_beat_onsets(2)-1; + pulse_wave_duration_in_samples = length(relevant_inds); + else + relevant_inds = last_beat_onsets(1):last_beat_onsets(1)+pulse_wave_duration_in_samples-1; + end + + % See whether this one needs manually annotating + curr_p_wav = a(relevant_inds); + curr_p_wav = (curr_p_wav - min(curr_p_wav))/range(curr_p_wav); + t = find(curr_p_wav > 0.1,1)/fs; + % If the upslope isn't straightaway (i.e. after the first 60 ms) + if t > 0.06 + % Look up values + if up.find_pw_els + relevant_inds = find_PW_els(curr_file, measurement_pt_no); + end + % or manually annotate if they're not there + if isnan(relevant_inds(1)) + initial_el = (last_beat_onsets(1)-(data_from_file.fs*1.2)); + plot(a( initial_el : end) ) + title = 'Couldn''t find onset of this beat'; + dims = [1 35]; + opts.WindowStyle = 'normal'; + beep,pause(0.5), beep + if measurement_pt_no == 1 + prompt = {'Enter sample of second last beat onset:', 'Enter sample of last beat onset:'}; + definput = {'0','0'}; + answer = inputdlg(prompt,title,dims,definput,opts); + last_beat_onsets = [str2double(answer(1)), str2double(answer(2))]; + else + prompt = {'Enter sample of second last beat onset:'}; + definput = {'0'}; + answer = inputdlg(prompt,title,dims,definput,opts); + last_beat_onsets = str2double(answer(1)); + end + close all + last_beat_onsets = last_beat_onsets+initial_el-1; + % re-find relevant indices + if measurement_pt_no == 1 + relevant_inds = last_beat_onsets(1):last_beat_onsets(2)-1; + pulse_wave_duration_in_samples = length(relevant_inds); + else + relevant_inds = last_beat_onsets(1):last_beat_onsets(1)+pulse_wave_duration_in_samples-1; + end + fprintf(['\n - meas pt ' num2str(measurement_pt_no) ', start ' num2str(relevant_inds(1)) ', end ' num2str(relevant_inds(end))]) + clear answer definput prompt opts dims title initial_el + end + end + + successful_extraction = 1; + + catch + if heights_thresh > 0.6 + error('Not working') + end + continue + end + +end + +end + +function data = make_pulse_waves_continuous(data, up) + +% Check that this should be done +if ~(~up.all_beats && up.continuous_waves) + return +end + +% Cycle through each simulation +sim_names = fieldnames(data); +for sim_no = 1 : length(sim_names) + curr_sim_name = sim_names{sim_no}; + eval(['curr_sim_data = data.' curr_sim_name ';']) + + % cycle through each domain + for row_no = 1 : length(curr_sim_data) + + % Cycle through each signal + signals = fieldnames(curr_sim_data); + signals = signals(~strcmp(signals, 'domain_no') & ~strcmp(signals, 'distances') & ~strcmp(signals, 'fs') & ~strcmp(signals, 'start_sample') & ~strcmp(signals, 'units')); + for sig_no = 1 : length(signals) + + % extract data for this signal + curr_sig_name = signals{sig_no}; + eval(['curr_sig = data.' curr_sim_name '(row_no).' curr_sig_name ';']) + + % for each measurement point + for meas_pt_no = 1 : size(curr_sig,2) + curr_pw = curr_sig(:,meas_pt_no); + cont_pw = calc_static_wave(curr_pw); + eval(['data.' curr_sim_name '(row_no).' curr_sig_name '(:,meas_pt_no) = cont_pw;']) + end + + end + + end + +end + +end + +function [relevant_inds, pulse_wave_duration_in_samples] = find_rel_inds_using_new_method(sig, fs, measurement_pt_no, pulse_wave_duration_in_samples) + +%% Identify beats + +% - find derivative +mov_avg_duration = 0.01; +no_samps = mov_avg_duration*fs; +sig_mov_avg = movmean(sig,5); +deriv = [0;diff(sig_mov_avg)*fs]; + +% - find maxima in derivative +deriv_maxima = find_max(deriv); + +% - identify relevant maxima (those above a threshold value) +thresh = movmax(deriv, 2*fs); +thresh = 0.95*[thresh(2*fs:end); ones(2*fs-1,1)*thresh(end)]; +rel_max = deriv_maxima(deriv(deriv_maxima)>thresh(deriv_maxima)); + +% - refine candidates +finished_refining = 0; +while ~finished_refining + thresh_secs = 0.5; + thresh_samps = thresh_secs*fs; + rel_max_to_eliminate = []; + for rel_max_no = 1 : length(rel_max)-1 + curr_rel_max = rel_max(rel_max_no:rel_max_no+1); + if range(curr_rel_max) < thresh_samps + % then eliminate the one with the lower derivative + [~, temp] = min(deriv(curr_rel_max)); + clear max_variation no_samps_to_consider + rel_max_el = temp+rel_max_no-1; + rel_max_to_eliminate = [rel_max_to_eliminate, rel_max_el]; + end + end + rel_els = setxor(1:length(rel_max), rel_max_to_eliminate); + rel_max = rel_max(rel_els); clear rel_els + if sum(diff(rel_max) length(sig) + if ~isnan(pulse_wave_duration_in_samples) + relevant_inds = beat_onsets(end-2) : beat_onsets(end-2) + pulse_wave_duration_in_samples-1; + else + relevant_inds = beat_onsets(end-2) : beat_onsets(end-1)-1; + end +end + +% store duration of PW +pulse_wave_duration_in_samples = length(relevant_inds); + +end + +function maxima = find_max(sig) + +maxima1 = find(sig(2:end-1) > sig(1:end-2) & sig(3:end) < sig(2:end-1)) + 1; +maxima2 = find(sig(2:end-2) > sig(1:end-3) & sig(2:end-2) == sig(3:end-1) & sig(4:end) < sig(3:end-1)) + 2; + +maxima = unique([maxima1; maxima2]); + +end + +function minima = find_min(sig) + +minima1 = find(sig(2:end-1) < sig(1:end-2) & sig(3:end) > sig(2:end-1)) + 1; +minima2 = find(sig(2:end-2) < sig(1:end-3) & sig(2:end-2) == sig(3:end-1) & sig(4:end) > sig(3:end-1)) + 2; + +minima = unique([minima1; minima2]); + +end + +function pos_zero_cross = find_pos_zero_cross(deriv) + +pos_zero_cross = find(deriv(2:end)>0 & deriv(1:end-1) <= 0)+1; + +end + +function static_wave = calc_static_wave(orig_wave) + +orig_wave = orig_wave(:); + +% Calculate expected position of next point +next_point = orig_wave(end) + diff(orig_wave(end-1:end)); + +% If the wave was static, then this next point would be equal to the first point +% So, we can make the wave static by making this next point equal to the first +temp = linspace(0,orig_wave(1)-next_point, length(orig_wave)); temp = temp(:); +static_wave = orig_wave + temp; + +end","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/Additional Functions/AorticFlowWave_orig.m",".m","49949","888","function inflow = AorticFlowWave_orig(params) +% AORTICFLOWWAVE generates an exemplary aortic flow wave, with optional +% input parameters specifying its properties +% +% AorticFlowWave +% +% Inputs: - params, an optional structure of input parameters +% +% Outputs: - inflow, a structure containing the waveform and its +% properties. +% +% Accompanying Article: +% This code is provided to facilitate reproduction of the Pulse Wave +% Database described in: +% Charlton P.H. et al. Modelling arterial pulse waves in healthy +% ageing: a database for in silico evaluation of haemodynamics +% and pulse wave indices, ~~ under review ~~ +% DOI: ~~ tbc ~~ +% Further information on the pwdb Pulse Wave Database is provided in +% this article and at the project website: +% https://peterhcharlton.github.io/pwdb +% +% Author: Peter H. Charlton +% +% Licence: +% Permission is hereby granted, free of charge, to any person obtaining a copy +% of this software and associated documentation files (the ""Software""), to deal +% in the Software without restriction, including without limitation the rights +% to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +% copies of the Software, and to permit persons to whom the Software is +% furnished to do so, subject to the following conditions: +% +% The above copyright notice and this permission notice shall be included in all +% copies or substantial portions of the Software. +% +% THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +% IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +% FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +% AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +% LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +% OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +% SOFTWARE. +% +% Copyright (C) 2019 King's College London +% +% Contributed to by: Marie Willemet, Jordi Alastruey, and Peter H. Charlton +% v.1.0 + +%% ==== Setup input params (adding default and derived values where necessary) +if nargin < 1 + params = struct; +end +inflow = setup_params(params); + +%% ==== Find Template Flow Wave +template_flow = create_template_inflow_waveform(inflow); + +%% ==== Find Adjusted Flow Wave +inflow = adjust_template_flow(inflow, template_flow); + +%% ==== Adjust Sampling Frequency +inflow = adjust_sampling_frequency(inflow); + +%% ==== Calculate Characteristics of Inflow wave +inflow = calc_characteristics_inflow_wave(inflow); + +%% ==== Plot Figures +plot_figures(inflow); + +end + +function inflow = setup_params(params) + +%% Setup + +% store the user-specified input params +inflow.input_params = params; clear params + +% shut figures unless plotting multiple flow waveforms +if ~sum(strcmp(fieldnames(inflow.input_params),'plot_multiple')) + close all +elseif inflow.input_params.plot_multiple + figHandles = findobj('Type', 'figure'); + if ~isempty(figHandles) + if length(figHandles)==2 + close(figHandles(2)); + else + close all + end + end + clear figHandles +end + +%% Input parameters + +% if CO and HR have been specified, but not SV, then calculate SV +curr_params = fieldnames(inflow.input_params); +if sum(strcmp(curr_params, 'HR')) && sum(strcmp(curr_params, 'CO')) && ~sum(strcmp(curr_params, 'SV')) + inflow.input_params.SV = 1000*inflow.input_params.CO / inflow.input_params.HR; +end + +% If either HR or T has been specified, but not the other, then specify it +if sum(strcmp(curr_params, 'HR')) && ~sum(strcmp(curr_params, 'T')) + inflow.input_params.T = 60/inflow.input_params.HR; +elseif ~sum(strcmp(curr_params, 'HR')) && sum(strcmp(curr_params, 'T')) + inflow.input_params.HR = 60/inflow.input_params.T; +end + +% If LVET has been specified then make sure it is in secs +if sum(strcmp(curr_params, 'LVET')) && inflow.input_params.LVET > 2 + inflow.input_params.LVET = inflow.input_params.LVET/1000; % convert from ms to secs +end + +% If T_Peak_Flow has been specified then make sure it is in secs +if sum(strcmp(curr_params, 'T_Peak_Flow')) && inflow.input_params.T_Peak_Flow > 2 + inflow.input_params.T_Peak_Flow = inflow.input_params.T_Peak_Flow/1000; % convert from ms to secs +end + +% identify any missing parameters +curr_params = fieldnames(inflow.input_params); +req_params = {'fs', 'wave_type', 'HR', 'SV', 'CO', 'T', 'LVET', 'T_Peak_Flow', 'T_sys_upslope_ip', 'Q_sys_upslope_ip', 'T_Min_Flow', 'T_dia', 'Reg_Vol', 'rev_flow', 'contractility_const'}; +curr_req_params = intersect(curr_params, req_params); +missing_params = setxor(curr_req_params, req_params); clear curr_params curr_req_params +% moves CO, LVET, T and T_sys_upslope_ip to the end, as they are dependent on other parameters. +for rel_param = req_params + temp = find(strcmp(missing_params, rel_param{1,1})); + if ~isempty(temp) + missing_params = missing_params([1:temp-1, temp+1 : length(missing_params)]); + missing_params(end+1) = {rel_param{1,1}}; + end +end + + +% If any parameters are missing then insert the baseline values for them +for param_no = 1 : length(missing_params) + + % identify the current missing parameter + curr_missing_param = missing_params{param_no}; + + % specify the baseline value of this parameter + switch curr_missing_param + case 'HR' + val = 75; % in bpm + val = 75; % Mynard's, in bpm + case 'SV' + val = 83; % im ml + val = (6.2*1000/inflow.input_params.HR); % Mynard's, in ml + case 'CO' + val = inflow.input_params.HR*inflow.input_params.SV/1000; % im l/min + %val = 6.2; % Mynard's, in l/min + case 'wave_type' + val = 'elderly'; % either 'young' or 'avg' or 'elderly' + val = 'Mynard'; % Use Mynard2015's aortic root wave + case 'rev_flow' + val = 1; % between 0 and 1 - the proportion of reverse flow to include + case 'fs' + val = 1000; % in Hz + case 'contractility_const' + val = 1; % a multiplication factor applied to the time of the systolic peak + case 'T' + val = 60/inflow.input_params.HR; + case 'T_sys_upslope_ip' + val = (0.020/0.085)*inflow.input_params.T_Peak_Flow; + val = (0.010/0.080)*inflow.input_params.T_Peak_Flow; % Mynard's + case 'Q_sys_upslope_ip' + val = 0.32; + % Haven't measured Mynard's - don't think it's used + case 'LVET' + val = calc_lvet(inflow); + val = 0.282; % Mynard's, s + case 'T_Peak_Flow' + val = (0.085/0.290)*inflow.input_params.LVET; + val = (0.080/0.282)*inflow.input_params.LVET; % Mynard's + case 'T_Min_Flow' + val = (0.310/0.290)*inflow.input_params.LVET; + val = (0.298/0.282)*inflow.input_params.LVET; % Mynard's + case 'T_dia' + val = (0.330/0.290)*inflow.input_params.LVET; + val = (0.309/0.282)*inflow.input_params.LVET; % Mynard's + case 'Reg_Vol' + val = 0.73; + val = 1.2775; % Mynard's, ml + end + + % insert this baseline value + eval(['inflow.input_params.' curr_missing_param ' = val;']) + + clear val + +end + +%% Scale contractility and reverse flow magnitude +contractility_times = {'T_sys_upslope_ip', 'T_Peak_Flow'}; +for s = 1 : length(contractility_times) + eval(['inflow.input_params.' contractility_times{s} ' = inflow.input_params.contractility_const * inflow.input_params.' contractility_times{s} ';']); +end +inflow.input_params.Reg_Vol = inflow.input_params.rev_flow * inflow.input_params.Reg_Vol; + +%% Input settings + +% identify any missing settings +curr_params = fieldnames(inflow.input_params); +req_params = {'do_plot','save_plot', 'plot_multiple', 'plot_name', 'file_path'}; +curr_req_params = intersect(curr_params, req_params); +missing_params = setxor(curr_req_params, req_params); clear curr_params req_params + +% If any parameters are missing then insert the baseline values for them +for param_no = 1 : length(missing_params) + + % identify the current missing parameter + curr_missing_param = missing_params{param_no}; + + % specify the baseline value of this parameter + switch curr_missing_param + case 'do_plot' + val = true; % whether or not to plot the generated wave + case 'save_plot' + val = true; + case 'plot_multiple' + val = false; + case 'plot_name' + val = 'AorticFlowWave_plot'; + case 'file_path' + val = '/Users/petercharlton/Google Drive/Work/Code/AorticFlowWave/AorticFlowWave manual/Figures/'; + if ~exist(val, 'dir') + val = uigetdir; + end + end + + % insert this baseline value + eval(['inflow.input_settings.' curr_missing_param ' = val;']) + + clear val + +end + +% move user specified settings to this new structure +for param_no = 1 : length(curr_req_params) + + % identify the current missing parameter + curr_setting = curr_req_params{param_no}; + + % insert this setting + eval(['inflow.input_settings.' curr_setting ' = inflow.input_params.' curr_setting ';']) + + % remove from the params structure + inflow.input_params = rmfield(inflow.input_params, curr_setting); + +end + +%% Put fields in alphabetical order +inflow.input_params = orderfields(inflow.input_params); +inflow.input_settings = orderfields(inflow.input_settings); + +end + +function LVET = calc_lvet(inflow) + +% use the function provided in the following article to derive LVET: +% +% Weissler et al, ""Relationships between left ventricular ejection time, +% stroke volume, and heart rate in normal individuals and patients with +% cardiovascular disease"", American Heart Journal, vol. 62, 1961. +% DOI: 10.1016/0002-8703(61)90403-3 + +% Function: +% LVET = 0.266 + 0.0011*(SV - 82) - 0.0009*(HR - 73) +% where LVET is in secs, SV [ml] is stroke volume, and HR [bpm] is heart rate. + +% If a LVET has been specified as an input, then take this +if ~sum(strcmp(fieldnames(inflow.input_params), 'LVET')) + + % otherwise, calculate using this formula + LVET = 0.266 + 0.0011*(inflow.input_params.SV - 82) - 0.0009*(inflow.input_params.HR - 73); % in secs + +else + LVET = inflow.input_params.LVET; +end + + +end + +function template_flow = create_template_inflow_waveform(inflow) + +%% === Setup constants +do_change = 1; +if do_change + prop = 1.2; + prop2 = 1.1; + prop3 = 1.1; + prop4 = 1.04; + prop5 = 1.05; + prop6 = 1.03; +else + [prop, prop2,prop3,prop4,prop5, prop6] = deal(1); +end + +% timings +template_flow.T = 1; +template_flow.ti_0 = (1/prop)*0.024*template_flow.T; %Time of inflection point in systolic increase +template_flow.tmax_0 = 0.08*template_flow.T; %Time of systolic peak +template_flow.ti2_0 = (1/prop5)*prop2*0.17*template_flow.T; %0.150; Time of inflection point in systolic decrease (old only) +template_flow.ti3_0 = prop4*prop2*0.21*template_flow.T; %0.150; Time of inflection point in systolic decrease (old only) +template_flow.ts_0 = 0.290*template_flow.T; %Time of start of dicrotic notch +template_flow.tmin_0 = 0.310*template_flow.T; %Time of minimum flow during dicrotic notch %%% THIS HAS BEEN ADJUSTED from 0.30 +template_flow.td_0 = 0.330*template_flow.T; %Time of start of diastole + +% flows +template_flow.Qmax = 1; %Systolic peak flow +template_flow.Qi = 0.367; %Flow at inflection point on systolic upslope +template_flow.Qi2 = prop5*prop3*(1/prop2)*0.647; %Flow at inflection point in systolic decrease (old) +template_flow.Qi3 = prop6*(1/prop3)*(1/prop2)*0.496; %Flow at second inflection point in systolic decrease (old) + +% find approximate Qmin (during reverse flow) +template_flow.Qmin = -0.1; %Minimum flow during dicrotic notch +% % Adjust if the regurgitation volume is provided +% if sum(strcmp(fieldnames(params),'Reg_Vol')) +% desired_ratio_reverse_to_forward_flow = params.Reg_Vol/(params.SV+params.Reg_Vol); +% curr_reverse_flow = abs(0.5*(template_flow.td_0-template_flow.ts_0)*template_flow.Qmin); +% curr_forward_flow = 0.5*template_flow.ts_0*template_flow.Qmax; +% approx_curr_ratio_reverse_to_forward_flow = curr_reverse_flow/curr_forward_flow; +% scale_factor = desired_ratio_reverse_to_forward_flow/approx_curr_ratio_reverse_to_forward_flow; +% template_flow.Qmin = template_flow.Qmin*scale_factor; +% end + +% round timings to right sizes of time vector +ti = round(template_flow.ti_0 *1000)./1000; +tmax = round(template_flow.tmax_0*1000)./1000; +ti2 = round(template_flow.ti2_0 *1000)./1000; +ti3 = round(template_flow.ti3_0 *1000)./1000; +ts = round(template_flow.ts_0 *1000)./1000; +tmin = round(template_flow.tmin_0*1000)./1000; +td = round(template_flow.td_0 *1000)./1000; + +% time step +dt = 1/1000; + +%% === Calculate template using Marie's piecewise polynomial + +% switch params.wave_type % young, avg, or elderly +% case 'young' +% template_flow.age = 'young'; +% template_flow.v = Get_parametric_young(dt, template_flow.Qi, template_flow.Qmax, template_flow.Qmin, ti, tmax, tmin, ts, td); +% case 'avg' +% template_flow.age = 'avg'; +% young = Get_parametric_young(dt, template_flow.Qi, template_flow.Qmax, template_flow.Qmin, ti, tmax, tmin, ts, td); +% elderly = Get_parametric_old(dt, template_flow.Qi, template_flow.Qmax, template_flow.Qmin, template_flow.Qi2, ti, tmax, tmin, ti2, ts, td); +% template_flow.v = (young+elderly)./2; clear young elderly +% case 'elderly' +% template_flow.age = 'elderly'; +% template_flow.v = Get_parametric_old(dt, template_flow.Qi, template_flow.Qmax, template_flow.Qmin, template_flow.Qi2, ti, tmax, tmin, ti2, ts, td); +% case 'impulse' +% template_flow.age = 'impulse'; +% durn_of_impulse = 0.05*template_flow.T; +% durn_of_impulse_samples = round(durn_of_impulse*(1/dt)); +% durn_of_beat = template_flow.T; +% durn_of_beat_samples = round(durn_of_beat*(1/dt)); +% template_flow.v = [0, ones(1,durn_of_impulse_samples), zeros(1,durn_of_beat_samples - durn_of_impulse_samples-1)]; +% end + +if strcmp(inflow.input_params.wave_type, 'elderly') + template_flow.age = 'elderly'; + template_flow.v = Get_parametric_pete(dt, template_flow.Qi, template_flow.Qmax, template_flow.Qmin, template_flow.Qi2, ti, tmax, tmin, ti2, ts, td, template_flow.Qi3, ti3); +elseif strcmp(inflow.input_params.wave_type, 'Mynard') + template_flow.age = 'young'; + template_flow.v = Get_Mynard2015_flow_wave; +end +template_flow.t = [0:(length(template_flow.v)-1)]*(1/1000); + +end + +function inflow = adjust_template_flow(inflow, template_flow) +%% === Adjust template to give desired timings + +% setup +dt = 1/inflow.input_params.fs; + +% Find sytolic upslope +deb = 1; [~, fin] = max(template_flow.v); +sys_upslope.v = template_flow.v(deb:fin); +sys_upslope.t = linspace(0, inflow.input_params.T_Peak_Flow, length(sys_upslope.v)); + +% Find systolic downslope +[~, temp] = max(template_flow.v); deb = temp+1; clear temp +fin = find(template_flow.v(1:end-1) > 0 & template_flow.v(2:end) <= 0); fin = fin(1); +sys_downslope.v = template_flow.v(deb:fin); +sys_downslope.t = linspace(sys_upslope.t(end)+dt, inflow.input_params.LVET, length(sys_downslope.v)); + +% Find reverse flow +deb = find(template_flow.v(1:end-1) > 0 & template_flow.v(2:end) <= 0); deb = deb(1)+1; +fin = find(template_flow.v ~= 0, 1, 'last'); +reverse.v = template_flow.v(deb:fin); +reverse.t = linspace(sys_downslope.t(end)+dt, inflow.input_params.T_dia, length(reverse.v)); + +% Find diastolic flat line +no_els = round((inflow.input_params.T - (inflow.input_params.T_dia+dt))/dt); +diastolic.t = linspace(inflow.input_params.T_dia+dt, inflow.input_params.T, no_els); +diastolic.v = zeros(size(diastolic.t)); + +% concatenate to give waveform +mod_flow.t = [sys_upslope.t, sys_downslope.t, reverse.t, diastolic.t]; +mod_flow.v = [sys_upslope.v, sys_downslope.v, reverse.v, diastolic.v]; + +% resample to give constant fs, without irregular spacing at joins +inflow.t = (0 : floor(mod_flow.t(end)*inflow.input_params.fs))/inflow.input_params.fs; +inflow.v = interp1(mod_flow.t, mod_flow.v, inflow.t); + +if sum(strcmp(fieldnames(inflow.input_params), 'Reg_Vol')) + % Scale to give desired reverse flow volume + scale_factor = inflow.input_params.Reg_Vol/abs(sum(inflow.v(inflow.v<0)*dt)); + inflow.v(inflow.v<0) = inflow.v(inflow.v<0)*scale_factor; % flow is now in ml/s + + % Scale to give desired stroke volume + scale_factor = (inflow.input_params.SV+inflow.input_params.Reg_Vol)/(sum(inflow.v(inflow.v>0))*dt); + inflow.v(inflow.v>0) = inflow.v(inflow.v>0)*scale_factor; % flow is now in ml/s +else + % Scale to give desired stroke volume + scale_factor = inflow.input_params.SV/(sum(inflow.v)*dt); + inflow.v = inflow.v*scale_factor; % flow is now in ml/s + +end + +% Convert to required units +CO_in_m3_per_sec = inflow.input_params.CO/(60*1000); %(convert from l/min) +inflow.v = inflow.v./mean(inflow.v).*CO_in_m3_per_sec; + +% % Update inflow parameters with final values +% CO = mean(inflow.v); +% inflow.CO_m3_per_sec = CO; % Cardiac output [m3/s] + +end + +function Q = Get_parametric_pete(dt, Qi, Qmax, Qmin,Qi2, ti,tmax,tmin,ti2, ts, td, Qi3, ti3) + +%% Find Q1 (systolic uplslope, fourth order) + +t_matrix = [ + 0 0 0 0 1; % Q1(0) = 0 + ti^4 ti^3 ti^2 ti 1; % Q1(ti) = Qi + 4*3*ti^2 3*2*ti 2*1 0 0; % Q1''(ti) = 0 + 4*tmax^3 3*tmax^2 2*tmax 1 0; % Q1'(tmax) = 0 + tmax^4 tmax^3 tmax^2 tmax 1 % Q1(tmax) = Qmax + ]; + +q_matrix = [ + 0; + Qi; + 0; + 0; + Qmax + ]; + +%Solve for coefficients t_matrix*coeffs=q_matrix: coeffs = t_matrix\q_matrix; +Q1_coeffs = t_matrix\q_matrix; + +% %% Find Q2 (systolic downslope, second order) +% +% t_matrix = [ +% tmax^2 tmax 1; % Q2(tmax) = Qmax +% 2*tmax 1 0; % Q2'(tmax) = 0 +% ts^2 ts 1; % Q2(ts) = 0 +% ]; +% +% q_matrix = [ +% Qmax; +% 0; +% 0; +% ]; +% +% %Solve for coefficients t_matrix*coeffs=q_matrix: coeffs = t_matrix\q_matrix; +% Q2_coeffs = t_matrix\q_matrix; +% +% %% Find Q2 (systolic downslope with inflection point, fourth order) +% +% t_matrix = [ +% tmax^4 tmax^3 tmax^2 tmax 1; % Q2(tmax) = Qmax +% 4*tmax^3 3*tmax^2 2*tmax 1 0; % Q2'(tmax) = 0 +% ti2^4 ti2^3 ti2^2 ti2 1; % Q2(ti2) = Qi2 +% 4*3*ti2^2 3*2*ti2 2*1 0 0; % Q2''(ti2) = 0 +% ts^4 ts^3 ts^2 ts 1; % Q2(ts) = 0 +% ]; +% +% q_matrix = [ +% Qmax; +% 0; +% Qi2; +% 0; +% 0; +% ]; +% +% %Solve for coefficients t_matrix*coeffs=q_matrix: coeffs = t_matrix\q_matrix; +% Q2_coeffs = t_matrix\q_matrix; + +%% Find Q2 (systolic downslope with two inflection points, sixth order) + +t_matrix = [ + tmax^6 tmax^5 tmax^4 tmax^3 tmax^2 tmax 1; % Q2(tmax) = Qmax + 6*tmax^5 5*tmax^4 4*tmax^3 3*tmax^2 2*tmax 1 0; % Q2'(tmax) = 0 + ti2^6 ti2^5 ti2^4 ti2^3 ti2^2 ti2 1; % Q2(ti2) = Qi2 + 6*5*ti2^4 5*4*ti2^3 4*3*ti2^2 3*2*ti2 2*1 0 0; % Q2''(ti2) = 0 + ti3^6 ti3^5 ti3^4 ti3^3 ti3^2 ti3 1; % Q2(ti3) = Qi3 + 6*5*ti3^4 5*4*ti3^3 4*3*ti3^2 3*2*ti3 2*1 0 0; % Q2''(ti3) = 0 + ts^6 ts^5 ts^4 ts^3 ts^2 ts 1; % Q2(ts) = 0 + ]; + +q_matrix = [ + Qmax; + 0; + Qi2; + 0; + Qi3; + 0; + 0; + ]; + +%Solve for coefficients t_matrix*coeffs=q_matrix: coeffs = t_matrix\q_matrix; +Q2_coeffs = t_matrix\q_matrix; + +%% Find Q3 (reverse flow, third order) + +%Q2_deriv_ts = 2*Q2_coeffs(1).*ts + Q2_coeffs(2); + +t_matrix = [ + ts^3 ts^2 ts 1; % Q3(ts) = 0 + % 4*ts^3 3*ts^2 2*ts 1 0; % Q3'(ts) = Q2'(ts) + 3*tmin^2 2*tmin 1 0; % Q3'(tmin) = 0 + tmin^3 tmin^2 tmin^1 1; % Q3(tmin) = Qmin + td^3 td^2 td 1; % Q3(td) = 0 + %3*td^2 2*td 1 0; % Q3'(td) = 0 + ]; + +q_matrix = [ + 0; + %Q2_deriv_ts; + 0; + Qmin + 0; + ]; + +%Solve for coefficients t_matrix*coeffs=q_matrix: coeffs = t_matrix\q_matrix; +Q3_coeffs = t_matrix\q_matrix; + +%% Calculate template flow curve + +dt=1e-3; + +% Q1, t1 +t1=[0:dt:tmax]; +Q1 = Q1_coeffs(1).*t1.^4 + Q1_coeffs(2).*t1.^3 + Q1_coeffs(3).*t1.^2 +Q1_coeffs(4).*t1 + Q1_coeffs(5); + +% Q2, t2 +t2=[tmax+dt:dt:ts]; +Q2 = Q2_coeffs(1)*t2.^6 + Q2_coeffs(2)*t2.^5 + Q2_coeffs(3).*t2.^4 + Q2_coeffs(4).*t2.^3 + Q2_coeffs(5).*t2.^2 +Q2_coeffs(6).*t2 + Q2_coeffs(7); +% Q2 = Q2_coeffs(1).*t2.^4 + Q2_coeffs(2).*t2.^3 + Q2_coeffs(3).*t2.^2 +Q2_coeffs(4).*t2 + Q2_coeffs(5); +%Q2 = Q2_coeffs(1).*t2.^2 + Q2_coeffs(2).*t2 + Q2_coeffs(3); + +% Q3, t3 +t3 = [ts+dt:dt:td]; +% Q3 = Q3_coeffs(1).*t3.^4 +Q3_coeffs(2).*t3.^3 + Q3_coeffs(3).*t3.^2 + Q3_coeffs(4).*t3 + Q3_coeffs(5); +Q3 = Q3_coeffs(1).*t3.^3 +Q3_coeffs(2).*t3.^2 + Q3_coeffs(3).*t3 + Q3_coeffs(4); + +% Q4, t4 +t4 = [td+dt:dt:1.0]; +Q4 = t4.*0; + +%% Construct template curve +t = [t1,t2,t3,t4]; +Q = [Q1,Q2,Q3,Q4]; + +end + +function Q = Get_Mynard2015_flow_wave + +fs = 1000; % Hz +% Data provided by Mynard: +Q = [0.975173175413631;0.973779853988154;0.972395614614815;0.970995717731558;0.969511227019400;0.967822711189793;0.965786748864051;0.963283288352364;0.960257180172596;0.956733614590217;0.952804019043309;0.948592861750212;0.944220671600988;0.939775612934077;0.935299487236573;0.930788206519929;0.926202977984071;0.921487672252196;0.916588056259775;0.911469209683415;0.906128003680296;0.900598361098229;0.894948479110418;0.889270767746236;0.883666691560787;0.878229797375804;0.873030633851194;0.868106794857485;0.863460040023719;0.859060747248515;0.854858328407404;0.850795093069735;0.846820567387548;0.842903445940403;0.839039020574192;0.835250902526769;0.831586960403603;0.828110482041099;0.824888470942132;0.821979531423770;0.819423828948797;0.817237101401127;0.815409739068083;0.813910764962756;0.812695446475572;0.811714543871594;0.810923016496613;0.810286366332797;0.809783558074059;0.809406383225149;0.809155982868884;0.809049312351120;0.822723666912791;1.02233385165230;1.96658629314415;4.58560140254054;9.85427558739735;18.3723567331533;30.1314774777907;44.5666042279459;60.7946355212591;77.8878867053600;95.0770252268905;111.846390198646;127.934762788699;143.278424134962;157.935102195756;172.016187493348;185.639837609637;198.905789610112;211.886315485302;224.626247569543;237.146494154128;249.448001830952;261.515308275138;273.320033907046;284.824893763383;295.988445536841;306.770268021839;317.135901678616;327.060806548574;336.532774620005;345.552564122539;354.132876926804;362.296079123497;370.071215649353;377.490884042716;384.588435958977;391.395812923550;397.942143214896;404.253068924458;410.350659695562;416.253710063464;421.978206529741;427.537777920319;432.943995528724;438.206455565240;443.332643996137;448.327642700327;453.193777638760;457.930329008757;462.533418553688;466.996162750017;471.309138243523;475.461155370642;479.440285080944;483.235041551993;486.835593235815;490.234863026527;493.429385478842;496.419814845701;499.211018863089;501.811744031372;504.233891257801;506.491488218617;508.599479649849;510.572474215038;512.423584988732;514.163481563606;515.799739601955;517.336534070953;518.774681411257;520.111998663707;521.343917882841;522.464274200170;523.466176452167;524.342869998804;525.088510984828;525.698787922101;526.171347706221;526.506006380627;526.704747502486;526.771530539299;526.711946609556;526.532768110292;526.241442186613;525.845576190021;525.352457228893;524.768639135078;524.099619940398;523.349622557002;522.521481755218;521.616632378229;520.635187375853;519.576089782668;518.437320238385;517.216140141572;515.909351597176;514.513556936185;513.025401511467;511.441787659971;509.760050567731;507.978090122726;506.094456391599;504.108390059734;502.019820234977;499.829327332228;497.538078870921;495.147747545238;492.660421408567;490.078515604694;487.404693896395;484.641806405646;481.792847669950;478.860936563018;475.849317075378;472.761376647828;469.600676913928;466.370990500281;463.076337047776;459.721011868244;456.309601576609;452.846982508583;449.338299567697;445.788925134535;442.204399603282;438.590356794328;434.952438775355;431.296205409574;427.627044124906;423.950085234953;420.270128045542;416.591580412164;412.918414146340;409.254137683546;405.601785901964;401.963925786966;398.342675776211;394.739736069239;391.156426918743;387.593731908661;384.052343427062;380.532707909337;377.035068903213;373.559506534790;370.105972482048;366.674320045660;363.264329314927;359.875727739749;356.508206630724;353.161434222293;349.835065959949;346.528752629132;343.242146850871;339.974908347998;336.726708255579;333.497232626731;330.286185183115;327.093289287159;323.918289074735;320.760949682792;317.621056533014;314.498413683235;311.392841324680;308.304172575322;305.232249788152;302.176920648979;299.138034374586;296.115438333779;293.108975399232;290.118482297792;287.143789164435;284.184720425785;281.241097063450;278.312740302484;275.399476098279;272.501140627695;269.617586923616;266.748691925274;263.894363582487;261.054547078738;258.229230595293;255.418450710163;252.622296983934;249.840915478514;247.074511117000;244.323348894336;241.587754005714;238.868110988727;236.164861986677;233.478504240701;230.809586911346;228.158707317984;225.526506668447;222.913665332752;220.320897695917;217.748946607613;215.198577433230;212.670571703443;210.165720358625;207.684816590472;205.228648295138;202.797990168838;200.393595496125;198.016187701204;195.666451751727;193.345025520643;191.052491223716;188.789367057162;186.556099160881;184.353054028231;182.180511473288;180.038658252078;177.927582416260;175.847268457468;173.797593279242;171.778323012440;169.789110670159;167.829494620601;165.898897841200;163.996627905452;162.121877644825;160.273726422047;158.451141948429;156.652982576222;154.877999996753;153.124842275710;151.392057157989;149.678095575415;147.981315291308;146.299984616011;144.632286127094;142.976320327190;141.330109171368;139.691599394906;138.058665571552;136.429112832201;134.800679174373;133.171037294589;131.537795878214;129.898500285375;128.250629578665;126.591552056964;124.918513546968;123.228701286997;121.519279660594;119.787396713776;118.030173344769;116.244685038415;114.427943132719;112.576879319406;110.688334247474;108.759049349989;106.785660427503;104.764691739498;102.692549897179;100.565517355309;98.3797456114618;96.1312483447445;93.8158947430382;91.4294032575011;88.9673360283976;86.4250942542448;83.7979148138351;81.0808684833106;78.2688601109401;75.3566311223238;72.3387647348645;69.2096942693344;65.9637149614027;62.5949996961145;59.0976191088091;55.4655665094076;51.6927880876767;47.7732188551761;43.7008247436815;39.4696510842022;35.0738773265343;30.5078774208866;25.7662847630790;20.8440598589074;15.7365576638450;10.4395896586277;4.94948395886629;-0.735422487056177;-6.61006110317804;-12.6622828791241;-18.8741551014073;-25.2223446279507;-31.6774795652257;-38.2025309338117;-44.7503098863757;-51.2601554986592;-57.6538083796666;-63.8303716876630;-69.6602108183708;-74.9777007689949;-79.5729897866242;-83.1835808216337;-85.4878655563827;-86.1053603202930;-84.6131464119407;-80.5954995994022;-73.7514724136509;-64.0798633763130;-52.1091746662620;-39.0192868202663;-26.4236251384105;-15.7941270663738;-7.91285846891109;-2.74469604605859;0.293602435264025;1.98007377814065;2.92205567366193;3.49397045416749;3.89008117479282;4.14089208439632;4.20614627486643;4.04493717059770;3.65230704785446;3.06654618725146;2.35815282267805;1.61164891584995;0.908193676387704;0.312993750191313;-0.131483838549379;-0.407114525746058;-0.517743427869374;-0.484134357520946;-0.337500761404327;-0.112833084082376;0.156872389987909;0.444636538227652;0.731345027437622;1.00549206445160;1.26133764803882;1.49627099108680;1.70822087230301;1.89379163630702;2.04750482337735;2.16218836931823;2.23026692820176;2.24552638787934;2.20487245926461;2.10966251151507;1.96632527713331;1.78615156071780;1.58430251438172;1.37821353006803;1.18565666114217;1.02275857288413;0.902257504376651;0.832227903567992;0.815419325838948;0.849258943000078;0.926471019680050;1.03618649105827;1.16536244555750;1.30031059679785;1.42814387876862;1.53798635774857;1.62184185248123;1.67507168268247;1.69648274308898;1.68806788064185;1.65446889571512;1.60224849115926;1.53906274445581;1.47282227801065;1.41092024226895;1.35959019164763;1.32343840995741;1.30517473525675;1.30554512513065;1.32344993220714;1.35621592404900;1.39997894562081;1.45012864222408;1.50176691865472;1.55013711262050;1.59098990128905;1.62086310064297;1.63726410106609;1.63875430171567;1.62494357247146;1.59640897161454;1.55455559570685;1.50143877623741;1.43956630142906;1.37169744439211;1.30065285302460;1.22914600799649;1.15964393278636;1.09426168755604;1.03469201194843;0.982169473485648;0.937466421126849;0.900916576754242;0.872461092336484;0.851711324911019;0.838022391974301;0.830571715975153;0.828437194426511;0.830670286624854;0.836360134370805;0.844685779213896;0.854954550765467;0.866625729579164;0.879319585335726;0.892812809676451;0.907022159158339;0.921978757821491;0.937795948512687;0.954633805326337;0.972663416953261;0.992033828224525;1.01284410678493;1.03512242076436;1.05881332183346;1.08377368490528;1.10977702323459;1.13652523530348;1.16366629882222;1.19081604552159;1.21758195002861;1.24358685111199;1.26849068155330;1.29200857560822;1.31392414863640;1.33409737863406;1.35246646033510;1.36904423843737;1.38390978338493;1.39719607347560;1.40907499283471;1.41974096642944;1.42939455153875;1.43822720054384;1.44640822057111;1.45407470397354;1.46132491496614;1.46821531763466;1.47476114298754;1.48094013869504;1.48669894093813;1.49196136425231;1.49663782766939;1.50063512319714;1.50386578038738;1.50625637879319;1.50775429615074;1.50833254006601;1.50799248071200;1.50676446792542;1.50470646655165;1.50190096972003;1.49845054448812;1.49447242448339;1.49009258936109;1.48543976285306;1.48063972419857;1.47581026734594;1.47105706521158;1.46647060968185;1.46212430881871;1.45807373738226;1.45435696080351;1.45099579024122;1.44799778032830;1.44535875286724;1.44306561926812;1.44109928056824;1.43943740433552;1.43805690958957;1.43693603064433;1.43605587501926;1.43540143560977;1.43496206010104;1.43473141839304;1.43470703956439;1.43488951227804;1.43528145584444;1.43588637346798;1.43670749517974;1.43774670667983;1.43900364339042;1.44047500816853;1.44215414823655;1.44403090376470;1.44609171884197;1.44831998672798;1.45069658631969;1.45320055643842;1.45580984905350;1.45850210192629;1.46125537497052;1.46404880206793;1.46686312043640;1.46968105181609;1.47248752262826;1.47526972300285;1.47801701615651;1.48072071934780;1.48337378498477;1.48597041509377;1.48850564418889;1.49097492473993;1.49337374632552;1.49569731442067;1.49794030833073;1.50009673043004;1.50215985127527;1.50412224791871;1.50597592630257;1.50771251338018;1.50932350081571;1.51080051987820;1.51213562656644;1.51332157683547;1.51435207395019;1.51522197314722;1.51592743274461;1.51646600506683;1.51683666492955;1.51703977759086;1.51707701165433;1.51695120544616;1.51666619753251;1.51622663328266;1.51563775984886;1.51490522148164;1.51403486597555;1.51303257136306;1.51190409986457;1.51065498366048;1.50929044472432;1.50781534874546;1.50623419114788;1.50455111150159;1.50276993125144;1.50089420884152;1.49892730597802;1.49687245884812;1.49473284859790;1.49251166618081;1.49021216766126;1.48783771724494;1.48539181653539;1.48287811963546;1.48030043462400;1.47766271257347;1.47496902595788;1.47222353890944;1.46943047221929;1.46659406611873;1.46371854366174;1.46080807705649;1.45786675868910;1.45489857791480;1.45190740409148;1.44889697580608;1.44587089572787;1.44283263024876;1.43978551276761;1.43673274933238;1.43367742530605;1.43062251176056;1.42757087045167;1.42452525641417;1.42148831753469;1.41846259070050;1.41545049448519;1.41245431861558;1.40947621072178;1.40651816109149;1.40358198630023;1.40066931265464;1.39778156042536;1.39491992977262;1.39208538917569;1.38927866693981;1.38650024618245;1.38375036357629;1.38102901198697;1.37833594693885;1.37567069659738;1.37303257478828;1.37042069645756;1.36783399494897;1.36527124044948;1.36273105902113;1.36021195164343;1.35771231280773;1.35523044825332;1.35276459156949;1.35031291945742;1.34787356556832;1.34544463293838;1.34302420511081;1.34061036425278;1.33820123324222;1.33579484431388;1.33338926016340;1.33098259456667;1.32857300400822;1.32615867997684;1.32373784447988;1.32130875074699;1.31886969005915;1.31641900407923;1.31395510053223;1.31147646950788;1.30898169807164;1.30646948191180;1.30393863372965;1.30138808866182;1.29881690734648;1.29622427726826;1.29360951296356;1.29097205556370;1.28831147197233;1.28562745386192;1.28291981639856;1.28018849649590;1.27743355035738;1.27465515011932;1.27185357956203;1.26902922899795;1.26618258951974;1.26331424686165;1.26042487506438;1.25751523010908;1.25458614360014;1.25163851651538;1.24867331300571;1.24569155419815;1.24269431200759;1.23968270293181;1.23665788186434;1.23362103596021;1.23057337859285;1.22751614349328;1.22445057906192;1.22137794288460;1.21829949650900;1.21521650054114;1.21213021004095;1.20904187013147;1.20595271174608;1.20286394751884;1.19977676786138;1.19669233729080;1.19361179106446;1.19053623215835;1.18746672858958;1.18440431111538;1.18134997126825;1.17830465973955;1.17526928511395;1.17224471292174;1.16923176504156;1.16623121941054;1.16324381003570;1.16027022726762;1.15731111829750;1.15436708785409;1.15143869904904;1.14852647435796;1.14563089670433;1.14275241057533;1.13989142319184;1.13704830578597;1.13422339494885;1.13141699401049;1.12862937441509;1.12586077710418;1.12311141392642;1.12038146909308;1.11767110067176;1.11498044212579;1.11230960387566;1.10965867487975;1.10702772420934;1.10441680261584;1.10182594408854;1.09925516737407;1.09670447746561;1.09417386703982;1.09166331783351;1.08917280196709;1.08670228318944;1.08425171804785;1.08182105698174;1.07941024532497;1.07701922423083;1.07464793150520;1.07229630237125;1.06996427014828;1.06765176686126;1.06535872378557;1.06308507192919;1.06083074245840;1.05859566706718;1.05637977831226;1.05418300991596;1.05200529703488;1.04984657649583;1.04770678698755;1.04558586922764;1.04348376609723;1.04140042277914;1.03933578708579;1.03728981028786;1.03526244848414;1.03325366392776;1.03126342537163;1.02929170672478;1.02733848406693;1.02540373170865;1.02348741823828;1.02158950339000;1.01970993615314;1.01784865411397;1.01600558373497;1.01418064114576;1.01237373309989;1.01058475778510;1.00881360530218;1.00706015770754;1.00532428865248;1.00360586280348;1.00190473526114;1.00022075127348;0.998553746415667;0.996903547212885;0.995269972068214;0.993652832340103;0.992051933470198;0.990467076131119;0.988898057416265;0.987344672099656;0.985806714003158;0.984283977483060;0.982776259028291;0.981283358940195;0.979805083034552;0.978341244292943;0.976891664388993;0.975456175004534;0.974034618864419;0.972626849924471;0.971232531803553;0.969847314708597;0.968446559622980;0.966961576526169;0.965273284904924;0.963238556143108;0.960737398614335;0.957714424958803;0.954194370546731;0.950268164283976;0.946059908881930;0.941690011856661;0.937246781822003;0.932772374536440;0.928263160351216;0.923680796836290;0.918969481829967;0.914075101004032;0.908962603132715;0.903628497931898;0.898106190788554;0.892463314366207;0.886791786457542;0.881192755742685;0.875759694103406;0.870563324949767;0.865641617188617;0.860996810907333;0.856599753215754;0.852400202939444;0.848340613182712;0.844370414994066;0.840457985701078;0.836598141523446;0.832813957473801;0.829152817129408;0.825677676834808;0.822455432486473;0.819544826720973;0.816986377513701;0.814796311551718;0.812965539338525;0.811463529533424;0.810245838926853;0.809263321669889;0.808470844851686;0.807833683488993;0.807330517386983;0.806952875718220;0.806701723506212;0.806589307442645;0.818727985867816;1.00588741144649;1.91128708796076;4.45410595443429;9.61193334647688;18.0006459823640;29.6332314140555;43.9622690940319;60.1137754534786;77.1605569936956;94.3277825133242;111.091698659148;127.183197017379;142.532489199134;157.193532957161;171.275966787995;184.897608484247;198.158660509707;211.132219432564;223.864044632443;236.375957796940;248.669758908944;260.730746615467;272.531165797111;284.034165391563;295.198499111895;305.983681531697;316.354941940750]; +Q(1:52) = 0; +Q(362:end) = 0; +Q = [Q(53:end); Q(1:52)]; + +Q = Q(:)'; +end + +function Qtot_old = Get_parametric_old(dt, Qi, Qmax, Qmin,Qi2, ti,tmax,tmin,ti2, ts, td) + + +%% Q2 = fourth order (for old wave); no horizontal slope at t=0 + +% 15 unknowns +old_LHS_O = [ + % First polynomial curve, Q1 (systolic upslope) + tmax^4 tmax^3 tmax^2 tmax^1 1 0 0 0 0 0 0 0 0 0 0; %Q1(tmax) = Qmax + 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0; %Q1(0) = 0 + 4*tmax^3 3*tmax^2 2*tmax^1 1 0 0 0 0 0 0 0 0 0 0 0; %Q1'(tmax) = 0 + 4*3*ti^2 3*2*ti 2 0 0 0 0 0 0 0 0 0 0 0 0; %Q1''(ti) = 0 + ti^4 ti^3 ti^2 ti 1 0 0 0 0 0 0 0 0 0 0; %Q1(ti) = Qi + % Second polynomial curve, Q2 (systolic downslope) + 0 0 0 0 0 tmax^4 tmax^3 tmax^2 tmax 1 0 0 0 0 0; %Q2(tmax) = Qmax + 0 0 0 0 0 4*tmax^3 3*tmax^2 2*tmax 1 0 0 0 0 0 0; %Q2'(tmax) = 0 + 0 0 0 0 0 ti2^4 ti2^3 ti2^2 ti2 1 0 0 0 0 0; %Q2(ti2) = Qi2 + 0 0 0 0 0 4*3*ti2^2 3*2*ti2 2 0 0 0 0 0 0 0; %Q2'(tmax) = 0 + + 0 0 0 0 0 ts^4 ts^3 ts^2 ts 1 -ts^4 -ts^3 -ts^2 -ts -1; %Q2(ts) = Q3(ts) + 0 0 0 0 0 4*ts^3 3*ts^2 2*ts 1 0 -4*ts^3 -3*ts^2 -2*ts -1 0; %Q2'(ts) = Q3'(ts) + 0 0 0 0 0 0 0 0 0 0 td^4 td^3 td^2 td 1; %Q3(td) = 0 + 0 0 0 0 0 0 0 0 0 0 4*td^3 3*td^2 2*td 1 0; %Q3'(td) = 0 + 0 0 0 0 0 0 0 0 0 0 tmin^4 tmin^3 tmin^2 tmin 1; %Q3(tmin) = Qmin + 0 0 0 0 0 0 0 0 0 0 4*tmin^3 3*tmin^2 2*tmin 1 0 %Q3'(tmin) = 0 + ]; + +%RHS +old_RHS_O = [ + Qmax; + 0; + 0; + 0; + Qi; + Qmax; + 0; + Qi2; + 0; + 0; + 0; + 0; + 0; + Qmin; + 0 +]; + +% Pete's editing + +% 15 unknowns +LHS_O = [ + % First polynomial curve, Q1 (systolic upslope) - fourth order polynomial + tmax^4 tmax^3 tmax^2 tmax^1 1 0 0 0 0 0 0 0 0 0 0; %Q1(tmax) = Qmax + 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0; %Q1(0) = 0 + 4*tmax^3 3*tmax^2 2*tmax^1 1 0 0 0 0 0 0 0 0 0 0 0; %Q1'(tmax) = 0 + 4*3*ti^2 3*2*ti 2 0 0 0 0 0 0 0 0 0 0 0 0; %Q1''(ti) = 0 + ti^4 ti^3 ti^2 ti 1 0 0 0 0 0 0 0 0 0 0; %Q1(ti) = Qi + % Second polynomial curve, Q2 (systolic downslope) - fourth order polynomial + 0 0 0 0 0 tmax^4 tmax^3 tmax^2 tmax 1 0 0 0 0 0; %Q2(tmax) = Qmax + 0 0 0 0 0 4*tmax^3 3*tmax^2 2*tmax 1 0 0 0 0 0 0; %Q2'(tmax) = 0 + 0 0 0 0 0 ti2^4 ti2^3 ti2^2 ti2 1 0 0 0 0 0; %Q2(ti2) = Qi2 + 0 0 0 0 0 4*3*ti2^2 3*2*ti2 2 0 0 0 0 0 0 0; %Q2''(ti2) = 0 + 0 0 0 0 0 ts^4 ts^3 ts^2 ts 1 -ts^4 -ts^3 -ts^2 -ts -1; %Q2(ts) = 0 % Changed: used to be Q2(ts) = Q3(ts) + % Second and third polynomial curves + 0 0 0 0 0 5*ts^4 4*ts^3 3*ts^2 2*ts 1 -4*ts^3 -3*ts^2 -2*ts -1 0; %Q2'(ts) - Q3'(ts) = 0 + % Third polynomial curve, Q3 (reverse flow) - fifth order polynomial + 0 0 0 0 0 0 0 0 0 0 ts^4 ts^3 ts^2 ts 1; %Q3(ts) = 0 % Added + 0 0 0 0 0 0 0 0 0 0 td^4 td^3 td^2 td 1; %Q3(td) = 0 + % 0 0 0 0 0 0 0 0 0 0 4*td^3 3*td^2 2*td 1 0; %Q3'(td) = 0 + 0 0 0 0 0 0 0 0 0 0 tmin^4 tmin^3 tmin^2 tmin 1; %Q3(tmin) = Qmin + 0 0 0 0 0 0 0 0 0 0 4*tmin^3 3*tmin^2 2*tmin 1 0 %Q3'(tmin) = 0 + ]; + +%RHS +RHS_O = [ + Qmax; + 0; + 0; + 0; + Qi; + Qmax; + 0; + Qi2; + 0; + 0; + 0; + 0; + 0; + Qmin; + 0 +]; + +%Solve system A*X=B: x = A\B; +clear X; +X = old_LHS_O\old_RHS_O; + + +%% Equation of flow curve solution - OLD +dt=1e-3; +%Q1, t1 +t1=[0:dt:tmax]; +Q1 = X(1).*t1.^4 + X(2).*t1.^3 + X(3).*t1.^2 +X(4).*t1 + X(5); + +%Q2,t2 +t2=[tmax+dt:dt:ts]; +% old +% Q2 = X(6).*t2.^4 + X(7).*t2.^3 + X(8).*t2.^2 + X(9).*t2 + X(10); +% new +Q2 = X(6).*t2.^4 + X(7).*t2.^3 + X(8).*t2.^2 + X(9).*t2 + X(10); + +%Q3,t3 +t3 = [ts+dt:dt:td]; +% old +% Q3 = X(11).*t3.^4 + X(12).*t3.^3 + X(13).*t3.^2 + X(14).*t3 + X(15); +Q3 = X(11).*t3.^4 + X(12).*t3.^3 + X(13).*t3.^2 + X(14).*t3 + X(15); + +%Q4, t4 +t4 = [td+dt:dt:1.0]; +Q4 = t4.*0; + +Qtot_old = [Q1, Q2, Q3, Q4]; + +end + +function Qtot_young = Get_parametric_young(dt, Qi, Qmax, Qmin, ti,tmax,tmin, ts, td) + + +%% Q2:second order, no horizontal slope = 0 at t=0 - YOUNG wave + +% [P14 P13 P12 P11 P10 P22 P21 P20 P34 P33 P32 P31 P30] +LHS_Y = [ + tmax^4 tmax^3 tmax^2 tmax^1 1 0 0 0 0 0 0 0 0; %Q1(tmax) = Qmax + 0 0 0 0 1 0 0 0 0 0 0 0 0; %Q1(0) = 0 +% 0 0 0 1 0 0 0 0 0 0 0 0 0; %Q1'(0) = 0 + 4*tmax^3 3*tmax^2 2*tmax^1 1 0 0 0 0 0 0 0 0 0; %Q1'(tmax) = 0 + 4*3*ti^2 3*2*ti 2 0 0 0 0 0 0 0 0 0 0; %Q1''(ti) =0 + ti^4 ti^3 ti^2 ti 1 0 0 0 0 0 0 0 0; %Q1(ti) = Qi + 0 0 0 0 0 tmax^2 tmax 1 0 0 0 0 0; %Q2(tmax)=Qmax + 0 0 0 0 0 2*tmax 1 0 0 0 0 0 0; %Q2'(tmax)=0 + 0 0 0 0 0 ts^2 ts 1 -ts^4 -ts^3 -ts^2 -ts -1; %Q2(ts)=Q3(ts) + 0 0 0 0 0 2*ts 1 0 -4*ts^3 -3*ts^2 -2*ts -1 0; %Q2'(ts)=Q3'(ts) + 0 0 0 0 0 0 0 0 td^4 td^3 td^2 td 1; %Q3(td) = 0 + 0 0 0 0 0 0 0 0 4*td^3 3*td^2 2*td 1 0; %Q3'(td)=0 + 0 0 0 0 0 0 0 0 tmin^4 tmin^3 tmin^2 tmin 1; %Q3(tmin) = Qmin + 0 0 0 0 0 0 0 0 4*tmin^3 3*tmin^2 2*tmin 1 0 %Q3'(tmin) = 0 + ]; + +%RHS +RHS_Y = [ + Qmax; + 0; +% 0; %Q1'(0) = 0 + 0; + 0; + Qi; + Qmax; + 0; + 0; + 0; + 0; + 0; + Qmin; + 0 +]; + +%Solve system A*X=B: x = A\B; +X = LHS_Y\RHS_Y; + +%% Equation of flow curve solution - YOUNG +%Q1, t1 +t1=[0:dt:tmax]; +Q1 = X(1).*t1.^4 + X(2).*t1.^3 + X(3).*t1.^2 +X(4).*t1 + X(5); + +%Q2,t2 +t2=[tmax+dt:dt:ts]; +Q2 = X(6).*t2.^2 + X(7).*t2 + X(8); + +%Q3,t3 +t3 = [ts+dt:dt:td]; +Q3 = X(9).*t3.^4 + X(10).*t3.^3 + X(11).*t3.^2 + X(12).*t3 + X(13); + +%Q4, t4 +t4 = [td+dt:dt:1.0]; +Q4 = t4.*0; + +Qtot_young = [Q1, Q2, Q3, Q4]; + +end + +function inflow = adjust_sampling_frequency(inflow) + +old_t = inflow.t; +inflow.t = 0:(1/inflow.input_params.fs):inflow.t(end); +inflow.v = interp1(old_t, inflow.v, inflow.t); + +end + +function inflow = calc_characteristics_inflow_wave(inflow) + +% NB: inflow.v is in m3 per sec + +% Sampling freq (Hz) +chars.fs = inflow.input_params.fs; + +% Duration of cardiac cycle (secs) +chars.T = (length(inflow.t)-1)/inflow.input_params.fs; + +% Heart rate (bpm) +chars.HR = 60/chars.T; + +% Stoke volume (in ml) +chars.SV = sum(inflow.v)*(1/chars.fs)*1000*1000; + +% Cardiac output (in l/min) +chars.CO = chars.HR*chars.SV/1000; + +% LVET (in ms) +end_systole_el = find(inflow.v(1:end-1)>0 & inflow.v(2:end) <=0, 1); +chars.LVET = inflow.t(end_systole_el); + +% Forward volume (in ml) +chars.vol_forward = sum(inflow.v(inflow.v>0))*(1/chars.fs)*1000*1000; + +% Regurgitation Volume +chars.Reg_Vol = abs(sum(inflow.v(inflow.v<0)))*(1/chars.fs)*1000*1000; + +% Proportion regurgitation (%) +chars.perc_reg = 100*chars.Reg_Vol/chars.vol_forward; + +% Measure of contractility +[chars.max_dq_dt, max_contr_el] = max(diff(inflow.v(1:end_systole_el))); + +% Additional timings: +% - Time of systolic peak +[~, sys_peak_el] = max(inflow.v); +chars.T_Peak_Flow = inflow.t(sys_peak_el); +% - Time of max regurgitation +[max_reg, max_reg_el] = min(inflow.v); +if max_reg < 0 + chars.T_Min_Flow = inflow.t(max_reg_el); +else + chars.T_Min_Flow = nan; +end +% - Time of end of regurgitation +if max_reg < 0 + end_reg_el = find(inflow.v(1:end-1)<0 & inflow.v(2:end) ==0, 1); + chars.T_dia = inflow.t(end_reg_el); +else + chars.T_dia = nan; +end +% - Time of max gradient of systolic upslope +chars.T_max_contr = inflow.t(max_contr_el); + +inflow.chars = orderfields(chars); + +end + +function plot_figures(inflow) + +% plot figure if requested +if inflow.input_settings.do_plot + + paper_size = [900 600]; + + % Final inflow waveform in ml/s + + figure('Position',[600 400 paper_size]) + set(gca,'fontsize',28) + hold on + plot([inflow.t(1), inflow.t(end)], [0,0], '--', 'Color', 0.2*ones(1,3)); + plot(inflow.t,inflow.v*1e6,'k','linewidth',2); + ylabel('Q (ml/s)') + xlabel('time (s)') + + %- adjust color if multiple plots + if inflow.input_settings.plot_multiple + h_lines = findall(gcf, 'Type', 'line'); + color_range = [0,0.75]; + if length(h_lines) > 1 + rel_colors = linspace(color_range(1), color_range(2), length(h_lines)); + for s = 1 : length(h_lines) + h_lines(s).Color = rel_colors(s)*[1,1,1]; + end + end + end + + if inflow.input_settings.save_plot + save_plot(gcf, paper_size, inflow.input_settings.plot_name, inflow.input_settings.file_path) + end + +end + +end + +function save_plot(h_fig, paper_size, filename, filepath) + +savepath = [filepath, filename]; +set(gcf,'color','w'); +set(gcf,'PaperUnits','centimeters'); +set(gcf,'PaperSize', [paper_size(1), paper_size(2)]./40); +set(gcf,'PaperPosition',[0 0 paper_size(1) paper_size(2)]./40); +print(gcf,'-dpdf',savepath) +print(gcf,'-dpng',savepath) + +end +","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/Additional Functions/TTAlgorithm1_11/14_12_19_Version09/PWV_Calulator_CC_cycle.m",".m","5487","200","function t_int = PWV_Calulator_CC_cycle(t,signal,indmaxs,indmins,gradins) + +dt = t(2)-t(1); + +% Determine most approximate length of cycle, most consistent kernel, and +% the approximate transit time +dCycle1 = abs(diff(gradins(1,:,1))); +dCycle2 = abs(diff(gradins(2,:,1))); + +diff1 = std(dCycle1); +diff2 = std(dCycle2); +if diff1 <= diff2 + CApprox = round( median(dCycle1) ); + kernel = gradins(1,:,1); +else + CApprox = round( median(dCycle2) ); + kernel = gradins(2,:,1); +end + +kernelExtend = round(0.2*CApprox); +trash = find(kernel > kernelExtend+1); +kernel = kernel(trash); + +TTApprox = median(diff(gradins(:,:,1))); + +if size(gradins,2) > 1 + + t_int = []; + + for i=2:length(kernel) + + kernel1 = [kernel(i) , kernel(i-1)]; + + M1 = min(signal(1,kernel1(1) : kernel1(2))); + M2 = min(signal(2,kernel1(1) : kernel1(2))); + + sig1 = [M1*ones(1,2*TTApprox), signal(1,kernel1(1)-kernelExtend : kernel1(2)), M1*ones(1,2*TTApprox)]; + sig2 = [M2*ones(1,2*TTApprox), signal(2,kernel1(1)-kernelExtend : kernel1(2)), M2*ones(1,2*TTApprox)]; + + % Normalise Carotid Wave Data + trash = sig1 - min(sig1); + sig1 = trash/max(trash); + + % Normalise Femoral Wave Data + trash = sig2 - min(sig2); + sig2 = trash/max(trash); + + y = []; + x = []; + + for j= -round(TTApprox/4): 1 : round(1.5*TTApprox) + + sig1_new = sig1( (2*TTApprox+1) : (2*TTApprox + kernelExtend + round(0.8*CApprox)) ); + sig2_new = sig2( (2*TTApprox+1)+j : (2*TTApprox + kernelExtend + round(0.8*CApprox))+j ); + + trash = find(sig2_new); + + xx = sum(sig1_new.*sig2_new); + y = [y,xx]; + x = [x,(j*dt)]; + + if xx > max(y(1:end-1)) + max_ind = j; + max_CC = xx; + else + end + end + + loop=1; + k=1; + while loop==1 + k=k+1; + poly = polyfit(x(k-1:k+1),y(k-1:k+1),1); + if poly(1) > 10 + ind1 = k; + loop = 0; + end + if (k+1) == length(y) + ind1 = 1; + loop = 0; + end + end + + [~,I] = max(y(ind1:end)); + I = I + (ind1-1); + interp_span = 5; + + if length(y) < (I+interp_span) + interp_span = length(y) - I; + elseif (I-interp_span) < 1 + interp_span = I-1; + end + + interp_int = [I-interp_span:I+interp_span]; + int = find(interp_int); + interp_int = interp_int(int); + + poly = polyfit(x(interp_int),y(interp_int),2); + x1 = [x(1):0.001:x(end)]; + y1 = poly(1).*x1.^2 + poly(2).*x1 + poly(3); + + m_TT = -poly(2)/(2*poly(1)); + + t_int = [t_int, m_TT]; + end + +else + ind = indmins(:,:,1); + kernel1 = [indmins(1,:,1) , indmaxs(1)]; + kernel2 = [indmins(2,:,1) , indmaxs(2)]; + + shift = max( round( abs(kernel2(2) - kernel1(2))*4 ) , 25 ); + + trash = round(size(signal,2)/4); + [~,I] = min( signal(1, (kernel1(1)+trash) :end)); + max_length = I + kernel1(1)+trash - 1; + + sig1_new = signal(1,:); + + sig2 = zeros(1,size(signal,2)); + sig2(kernel2(1):max_length) = signal(2,kernel2(1):max_length); + + y = []; + x = []; + + for j= -round(shift):1:round(shift) + if j<0 + sig2_new = [zeros(1,-j),sig2(1 : end-(-j)) ]; + else + sig2_new = [sig2(j+1:end),zeros(1,j)]; + end + + trash = find(sig2_new); + if numel(trash)<1 + save('error_data','') + elseif (trash(end)-trash(1)) >= (length( (kernel2(1)+1) :max_length)-1) + xx = sum(sig1_new.*sig2_new); + y = [y,xx]; + x = [x,(j*dt)]; + + if xx > max(y(1:end-1)) + max_ind = j; + max_CC = xx; + else + end + else + end + end + + % Recreate max correlation to find the Correlation coefficient + j = max_ind; + if j<0 + sig2_new = [zeros(1,-j),sig2(1 : end-(-j)) ]; + else + sig2_new = [sig2(j+1:end),zeros(1,j)]; + end + + ind_x = find(sig2_new); + SumProx1 = sum(sig1_new(ind_x).^2); + SumProx2 = sum(sig2_new(ind_x).^2); + CC_ref = max(SumProx1,SumProx2); + + CrossCoeff = max_CC/CC_ref; + + loop=1; + i=1; + while loop==1 + i=i+1; + poly = polyfit(x(i-1:i+1),y(i-1:i+1),1); + if poly(1) > 10 + ind = i; + loop = 0; + end + if (i+1) == length(y) + ind = 1; + loop = 0; + end + end + + [~,I] = max(y(ind:end)); + I = I + (ind-1); + interp_span = 5; + + if length(y) < (I+interp_span) + interp_span = length(y) - I; + elseif (I-interp_span) < 1 + interp_span = I-1; + end + + interp_int = [I-interp_span:I+interp_span]; + int = find(interp_int); + interp_int = interp_int(int); + + poly = polyfit(x(interp_int),y(interp_int),2); + x1 = [x(1):0.001:x(end)]; + y1 = poly(1).*x1.^2 + poly(2).*x1 + poly(3); + + t_int = -poly(2)/(2*poly(1)); + +end","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/Additional Functions/TTAlgorithm1_11/14_12_19_Version09/Cycle_Approximator.m",".m","2006","67","function indmin = Cycle_Approximator(t,signal1) +% The primary use of this is as a pre-routine to find the cardiac time +% period T. With this, we can adjust the MAX/MIN threshold to be per +% cardiac cycle, so that we do not miss any pulses. + +signal = signal1(1,:); + +%%%%% The Identification of Peaks %%%%% +% indmax are the maxima positions, indmin are the minima positions +indmax = []; +indmin = []; + +threshold = 2.5.*sqrt(var( signal )); + +% Threshold should be set to the height of the smallest peak that should be +% detected +sa = signal(end); % sa is the maximal element since the last minimum +sb = signal(end); % sb is the minimum element since the last maximum +sc = 0; + +i=length(signal); +a=length(signal); +d=0; % d is the direction of the signal 0-indetermined direction, +% 1-from minimum to maximum, 2-from maximum to minimum +sigLen=length(signal); + +while (i > 1) + i=i-1; + if (d==0) % direction not yet determined + if (sa >= (signal(i)+threshold)) + d=2; % FALL + if (i < sigLen-3) + else + end + elseif (signal(i) >= (sb+threshold)) + d=1; % RISE + end; + if (sa <= signal(i)) + sa = signal(i); + a = i; + elseif (signal(i) <= sb) + sb = signal(i); + b = i; + end; + elseif (d==1) % direction from min to max (RISE) + if (sa <= signal(i)) + sa = signal(i); + a = i; + elseif (sa >= (signal(i)+threshold))% && ~isempty(indmin) + indmax = [indmax a]; + sb = signal(i); + b = i; + d=2; + end; + elseif (d==2) % direction from max to min (FALL) + if (signal(i) <= sb) + sb = signal(i); + b = i; + elseif (signal(i) >= (sb + threshold)) || (t(a) - t(i)) > 0.4 + indmin = [indmin b]; + sa = signal(i); + a = i; + d=1; + end; + end +end +","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/Additional Functions/TTAlgorithm1_11/14_12_19_Version09/TTAlgorithm.m",".m","5963","160","function TT = TTAlgorithm(signal,f,algorithm,waveform,continuous,show) +% Description: +% TTAlgorithm applies user defined pulse wave analysis algorithms in +% order to determine the transit time between two wave forms. This +% software assumes that the two waveforms are measured simultaneously, +% and no temporal alignment is needed. +% Features: +% - Foot to foot algorithm +% - Foot to foot radius algorithm +% - Cross correlation of the entire cycle +% - Least Squares +% +% signal - matrix with two physiological waveform vectors +% f - signal freqency (Hz), (note the frequency of the Test Doppler Data was 100Hz) +% algorithm - 1, 2, 3, or 4 refering to the above algorithms respectively +% waveform - 1, or 2, referring to pressure/area or velocity/flow respectively +% continuous - 0, or 1, indicating a single wave (0) or multiple waves (1) +% show - display location of 'feet' used for analysis, (1=yes, 0=no) +% TT - vector of transit times, length depends on number of waveforms +% +% ************ +% ** Please cite the following paper if used for publication ** +% +% N R Gaddum, J Alastruey, P Beerbaum, P Chowienczyk, T Schaeffter, +% A technical assessment of pulse wave velocity algorithms applied +% to non-invasive arterial waveforms, Annals of Biomedical Engineering, +% 2013, 41(12):2617-29. DOI: 10.1007/s10439-013-0854-y +% +% ************ +% +% Author: +% Dr. Nicholas Gaddum +% +% Revisions: +% 2012-Aug-06 Created function +% 2012-Aug-09 Removed replication of time parameters. Only frequency +% remaining. Added pressure/area vs. velocity/flow parameter for +% Find_Landmarks observer. Bug fixing. +% 2012-Aug-13 Revised README file. +% 2012-Aug-21 Pressure test data added to the Test Data File. Added +% recomendations. Changes to the scanning window for algorithm 1. +% 2013-Aug-10 Bug fixing for high resolution pressure/flow data. Higher +% stability for foot location using the minimum radius +% 2014-Mar-24 Updated README file. Added troubleshooting section +% 2014-Oct-02 Reduction of m files, and include option for single or +% multiple waveform analysis +% 2014-Dec-03 Bug fix for brachial-ankle, carotid-ankle data, where the +% feet have a greater spacing. Cross correlation bug fix +% 2014-Dec-19 Removed and unused .mat file +% 2016-Jun-10 Bug fixing for low temporal resolution MRI flow data, and +% added signal observers for better stability of Cross Correlation + +if nargin < 1 + error('Please specify a matrix of two waveform vectors') + return +elseif nargin == 1 + warning('Sample frequency, algorithm, and data type not chosen. Set to defaults, (f=100Hz, Foot to foot, pressure data)') + f = 100; + algorithm = 1; + waveform = 1; + show = 0; +elseif nargin == 2 + warning('Algorithm and data type not chosen. Set to defaults, (Foot to foot, pressure data)') + algorithm = 1; + waveform = 1; + show = 0; +elseif nargin == 3 + warning('Data type not chosen. Set to default, (pressure data)') + waveform = 1; + show = 0; +elseif nargin == 4 + show = 0; +else +end + +if algorithm > 4 + warning('Invalid ""algorithm"" code. Set to default, (foot to foot)') + algorithm = 1; +end +if waveform > 2 + warning('Invalid ""waveform"" code. Set to default, (velocity)') + waveform = 2; +end +if continuous > 1 + warning('Invalid ""continuous"" code. Set to default, (signal wave)') + continuous = 0; +end +if show > 1 + warning('Invalid ""show"" code. Set to default, (show plots)') + show = 1; +end +if f < 50 + warning('Check prescribed frequency, it appears to be too low') +end + +if show == 1 + if algorithm == 1 + fprintf('Using Foot to foot:\n') + elseif algorithm == 2 + fprintf('Using Foot to foot minimum radius:\n') + elseif algorithm == 3 + fprintf('Using Least Squares:\n') + elseif algorithm == 4 + fprintf('Using Cross Correlation of the entire cycle:\n') + end +end + +% Prepare data for processing, ensure signals are in two rows +if size(signal,1) > size(signal,2) + signal = signal'; +end +ind = find(abs(signal) < 10^(-10)); +signal(ind) = 10^(-10); % Replace zero data with near zero data, (for Cross correlation algorithm) + +dt = 1/f; +n = size(signal,2); +t = [0:dt:(n-1)*dt]; + +%%%%%%% NOTE, wave feet can be poorly located if your frequency is +%%%%%%% significantly low/high. In this case, try varying the value of the +%%%%%%% following two variables +npoly_1 = ceil(0.03*f); % number of terms taken in the linear polyfit +npoly1_1 = ceil(0.10*f); % number of terms taken in the trend radius calculations + +if continuous == 1 + t_intv = Cycle_Approximator(t,signal); +elseif continuous == 0 + t_intv = 0; + + % If a single cycle is used, (particularly important for MRI), add some + % extra data before the foot of each profile in order for the software + % to be able to scan the waveform through the foot of the waveform + n1 = 10; + Amp1 = max(signal(1,:)) - min(signal(1,:)); + m1 = Amp1 * 0.001; + Amp2 = max(signal(2,:)) - min(signal(2,:)); + m2 = Amp2 * 0.001; + noise = rand(1,n1) - 0.5; + trash = [signal(1,1)*ones(1,n1); signal(2,1)*ones(1,n1)] + [m1*noise; m2*noise]; + + signal = [trash, signal]; + t = [0:dt:(n-1+n1)*dt]; +end + +% Find maxima/minima/maximum gradients for all algorithms +[indmaxs,indmins,gradins] = Find_Landmarks(t,signal,t_intv,npoly_1,npoly1_1,f,algorithm,waveform,continuous,show); + +switch algorithm + case 3 + % Least Squares difference of the systolic upstroke + t_int = PWV_Calulator_Least_Squares(t,signal,indmaxs,indmins); + case 4 + % Cross correlation of the entire waveform + t_int = PWV_Calulator_CC_cycle(t,signal,indmaxs,indmins,gradins); + otherwise + % Both foot to foot algorithms + t_int = PWV_Calulator_FTF(t,signal,indmaxs,indmins,gradins,show); +end +TT = t_int; +","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/Additional Functions/TTAlgorithm1_11/14_12_19_Version09/Find_Landmarks.m",".m","16290","428","function [indmaxs,indmins,gradins] = Find_Landmarks(t,signal1,t_intv,npoly_1,npoly1_1,f,algorithm,waveform,continuous,show) +%%%%%%%%%%%%% Locate Minima, Maxima and Max Gradients %%%%%%%%%%%%% + +switch show + case 0 + case 1 + fig1 = figure(1); + set(fig1,'Position',[50 50 826 274]) + set(gca,'Position',[0.06 0.16 0.93 0.72]) + cla + hold on + plot(t,signal1(1,:),'k') + plot(t,signal1(2,:),'Color',[0.5 0.5 0.5]) + low = min(min(signal1)); + high = max(max(signal1)); + axis([ t(1) t(end) (low - 0.1*abs(low)) (high + 0.1*abs(high)) ]) + title('TT Analysis of Waveform Data','FontSize',16) + xlabel('Time (seconds)','FontSize',14) + ylabel('Waveform Magnitude','FontSize',14) + set(gca, 'Box', 'off' ); +end + +%%%%%%%%%%%%% Determine Minima, Maxima and Max Gradients - Start %%%%%%%%%%%%%%%%% +% signal1 = signal; +% t = t'; + +clear signal + +for j = 1:size(signal1,1) + %%%%% The Identification of Peaks %%%%% + % indmax are the maxima positions, indmin are the minima positions + indmax = nan; + indmin = []; + gradin = []; % Gradient info to store the index, gradient and y-intercept for the Find the Foot p-processing + intercept = []; % plotted locations upon the polynomial of max gradient + + signal = signal1(j,:); + + if length(t_intv) > 1 % i.e. numerous cycles, (continuous = 1) + threshold = 2.5.*sqrt(var( signal(t_intv(2) : t_intv(1) ) )); + if waveform == 1 + t_max_min = 0.50 * abs(mean(diff(t_intv)))/f; + elseif waveform == 2 + t_max_min = 0.3 * abs(mean(diff(t_intv)))/f; + end + else % i.e. single cycle, (continuous = 0) + threshold = 2.5.*sqrt(var( signal )); + if waveform == 1 + t_max_min = 0.50 * length(signal)/f; + elseif waveform == 2 + t_max_min = 0.3 * length(signal)/f; + end + end + + % Threshold should be set to the height of the smallest peak that should be + % detected + sa = min(signal); % sa is the maximal element since the last minimum + sb = max(signal); % sb is the gradient since the last maximum + sc = 0; % Start gradient off at a very high negative gradient, (i.e. mid/late systole) + + + trash = diff(signal); + equalAxisConst = (max(trash) / (t(2)-t(1))) / 10; + + i=length(signal)-2; + a=length(signal); + % d is the direction of the signal, 0-indetermined direction, + % 1-increasing, 2-decreasing, (note this is observing the waveform from + % the end to the beginning, i.e. t=end to t=t(1). + if continuous == 0 + d=1; % this case assumes that only one waveform is available, i.e. MRI + else + d=0; % thsi case assumes continuous data with numerous waveforms + end + e=0; + + if t_intv(1) >= i + count_thresh = 2; + else + count_thresh = 1; + end + + v_b = []; + + while (i > npoly_1) + npoly = npoly_1; + npoly1 = npoly1_1; + i=i-1; + + if i == t_intv(count_thresh)% + if (count_thresh+1) > length(t_intv) + if t_intv(count_thresh+1)<1 + count_thresh = count_thresh - 2; + else + end + threshold = 2.5.*sqrt(var( signal(t_intv( count_thresh+1) : t_intv(count_thresh) ) )); + count_thresh = count_thresh + 1; + end + else + end + + if (d==0) % direction not yet determined + if (sa >= (signal(i)+threshold)) + % d=2; % FALL + elseif (signal(i) >= (sb+threshold)) + d=1; % RISE + end; + if (sa <= signal(i)) + sa = signal(i); + a = i; + elseif (signal(i) <= sb) + sb = signal(i); + end; + + elseif (d==1) % direction from min to max (RISE) + if (sa <= signal(i)) + sa = signal(i); + a = i; + elseif (sa >= (signal(i)+threshold))% && ~isempty(indmin) + % In order to prevent a repeating location of maxima + % due to the regression of i to a, check for repitition + % of maxima. + if isnan(indmax) % I had to use an NAN starter, because I cannot get MATLAB to use isempty here + indmax = a; + i=a; + sb = inf; + else + if a == indmax(end) + else + indmax = [indmax a]; + i=a; + sb = inf; + end + end + sc = -10; + b = i; + d=2; + e=2; + end; + + elseif (d==2) && i < length(signal) || i < 6 %-limits1 && i > limits1 % direction from max to min (FALL) + % Adjust window size for gradient and radius of curvature + % approx.s near beginning/end of signal + if i < (round( (npoly1+1)/2)) + npoly1 = 2*i-1; + else + end + if i < (round( (npoly+1)/2)) + npoly = 2*i-1; + else + end + + if (i+ round( (npoly1+1)/2 )) > length(signal) + npoly1 = 2 * (length(signal)-i)-1; + else + end + if (i+ round( (npoly+1)/2 )) > length(signal) + npoly = 2 * (length(signal)-i)-1; + else + end + + % To find the first derivative - for point of max gradient + poly1 = polyfit(t(i+(round( (npoly+1)/2 )-1) :-1: i-(round( (npoly+1)/2 )-1)),... + signal(i+(round( (npoly+1)/2 )-1) :-1: i-(round( (npoly+1)/2 )-1)),1); + + if algorithm > 1 % If definition of minimum is at the point of maximum radius of curvature + % Use three points to estimate a radius of curvature + y_1 = mean(signal(i+1 : i+(floor(npoly1/2)))); + x_1 = mean( t(i+1 : i+(floor(npoly1/2)))) * equalAxisConst; + y_2 = signal(i); + x_2 = t(i) * equalAxisConst; + y_3 = mean(signal(i-1 : -1 : i-(floor(npoly1/2)))); + x_3 = mean( t(i-1 : -1 : i-(floor(npoly1/2)))) * equalAxisConst; + + % Form linear equations + ma = (y_2-y_1) / (x_2-x_1); + mb = (y_3-y_2) / (x_3-x_2); + + % Standardise the chord lengths + x_5 = linspace(x_2,x_1,20); + y_5 = ma.*(x_5 - x_2) + y_2; + x_6 = linspace(x_2,x_3,20); + y_6 = mb.*(x_6 - x_2) + y_2; + l_5 = sqrt((x_5 - x_2).^2 + (y_5 - y_2).^2); + l_6 = sqrt((x_6 - x_2).^2 + (y_6 - y_2).^2); + diff_1 = min(l_5(end),l_6(end)); + % Redefine (x_1,y_1) and (x_3,y_3), (points either side of + % signal(i) + ind = find(l_5 > diff_1,1,'first'); + if isempty(ind) + ind = length(l_5); + end + x_1 = x_5(ind); + y_1 = y_5(ind); + ind = find(l_6 > diff_1,1,'first'); + if isempty(ind) + ind = length(l_6); + end + x_3 = x_6(ind); + y_3 = y_6(ind); + + % Form linear equations + ma = (y_2-y_1) / (x_2-x_1); + mb = (y_3-y_2) / (x_3-x_2); + a1 = [ (x_1+x_2) / 2 , (y_1+y_2) / 2 ]; + b1 = [ (x_2+x_3) / 2 , (y_2+y_3) / 2 ]; + + % Coordinate of the centre of the LV arc + x_4 = ( b1(2)-a1(2) - (a1(1)/ma - b1(1)/mb) ) / (-1/ma + 1/mb); + y_4 = -1/ma * (x_4 - a1(1)) + a1(2); + + grad2 = ( ( (y_1-y_4)^2 + (x_1-x_4)^2 )^0.5 +... + ( (y_2-y_4)^2 + (x_2-x_4)^2 )^0.5 +... + ( (y_3-y_4)^2 + (x_3-x_4)^2 )^0.5 )/3; + + if (poly1(1) >= sc) && d==2 + sc = poly1(1); + grad_store = [poly1(1),poly1(2)]; + v = grad_store(1) * t(i) + grad_store(2); + c = [i ; poly1(1) ; poly1(2) ; v]; + else + end + + % Check if a new minimum radius of curvature has been reached + if (grad2 > 10^5*sb) || i < (npoly_1+1) || ((t(a) - t(i))>t_max_min) %&& && b~=size(signal,2)) + min_data = [b ; v_b]; + indmin = [indmin min_data]; + sa = signal(i); + d=1; + + if e==2 + gradin = [gradin c]; + intercept = [intercept (c(2)*t(c(1)) + c(3))]; + sc = 0; + e=1; + pause_grad = 1; + end + elseif (grad2 <= sb) && y_4 > y_2 && i~=5 && (signal(a)-signal(i))>threshold/2 %(t(a) - t(i))>0.05 + sb = grad2; + b = i; + % Mean velocity at t(i) + v_min = mean( signal(b+(round( (1+1)/2 )-1) :-1: b-(round( (1+1)/2 )-1)) ); + v_b = v_min; + end + + else % If definition of minimum is at the local minimum + if (poly1(1) >= sc) && d==2 + sc = poly1(1); + v = poly1(1) * t(i) + poly1(2); + c = [i ; poly1(1) ; poly1(2) ; v]; + else + end + + % Check if a new minimum has been reached + if signal(i) <= sb && ((t(a) - t(i))t_max_min) + min_data = [b ; v_b]; + indmin = [indmin min_data]; + sa = signal(i); + d=1; + + if e==2 + gradin = [gradin c]; + intercept = [intercept (c(2)*t(c(1)) + c(3))]; + sc = 0; + e=1; + pause_grad = 1; + end + end + end + end + end + + if isnan(indmax) + error('Could not determine features of the physiological waveform - please chack signal data...') + end + + switch show + case 0 + case 1 + figure(1) + plot(t(indmax),signal(indmax),'vk','MarkerSize',10,'Linewidth',1) + plot(t(indmin(1,:)),indmin(2,:),'^k','MarkerSize',10,'Linewidth',1) + plot(t(gradin(1,:)),gradin(4,:),'ok','MarkerSize',10,'Linewidth',1) + end + + indmaxs(j,1:length(indmax)) = indmax'; + indmins(j,1:size(indmin,2),1:2) = indmin'; + gradins(j,1:size(gradin,2),1:4) = gradin'; +end + +if continuous == 0 + if size(indmaxs,2) > 1 + error('Data appears to be continuous, i.e. multiple cycles. If so, then please set the CONTINUOUS parameter to 1') + end +end +if continuous == 1 + if size(indmaxs,2) < 2 + error('Data appears to be a single cycle. If so, then please set the CONTINUOUS parameter to 0') + end +end + +%%%%%%%%%%%%% Determine Minima, Maxima and Max Gradients - End %%%%%%%%%%%%%%%%% + + +%%%%%%%%%%%%% Minima, Maxima and Max Gradients Sorting - Start %%%%%%%%%%%%%%%%% +% Ensure that similar cycles are compared +trash1 = find(gradins(1,:,1)); +trash2 = find(gradins(2,:,1)); + +ind1 = gradins(1,trash1,1); +ind2 = gradins(2,trash2,1); + +% Determine the standard deviation between the number of data points between +% successive cycles for both signals. Which ever has the lowest standard +% deviation will be used as the reference vector, (assuming this has the +% least noise/variabilit etc. +diff1 = ind1(1,1:end-1) - ind1(1,2:end); +diff1_std = std(diff1); + +diff2 = ind2(1,1:end-1) - ind2(1,2:end); +diff2_std = std(diff2); + +ind1_new = []; +ind2_new = []; + +% Based on +trash_g = []; +TTWindow = 0.25; % corresponding feet will be scanned to ensure they are within +/- 25% of the reference point + +while isempty(trash_g) % In case TTWindow is too small, (e.g. if carotid/ankle waveforms; high delay) + count = 1; + if diff1_std < diff2_std % signal 1 = reference feet + std_int = median(diff1); % Median number of points between reference feet + + l1 = length(ind1); + l2 = length(ind2); + for i=1:l1 + % Locate the nearest point to the reference by creating a + % 'mask', this is done by subtracting all the non-reference indexes + % from the current point on the reference vector + trash1 = abs(ones(1,l2).*ind1(i) - ind2); + trash2 = find(trash1 > (std_int*TTWindow)); + trash1(trash2) = nan; + if length(ind2) > length(trash2) % ensure the compared index length is greater than the mask length + [~,I] = min(trash1); + + trash_m(1,count,:) = indmins(1,i,:); + trash_m(2,count,:) = indmins(2,I,:); + + trash_g(1,count,:) = gradins(1,i,:); + trash_g(2,count,:) = gradins(2,I,:); + + trash_n(1,count,:) = indmaxs(1,i); + trash_n(2,count,:) = indmaxs(2,I); + + count = count + 1; + end + end + else % signal 2 = reference feet + std_int = median(diff2); % Median number of points between reference feet + + l1 = length(ind1); + l2 = length(ind2); + for i=1:l2 + % Locate the nearest point to the reference by creating a + % 'mask', this is done by subtracting all the non-reference indexes + % from the current point on the reference vector + trash1 = abs(ones(1,l1).*ind2(i) - ind1); + trash2 = find(trash1 > (std_int*TTWindow)); + trash1(trash2) = nan; + if length(ind1) > length(trash2) % ensure the compared index length is greater than the mask length + [~,I] = min(trash1); + + trash_m(2,count,:) = indmins(2,i,:); + trash_m(1,count,:) = indmins(1,I,:); + + trash_g(2,count,:) = gradins(2,i,:); + trash_g(1,count,:) = gradins(1,I,:); + + trash_n(2,count,:) = indmaxs(2,i); + trash_n(1,count,:) = indmaxs(1,I); + + count = count + 1; + end + end + end + TTWindow = TTWindow + 0.1; +end + +%%%%%%%%%%%%% Minima, Maxima and Max Gradients Sorting - End %%%%%%%%%%%%%%%%% + +clear gradins indmins indmaxs +gradins = trash_g; +indmins = trash_m; +indmaxs = trash_n; + +switch show + case 0 + case 1 + figure(1) + for i=1:2 + plot(t(indmaxs(i,:)),signal1(i,indmaxs(i,:)),'vr','MarkerSize',12,'Linewidth',1) + plot(t(indmins(i,:,1)),indmins(i,:,2),'^r','MarkerSize',12,'Linewidth',1) + plot(t(gradins(i,:,1)),gradins(i,:,4),'or','MarkerSize',12,'Linewidth',1) + end +end + +if continuous == 1 + % Ensure that signals 1 and 2 are in the correct order + diff_ind = indmins(1,:,1) - indmins(2,:,1); + trash = median(diff_ind); + + if trash < 0 + else + signal1 = flipud(signal1); + + indmins = flipdim(indmins,1); + indmaxs = flipdim(indmaxs,1); + gradins = flipdim(gradins,1); + end +end +signal = signal1';","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/Additional Functions/TTAlgorithm1_11/14_12_19_Version09/PWV_Calulator_Least_Squares.m",".m","7647","236","function t_int= PWV_Calulator_Least_Squares(t,signal,indmaxs,indmins) + +%%%%%%%%%%%%% Least Squares - Start %%%%%%%%%%%%% + +dt = t(2)-t(1); + +trash = diff(indmaxs); +trash = median(trash); + +ind = find(indmins(1,:,1)); +kernel1_tot = [indmins(1, : ,1);indmaxs(1, : )]; +ind = find(indmins(2,:,1)); +kernel2_tot = [indmins(2, : ,1);indmaxs(2, : )]; +Prox = 4; + +pixPCycle = round(abs(mean(diff(kernel1_tot(1,:))))); + +padding1 = round(pixPCycle/3); +padding2 = round(2*pixPCycle/3); + +count = 1; + +if length(ind) > 1 % if there are more than one cycles + + for k = 2:length(ind) + + kernel1 = kernel1_tot(:,k); + kernel2 = kernel2_tot(:,k); + + if kernel1(1) kernel2(1) + kernel1(1) = kernel2(1); + end + shift = round( abs(kernel1(2) - kernel1(1))); + + max_lengthBack = max( [(kernel1(2) - kernel1(1)) , (kernel2(2) - kernel2(1)) , abs(kernel2(2) - kernel1(1))] ); + max_lengthForward = round(max_lengthBack/2); + + if size(signal,2) < kernel2(2)+max_lengthForward + max_lengthForward = round(size(signal,2) - kernel2(2)); + end + + % Normalise the signals and lift off the x axis + min1 = min(signal(1,kernel1(1):kernel1(2))); + trash1 = signal(1,:) - min1; + sig1_norm = trash1/(trash1(kernel1(2))) + 0.05; + + min2 = min(signal(2,kernel2(1):kernel2(2))); + trash1 = signal(2,:) - min2; + sig2_norm = trash1/(trash1(kernel2(2))); + + sig2_base = zeros(1,length(t)); + lim1 = kernel2(2)-max_lengthBack; + if lim1 < 1 + lim1 = 1; + end + lim2 = kernel2(2)+max_lengthForward; + if lim2 > length(sig2_base) + lim2 = length(sig2_base); + end + sig2_base(lim1:lim2) = sig2_norm(lim1:lim2) + 0.05; + + if (kernel1(1) - padding1) < 1 + padding1 = kernel1(1) - 1; + elseif (kernel1(2) + padding2) >= length(t) + padding2 = length(t) - kernel1(2); + end + + % Signals for least squares correlation + sig1_new = sig1_norm(kernel1(1)-padding1 : kernel1(2)+padding2); + sig2 = sig2_base(kernel1(1)-padding1 : kernel1(2)+padding2); + + CCLength = length(find(sig2)); + + y = []; + x = []; + + loop = 1; + j = -round(shift); + + while loop == 1 + if j<0 + sig2_new = [zeros(1,-j),sig2(1 : end-(-j)) ]; + else + sig2_new = [sig2(j+1:end),zeros(1,j)]; + end + + trash = find(sig2_new); + if (trash(end)-trash(1)) >= round(CCLength*0.7) + trash = (sig1_new.*sig2_new); + [C,I] = find(trash); + LS = 0; + if numel(I)>0 + LS = sum( (sig1_new(I) -sig2_new(I)).^2 ); + else + LS = 20; + end + + y = [y,LS]; + x = [x,(j*dt)]; + + j = j+1; + ind = find(sig2_new); + if ind < (max_lengthBack+1) + loop = 0; + end + else + if isempty(y) + j = j+1; + else + loop = 0; + skip = 1; + end + end + end + + intZero = find(x==0); + + if ~isempty(intZero) + + trash1 = diff(y); + MaxMinInd = find(trash1(1:end-1).*trash1(2:end)<0)+1; + if length(MaxMinInd)>1 + MaxMin = y(MaxMinInd); + startGrad = diff(MaxMin(1:2)); + if startGrad > 0 + trash2 = MaxMinInd(1:2:end); + else + trash2 = MaxMinInd(2:2:end); + end + else + trash2 = MaxMinInd; + end + + trash3 = abs( (intZero+Prox - trash2)); + trash4 = (trash3) .* y(trash2); + [~,ind] = min(trash4); + I = trash2(ind); + + interp_span = 1; + if (I+interp_span) > length(y) + I = length(y) - interp_span; + elseif (I-interp_span) < 1 + I = 1 + interp_span; + end + interp_int = [I-interp_span:I+interp_span]; + int = find(interp_int>0); + interp_int = interp_int(int); + + poly = polyfit(x(interp_int),y(interp_int),2); + x1 = [x(1):0.001:x(end)]; + y1 = poly(1).*x1.^2 + poly(2).*x1 + poly(3); + + m_TT = -poly(2)/(2*poly(1)); + + t_int(count) = m_TT; + count = count+1; + skip = 0; + else + t_int(count) = nan; + count = count+1; + end + end + end + +else + + ind = indmins(:,:,1); + kernel1 = [indmins(1,:,1) , indmaxs(1)]; + kernel2 = [indmins(2,:,1) , indmaxs(2)]; + + shift = max( round( abs(kernel1(2) - kernel1(2))*5 ),20 ); + + max_length = max( [(kernel1(2) - kernel1(1)) , (kernel2(2) - kernel2(1))] ); + + trash1 = signal(1,:) - signal(1,kernel1(1)); + sig1_norm = trash1/(trash1(kernel1(2))) + 0.05; + + trash1 = signal(2,:) - signal(2,kernel2(1)); + sig2_norm = trash1/(trash1(kernel2(2))); + + sig2_base = zeros(1,length(t)); + sig2_base(kernel2(2)-max_length:kernel2(2)) = sig2_norm(kernel2(2)-max_length:kernel2(2)) + 0.05; + + y = []; + x = []; + + loop = 1; + j = -round(shift/4); + while loop == 1 + if j<0 + sig2_new = [zeros(1,-j),sig2_base(1 : end-(-j)) ]; + else + sig2_new = [sig2_base(j+1:end),zeros(1,j)]; + end + + trash = find(sig2_new); + if numel(trash)<1 + loop = 0; + elseif (trash(end)-trash(1)) >= (kernel2(2) - kernel2(1)-1) + trash = (sig1_norm.*sig2_new); + [C,I] = find(trash); + LS = 0; + if numel(I)>0 + LS = sum( (sig1_norm(I) -sig2_new(I)).^2 ); + else + LS = 20; + end + + y = [y,LS]; + x = [x,(j*dt)]; + + j = j+1; + ind = find(sig2_new); + if ind < (max_length+1) + loop = 0; + end + else + end + end + + [~,I] = min(y); + interp_span = 5; + if (I+interp_span) > length(y) + I = length(y) - interp_span; + elseif (I-interp_span) < 1 + I = 1 + interp_span; + end + interp_int = [I-interp_span:I+interp_span]; + int = find(interp_int>0); + interp_int = interp_int(int); + + poly = polyfit(x(interp_int),y(interp_int),2); + + t_int = -poly(2)/(2*poly(1)); +end","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/Additional Functions/TTAlgorithm1_11/14_12_19_Version09/PWV_Calulator_FTF.m",".m","1014","36","function [t_int,t_foot,horint] = PWV_Calulator_FTF(t,signal,indmaxs,indmins,gradins,show) + +%%%%%%%%%%%%% Find the 'Feet - Start %%%%%%%%%%%%% +lin = min(length(indmaxs),size(indmins,2)); +lin = min(lin,size(gradins,2)); + +for i=1:size(signal,1) + for j = 1:size(gradins,2) + if gradins(i,j,1) == 0 || indmins(i,j,1) == 0 + else + % Horizontal limits + centre = indmins(i,j,1); + space = 1; + horint(i,j) = mean( signal(i, (centre-space):(centre+space) ) ); % Add one to align minima and gradient coordinates + + % Locate trasnient intercept + t_foot(i,j) = (horint(i,j) - gradins(i,j,3))/(gradins(i,j,2)); + ind(i,j) = gradins(i,j,1); + end + end +end +TT = t_foot(2,:) - t_foot(1,:); +if median(TT) < 0 + TT = -TT; +end + +switch show + case 0 + case 1 + plot(t_foot,horint,'rx','MarkerSize',12,'Linewidth',2) +end + +non_zeros = find(t_foot(1,:).*t_foot(2,:)); + +t_int = TT; +","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/Additional Functions/extras/calculate_aorta_leg_segment_radii.m",".m","9289","274","function calculate_aorta_leg_segment_radii + +close all +up.matched_ratio = 1.15; +up.Dsys_Ddia_ratio = 1.08; % looks approximately right from an initial simulation + +%% Load data + +% Give details of the Excel file which contains the baseline model geometry: +up.network_spec_sheet = 'Haemod 116 segments'; +curr_filepath = fileparts(mfilename('fullpath')); +up.network_spec_file = [curr_filepath, '/input_data/116_artery_model_v10_after_hand_adj_bef_aorta_adj.xlsx']; +[num,txt,raw] = xlsread(up.network_spec_file, up.network_spec_sheet); +rel_col = strcmp(raw(1,:), 'Segment No'); +network_spec.seg_no = num(:, rel_col); +rel_col = strcmp(raw(1,:), 'Inlet node'); +network_spec.inlet_node = num(:, rel_col); +rel_col = strcmp(raw(1,:), 'Outlet node'); +network_spec.outlet_node = num(:, rel_col); +rel_col = strcmp(raw(1,:), 'Length [m]'); +network_spec.length = num(:, rel_col); +rel_col = strcmp(raw(1,:), 'Inlet Radius [m]'); +network_spec.inlet_radius = num(:, rel_col); +rel_col = strcmp(raw(1,:), 'Outlet Radius [m]'); +network_spec.outlet_radius = num(:, rel_col); +rel_col = strcmp(raw(1,:), 'Mynard Name'); +network_spec.segment_name = raw(2:size(num,1)+1, rel_col); +a = network_spec; + +%% Identify segments to be changed + +aorta_segs = [1 2 14 18 27 28 35 37 39 41]; +leg_segs = 42:55; + +%% Initial data + +lengths = a.length; +old_inlet_areas = pi*(a.inlet_radius.^2); +old_outlet_areas = pi*(a.outlet_radius.^2); + +%% Desired data (diameters) +desired_rads = []; + +% Asc Aorta (Hickson L1) +rel_el = 1; +rel_dist_prop = 0.5; +article_data.val.age = [24,34,45,57,63,73]; +article_data.val.v = 10 + (25*[35.5,38.5,41.75,42.0,44.0,44.5]./47); +article_dia_mm = interp1(article_data.val.age, article_data.val.v, 25); +desired_rad = article_dia_mm/(2000*up.Dsys_Ddia_ratio); +desired_rads = [desired_rads; rel_el, rel_dist_prop, desired_rad]; + +% Desc Thor Aorta (Hickson L2) +rel_el = 18; +rel_dist_prop = 0.5; +article_data.val.age = [24,34,45,57,63,73]; +article_data.val.v = 10 + (25*[48,53.5,58.5,58,65,64.5]./108); +article_dia_mm = interp1(article_data.val.age, article_data.val.v, 25); +desired_rad = article_dia_mm/(2000*up.Dsys_Ddia_ratio); +desired_rads = [desired_rads; rel_el, rel_dist_prop, desired_rad]; + +% Diaphragm (Hickson L3) %% CHECK +rel_el = 27; +rel_dist_prop = 0.9; +article_data.val.age = [24,34,45,57,63,73]; +article_data.val.v = 10*[1.85, 1.9, 2.05, 2.05, 2.2, 2.25]; +article_dia_mm = interp1(article_data.val.age, article_data.val.v, 25); +desired_rad = article_dia_mm/(2000*up.Dsys_Ddia_ratio); +desired_rads = [desired_rads; rel_el, rel_dist_prop, desired_rad]; + +% Abd Aorta (Hickson L4) +rel_el = 39; +rel_dist_prop = 0.1; +article_data.val.age = [24,34,45,57,63,73]; +article_data.val.v = 10 + (25*[29.5,35,38,37,42.5,44]./108); +article_dia_mm = interp1(article_data.val.age, article_data.val.v, 25); +desired_rad = article_dia_mm/(2000*up.Dsys_Ddia_ratio); +desired_rads = [desired_rads; rel_el, rel_dist_prop, desired_rad]; + +% 3cm above Aortic Bifurcation (Hickson L5) %% CHECK +rel_el = 39; +rel_dist_prop = 0.9; +article_data.val.age = [24,34,45,57,63,73]; +article_data.val.v = 10*[1.6, 1.65, 1.65, 1.7, 1.75, 1.75]; +article_dia_mm = interp1(article_data.val.age, article_data.val.v, 25); +desired_rad = article_dia_mm/(2000*up.Dsys_Ddia_ratio); +desired_rads = [desired_rads; rel_el, rel_dist_prop, desired_rad]; + +% Calculate lengths along aorta +for s = 1 : size(desired_rads,1) + rel_seg_no = desired_rads(s,1); + rel_prop = desired_rads(s,2); + temp = find(aorta_segs == rel_seg_no); + rel_full_els = aorta_segs(1:temp-1); + lens(s,1) = sum(lengths(rel_full_els)) + rel_prop*lengths(rel_seg_no); +end + +%% Fit curve to measured radii +rads = desired_rads(:,3); +tbl = table(lens,rads); +%mdl = fitlm(tbl,'quadratic'); +f = fit(lens,rads,'cubicinterp'); +%plot(f,lens,rads) + +%% Plot fitted and actual data +% Calculate fitted +rel_segs = aorta_segs; +dists = [0; cumsum(a.length(rel_segs))]; +fitted = feval(f,0:0.01:dists(end)); +% Plot fitted +subplot(1,2,1) +plot(0:0.01:dists(end), fitted*2000); hold on +plot(lens, rads*2000, '*k'); hold on +% Calculate actual +d1 = dists(1:end-1); r1 = a.inlet_radius(rel_segs); +d2 = dists(2:end); r2 = a.outlet_radius(rel_segs); +[~,order] = sort([d1;d2]); +for s = 1 : length(d1) + d(2*s-1) = d1(s); d(2*s) = d2(s); r(2*s-1) = r1(s); r(2*s) = r2(s); +end +% Plot actual +subplot(1,2,1) +plot(d,2*1000*r) + +%% Find old reflection ratios +for seg_no = 1 : length(a.outlet_node) + curr_outlet_node = a.outlet_node(seg_no); + inlet_segs = find(a.inlet_node == curr_outlet_node); + inlet_seg_radii = a.inlet_radius(inlet_segs); + outlet_area = pi*a.outlet_radius(seg_no)^2; + inlet_area = sum(pi*inlet_seg_radii.^2); + refl_ratios(seg_no,1) = outlet_area / inlet_area; +end + +%% New data +new = a; +for seg_no = 1 : length(aorta_segs) + curr_seg = aorta_segs(seg_no); + % Remove any tapering from this segment + new.outlet_radius(curr_seg) = new.inlet_radius(curr_seg); + % Adjust the next segment's inlet radius to ensure that the same ratio is kept + outlet_area = pi*new.outlet_radius(curr_seg)^2; + curr_outlet_node = a.outlet_node(curr_seg); + inlet_segs = find(a.inlet_node == curr_outlet_node); + inlet_seg_radii = a.inlet_radius(inlet_segs); + inlet_area = sum(pi*inlet_seg_radii.^2); + curr_refl_ratio = outlet_area / inlet_area; + desired_refl_ratio = refl_ratios(curr_seg); + area_scaling = curr_refl_ratio/desired_refl_ratio; + radius_scaling = sqrt(area_scaling); + new.inlet_radius(inlet_segs) = inlet_seg_radii*radius_scaling; + +end + +%% Find new reflection ratios (just to check) +for seg_no = 1 : length(aorta_segs) + curr_seg = aorta_segs(seg_no); + curr_outlet_node = new.outlet_node(curr_seg); + inlet_segs = find(new.inlet_node == curr_outlet_node); + inlet_seg_radii = new.inlet_radius(inlet_segs); + outlet_area = pi*new.outlet_radius(curr_seg)^2; + inlet_area = sum(pi*inlet_seg_radii.^2); + new_refl_ratios(seg_no,1) = outlet_area / inlet_area; +end + +%% Plot new actual (aorta) + +% Calculate actual +d1 = dists(1:end-1); r1 = new.inlet_radius(rel_segs); +d2 = dists(2:end); r2 = new.outlet_radius(rel_segs); +for s = 1 : length(d1) + d(2*s-1) = d1(s); d(2*s) = d2(s); r(2*s-1) = r1(s); r(2*s) = r2(s); +end +% Plot actual +subplot(1,2,1) +plot(d,2*1000*r) + +%% Find old leg tapering proportions +for s = 1 : length(leg_segs) + + % Inlet radius has already been increased + + % Find old tapering proportions + curr_seg = leg_segs(s); + old_outlet_area = pi*(a.outlet_radius(curr_seg)^2); + old_inlet_area = pi*(a.inlet_radius(curr_seg)^2); + old_prop_tapering = old_outlet_area/old_inlet_area; + + % Adjust outlet radius to keep old tapering proportions + new_inlet_area = pi*(new.inlet_radius(curr_seg)^2); + new_outlet_area = new_inlet_area*old_prop_tapering; + new.outlet_radius(curr_seg) = sqrt(new_outlet_area/pi); + + % Adjust inlet radii of next segments to maintain reflection ratio + curr_outlet_node = new.outlet_node(curr_seg); + inlet_segs = find(new.inlet_node == curr_outlet_node); + inlet_seg_radii = new.inlet_radius(inlet_segs); + inlet_area = sum(pi*inlet_seg_radii.^2); + curr_refl_ratio = new_outlet_area / inlet_area; + desired_refl_ratio = refl_ratios(curr_seg); + area_scaling = curr_refl_ratio/desired_refl_ratio; + radius_scaling = sqrt(area_scaling); + new.inlet_radius(inlet_segs) = inlet_seg_radii*radius_scaling; +end + +%% Plot old actual (legs) + +init_dist = dists(end); +rel_segs = [42, 44, 46, 48]; +rel_segs = [43, 50, 52, 55]; +dists = cumsum([init_dist; a.length(rel_segs)]); + +% Calculate actual +d1 = dists(1:end-1); r1 = a.inlet_radius(rel_segs); +d2 = dists(2:end); r2 = a.outlet_radius(rel_segs); +clear d r +for s = 1 : length(d1) + d(2*s-1) = d1(s); d(2*s) = d2(s); r(2*s-1) = r1(s); r(2*s) = r2(s); +end +% Plot actual +subplot(1,2,2) +plot(d,2*1000*r), hold on + +%% Plot new actual (legs) + +% Calculate actual +d1 = dists(1:end-1); r1 = new.inlet_radius(rel_segs); +d2 = dists(2:end); r2 = new.outlet_radius(rel_segs); +[~,order] = sort([d1;d2]); +for s = 1 : length(d1) + d(2*s-1) = d1(s); d(2*s) = d2(s); r(2*s-1) = r1(s); r(2*s) = r2(s); +end +% Plot actual +subplot(1,2,2) +plot(d,2*1000*r) + + + +%% Output new radii + +for seg_no = [aorta_segs, leg_segs] + fprintf(['\n new_inlet_radius(' num2str(seg_no) ') = ' num2str(new.inlet_radius(seg_no),4) ]); +end +for seg_no = [aorta_segs, leg_segs] + fprintf(['\n new_outlet_radius(' num2str(seg_no) ') = ' num2str(new.outlet_radius(seg_no),4) ]); +end + +end + +function new_areas = modify_bifurcations(new_areas, inlet_seg, outlet_seg1, outlet_seg2, up) + +prop1 = new_areas(outlet_seg1)/(new_areas(outlet_seg2) + new_areas(outlet_seg1)); + +new_total_area = new_areas(inlet_seg)*up.matched_ratio; + +new_areas(outlet_seg1) = prop1*new_total_area; +new_areas(outlet_seg2) = (1-prop1)*new_total_area; + +end + +function new_areas = modify_common_areas(old_areas, new_areas, common_seg, inlet1, inlet2, up) + +old_prop = mean([old_areas(common_seg)/old_areas(inlet1), old_areas(common_seg)/old_areas(inlet2)]); + +new_areas(common_seg) = old_prop*mean([new_areas(inlet1), new_areas(inlet2)]); + +end + +function new_areas = modify_terminal_branches(old_areas, new_areas, terminal_seg, inlet_seg) + +old_prop = old_areas(terminal_seg)/old_areas(inlet_seg); +new_areas(terminal_seg) = old_prop*new_areas(inlet_seg); + +end","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/Additional Functions/extras/check_pwdb_processing.m",".m","5288","162","function check_pwdb_processing(pwdb_no, collated_data) + +fprintf('\n --- Checking PWDB processing ---') + +% Setup paths with current simulation paths +PATHS = setup_paths_for_post_processing(pwdb_no); + +% setup +up = setup_up; + +% load data +if nargin == 2, up.use_exported_data = 0; end +if up.use_exported_data + load(PATHS.exported_data_mat_pwdb_data) +else + if ~exist('collated_data', 'var'), load(PATHS.collated_data), end + data = convert_collated_data(collated_data); +end + +% Check PWA +check_pwa(data,up); + +% check PW extraction +check_pw_extraction(data, up) + +end + +function up = setup_up + +up.pw_duration_range = [0.5, 1.0]; + +up.use_exported_data = 1; + +end + +function check_pwa(data,up) + +% check whether haemod params have been extracted +no_subjs = length(data.haemods); +no_nans = nan(no_subjs,1); +for subj_no = 1 : length(data.haemods) + a = struct2cell(data.haemods); a = cell2mat(a(:,:,1)); + no_nans(subj_no) = sum(isnan(a)); +end + + +end + +function check_pw_extraction(data, up) + +% Identify names of waves to be checked +wave_names = fieldnames(data.waves); +wave_keep = true(length(wave_names),1); +for s = 1 : length(wave_names) + curr_wave = wave_names{s}; + if ~sum(strcmp(curr_wave(1), {'P', 'U', 'A'})) + wave_keep(s) = false; + end +end +wave_names = wave_names(wave_keep); + +% check each wave in turn +error_subjs_aortic = false(length(data.config.age),1); +error_subjs_others = false(length(data.config.age),1); +for wave_no = 1 : length(wave_names) + lens = nan(length(data.config.age),1); + for subj_no = 1 : length(data.config.age) + eval(['curr_wave_data = data.waves.' wave_names{wave_no} '{subj_no};']) + lens(subj_no) = length(curr_wave_data); + end + tol = up.pw_duration_range*data.waves.fs; + rel_els = lens > tol(2) | lens < tol(1); + if ~isempty(strfind(wave_names{wave_no}, 'AorticRoot')) + error_subjs_aortic(rel_els) = true; + else + error_subjs_others(rel_els) = true; + end +end + +% output answer +if sum(error_subjs_aortic) + fprintf('\n Problems extracting aortic root waves') +end +if sum(error_subjs_others) + fprintf('\n Problems extracting non-aortic root waves') +end +if ~sum(error_subjs_aortic) & ~sum(error_subjs_others) + fprintf('\n No problems extracting waves') +end + +end + +function data = convert_collated_data(collated_data) + +fprintf('\nConverting collated data: ') + +% - sampling frequency +data.waves.fs = collated_data(1).output_data(1).fs; + +% - age +data.config.age = nan(length(collated_data),1); +for subj_no = 1 : length(collated_data) + data.config.age(subj_no) = collated_data(subj_no).input_data.sim_settings.age; +end + +% - waves + +% setup +sites = {'AorticRoot', 'ThorAorta', 'AbdAorta', 'IliacBif', 'Carotid', 'SupTemporal', 'SupMidCerebral', 'Brachial', 'Radial', 'Digital', 'CommonIliac', 'Femoral', 'AntTibial'}; +site_domain_no = [1, 18, 39, 41, 15, 87, 72, 21, 22, 112, 44, 46, 49]; +site_dist_prop = [0, 1, 0, 1, 0.5, 1, 1, 0.75, 1, 1, 0.5, 0.5, 1]; +signals = {'P', 'U', 'A', 'PPG'}; % omit 'Q' as it's U.*A + +% identify domains which are available +domains = extractfield(collated_data(1).output_data, 'domain_no'); +[~,rel_els,~] = intersect(site_domain_no, domains); +site_domain_no = site_domain_no(rel_els); +sites = sites(rel_els); +site_dist_prop = site_dist_prop(rel_els); + +for subj_no = 1 : length(collated_data) + fprintf([num2str(subj_no) ', ']) + for site_no = 1 : length(sites) + for sig_no = 1 : length(signals) + + % identify name of wave at this site + wave_site_name = [signals{sig_no}, '_', sites{site_no}]; + + % make variable if required + if ~sum(strcmp(fieldnames(data.waves), wave_site_name)) + eval(['data.waves.' wave_site_name ' = cell(length(collated_data),1);']) + end + + % - extract wave + + % Identify site-specific info + curr_domain_no = site_domain_no(site_no); + curr_domain_el = domains == curr_domain_no; + curr_site_dist_prop = site_dist_prop(site_no); + + % Identify the relevant data for this simulation at this site + seg_length = collated_data(subj_no).input_data.sim_settings.network_spec.length(curr_domain_no); + dists = extractfield(collated_data(subj_no).output_data(curr_domain_el), 'distances'); + [~,rel_dist_el] = min(abs(curr_site_dist_prop*seg_length-dists)); clear dists + + % Extract wave + if strcmp(signals{sig_no}, 'P') + factor = 133.33; + else + factor = 1; + end + eval(['temp = collated_data(subj_no).output_data(curr_domain_el).' signals{sig_no} '(:,rel_dist_el)/factor;']) + + % store this wave + eval(['data.waves.' wave_site_name '{subj_no} = temp;']); + + clear temp factor curr_sig curr_sig_data rel_wave_data seg_length rel_dist_el curr_domain_no curr_domain_el curr_site_dist_prop curr_site + end + end +end + +end","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/Additional Functions/extras/copy_pwdb_files.m",".m","2293","73","function copy_pwdb_files(pwdb_no) + +PATHS = setup_paths_for_post_processing(pwdb_no); + +source_dir = '/Volumes/pete_data/201901_PWDB_complete/'; +source_dir = '/Volumes/pete_data/201902_PWDB_initial/'; +req_domains = [1,2,3,4,7,14,15,16,18,19,21,22,27,28,35,37,39,41,42,44,46,49,65,71,72,79,84,87,96,108,112]; +req_domains = [3,4]; +doing_extra_files = 1; + +% copy input files +max_subjs = 21; +for subj_no = 1 : max_subjs + + fprintf(['\n ' num2str(subj_no)]) + + % check that this subject exists + curr_filepath = [source_dir, 'sim_' num2str(subj_no) '.in']; + if ~exist(curr_filepath, 'file') + break + end + + % copy input files + if ~doing_extra_files + file_exts = {['sim_' num2str(subj_no) '.mat']; + ['sim_' num2str(subj_no) '.in']; + ['sim_' num2str(subj_no) '_IN_1.bcs']}; + for file_no = 1 : length(file_exts) + in_file = [source_dir, file_exts{file_no}]; + out_file = [PATHS.InputFiles, file_exts{file_no}]; + copyfile(in_file, out_file); + end + end + + % copy output files for each required domain + for dom_no = 1 : length(req_domains) + curr_dom = req_domains(dom_no); + file_exts = {['sim_' num2str(subj_no) '_' num2str(curr_dom) '.his'], ... + ['sim_' num2str(subj_no) '_out_' num2str(curr_dom) '.lum']}; + for file_no = 1 : length(file_exts) + in_file = [source_dir, file_exts{file_no}]; + out_file = [PATHS.OutputFiles, file_exts{file_no}]; + if exist(in_file, 'file') + method = 'rsync'; % or 'copyfile' + do_copy(in_file, out_file, method); + end + end + end + + % copy remaining output files + if ~doing_extra_files + file_exts = {['sim_' num2str(subj_no) '_period.tex']}; + for file_no = 1 : length(file_exts) + in_file = [source_dir, file_exts{file_no}]; + out_file = [PATHS.OutputFiles, file_exts{file_no}]; + copyfile(in_file, out_file); + end + end + +end + +end + +function do_copy(in_file, out_file, method) + +if strcmp(method, 'rsync') + command = ['rsync ' in_file ' ' , out_file]; + [status,cmdout] = system(command,'-echo'); +elseif strcmp(method, 'copyfile') + copyfile(in_file, out_file); +end + +end","MATLAB" +"In Silico","peterhcharlton/pwdb","pwdb_v0.1/Additional Functions/extras/calculate_hand_artery_segment_radii.m",".m","6503","128","function calculate_hand_artery_segment_radii + +up.matched_ratio = 1.15; % as stated in the introduction of: Greenwald SE, Newman DL. Impulse propagation through junctions. Med Biol Eng Comput 20: 343?350, 1982. + +% %% Load data +% +% % Give details of the Excel file which contains the baseline model geometry: +% up.network_spec_sheet = 'Haemod 116 segments'; +% curr_filepath = fileparts(mfilename('fullpath')); +% up.network_spec_file = [curr_filepath, '/input_data/116_artery_model_v10_before_hand_adj.xlsx']; +% [num,txt,raw] = xlsread(up.network_spec_file, up.network_spec_sheet); +% rel_col = strcmp(raw(1,:), 'Segment No'); +% network_spec.seg_no = num(:, rel_col); +% rel_col = strcmp(raw(1,:), 'Inlet node'); +% network_spec.inlet_node = num(:, rel_col); +% rel_col = strcmp(raw(1,:), 'Outlet node'); +% network_spec.outlet_node = num(:, rel_col); +% rel_col = strcmp(raw(1,:), 'Length [m]'); +% network_spec.length = num(:, rel_col); +% rel_col = strcmp(raw(1,:), 'Inlet Radius [m]'); +% network_spec.inlet_radius = num(:, rel_col); +% rel_col = strcmp(raw(1,:), 'Outlet Radius [m]'); +% network_spec.outlet_radius = num(:, rel_col); +% rel_col = strcmp(raw(1,:), 'Mynard Name'); +% network_spec.segment_name = raw(2:size(num,1)+1, rel_col); + +%% Data from Alastruey 2006 (model 2) +old_outlet_radius = nan(116,1); +% Left Hand Side +old_outlet_radius(22) = 0.00174; % matches article (radial) +old_outlet_radius(25) = 0.00203; % matches article (ulnar) +old_outlet_radius(107) = 0.00093; % matches DPA 3 (which is the correct segment when comparing the Nektar sketch to the diagram of the model in the paper) +old_outlet_radius(108) = 0.00161; % matches SPA 3 (which is the correct segment when comparing the Nektar sketch to the diagram of the model in the paper) +old_outlet_radius(109) = 0.00130; % matches DPA 1 (which is the correct segment when comparing the Nektar sketch to the diagram of the model in the paper) +old_outlet_radius(110) = 0.00169; % matches SPA 1 (which is the correct segment when comparing the Nektar sketch to the diagram of the model in the paper) +old_outlet_radius(111) = 0.00114; % matches SPA II (which is the correct segment when comparing the Nektar sketch to the diagram of the model in the paper) +old_outlet_radius(112) = 0.00132; % matches DIG 3 (which is the correct segment when comparing the Nektar sketch to the diagram of the model in the paper) +old_outlet_radius(113) = 0.00136; % matches DIG 2 (which is the correct segment when comparing the Nektar sketch to the diagram of the model in the paper) +old_outlet_radius(114) = 0.00093; % matches DIG 4 (which is the correct segment when comparing the Nektar sketch to the diagram of the model in the paper) +old_outlet_radius(115) = 0.00130; % matches DIG 1 (which is the correct segment when comparing the Nektar sketch to the diagram of the model in the paper) +old_outlet_radius(116) = 0.00075; % matches DPA 2 (which is the correct segment when comparing the Nektar sketch to the diagram of the model in the paper) +% Right Hand Side +old_outlet_radius(8) = 0.00174; +old_outlet_radius(11) = 0.00203; +old_outlet_radius(97) = 0.00093; +old_outlet_radius(98) = 0.00161; +old_outlet_radius(99) = 0.00130; +old_outlet_radius(100) = 0.00169; +old_outlet_radius(101) = 0.00114; +old_outlet_radius(102) = 0.00132; +old_outlet_radius(103) = 0.00136; +old_outlet_radius(104) = 0.00093; +old_outlet_radius(105) = 0.00130; +old_outlet_radius(106) = 0.00075; +old_areas = pi*(old_outlet_radius.^2); + +%% New data +% These are the data for the network before scaling by sqrt(1.5) +new_areas = old_areas; +new_areas(22) = pi*(0.00107^2); +new_areas(25) = pi*(0.00183^2); +new_areas(8) = pi*(0.00107^2); +new_areas(11) = pi*(0.00183^2); + +%% Find areas + +% modify areas for hand segments +new_areas = modify_bifurcations(new_areas, 22, 107, 108, up); % junction at end of left radial +new_areas = modify_bifurcations(new_areas, 25, 109, 110, up); % junction at end of left ulnar +new_areas = modify_bifurcations(new_areas, 8, 97, 98, up); % junction at end of right radial +new_areas = modify_bifurcations(new_areas, 11, 99, 100, up); % junction at end of right ulnar + +% modify areas which are common (anastomoses) +new_areas = modify_common_areas(old_areas, new_areas, 111, 108, 110, up); % central section of left superficial palmar arch +new_areas = modify_common_areas(old_areas, new_areas, 116, 109, 107, up); % left deep palmar arch +new_areas = modify_common_areas(old_areas, new_areas, 101, 98, 100, up); % central section of right superficial palmar arch +new_areas = modify_common_areas(old_areas, new_areas, 106, 99, 97, up); % right deep palmar arch + +% modify terminal branches according to proportion of area +new_areas = modify_terminal_branches(old_areas, new_areas, 112, 108); +new_areas = modify_terminal_branches(old_areas, new_areas, 113, 110); +new_areas = modify_terminal_branches(old_areas, new_areas, 102, 98); +new_areas = modify_terminal_branches(old_areas, new_areas, 103, 100); +new_areas = modify_terminal_branches(old_areas, new_areas, 115, 109); +new_areas = modify_terminal_branches(old_areas, new_areas, 114, 107); +new_areas = modify_terminal_branches(old_areas, new_areas, 105, 99); +new_areas = modify_terminal_branches(old_areas, new_areas, 104, 97); + +new_radii = sqrt(new_areas/pi); + +% Output new radii +fprintf('\n\n~~~~~~~~~~ New Radii ~~~~~~~~~') +for seg_no = [8,11,22,25,97:116] + fprintf(['\n new_radius(' num2str(seg_no) ') = ' num2str(new_radii(seg_no),3) ]); +end + +fprintf('\n\n~~~~~~~~~~ New Radii, after scaling by sqrt(1.5) ~~~~~~~~~') +for seg_no = [8,11,22,25,97:116] + fprintf(['\n new_radius(' num2str(seg_no) ') = ' num2str(new_radii(seg_no),3) ]); +end + +end + +function new_areas = modify_bifurcations(new_areas, inlet_seg, outlet_seg1, outlet_seg2, up) + +prop1 = new_areas(outlet_seg1)/(new_areas(outlet_seg2) + new_areas(outlet_seg1)); + +new_total_area = new_areas(inlet_seg)*up.matched_ratio; + +new_areas(outlet_seg1) = prop1*new_total_area; +new_areas(outlet_seg2) = (1-prop1)*new_total_area; + +end + +function new_areas = modify_common_areas(old_areas, new_areas, common_seg, inlet1, inlet2, up) + +old_prop = mean([old_areas(common_seg)/old_areas(inlet1), old_areas(common_seg)/old_areas(inlet2)]); + +new_areas(common_seg) = old_prop*mean([new_areas(inlet1), new_areas(inlet2)]); + +end + +function new_areas = modify_terminal_branches(old_areas, new_areas, terminal_seg, inlet_seg) + +old_prop = old_areas(terminal_seg)/old_areas(inlet_seg); +new_areas(terminal_seg) = old_prop*new_areas(inlet_seg); + +end","MATLAB"