pax_global_header00006660000000000000000000000064135322242640014515gustar00rootroot0000000000000052 comment=fee2fed967355ccc44f219fa0776d2d4fdabc87b Minimac4-1.0.2/000077500000000000000000000000001353222426400131565ustar00rootroot00000000000000Minimac4-1.0.2/.gitignore000066400000000000000000000001061353222426400151430ustar00rootroot00000000000000.idea/ *.so *.dylib *.dll *.lai *.la *.a *.lib *.slo *.lo *.o *.objMinimac4-1.0.2/CMakeLists.txt000066400000000000000000000031121353222426400157130ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.2) project(minimac4 VERSION 1.0.2) set(CMAKE_CXX_STANDARD 11) execute_process(COMMAND date OUTPUT_VARIABLE DATE OUTPUT_STRIP_TRAILING_WHITESPACE) execute_process(COMMAND whoami OUTPUT_VARIABLE USER OUTPUT_STRIP_TRAILING_WHITESPACE) add_definitions(-DVERSION="${PROJECT_VERSION}" -DUSER="${USER}" -DDATE="${DATE}") set(CMAKE_FIND_LIBRARY_SUFFIXES ".a;${CMAKE_FIND_LIBRARY_SUFFIXES}") # Prefer libz.a when both are available find_package(OpenMP) if (OPENMP_FOUND) set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}") set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}") endif() find_package(ZLIB REQUIRED) find_library(STATGEN_LIBRARY StatGen) add_executable(minimac4 src/Analysis.cpp src/Analysis.h src/AnalysisChunks.cpp src/DosageData.cpp src/DosageData.h src/HaplotypeSet.cpp src/HaplotypeSet.h src/Imputation.cpp src/Imputation.h src/ImputationStatistics.cpp src/ImputationStatistics.h src/Main.cpp src/MarkovModel.cpp src/MarkovModel.h src/MarkovParameters.cpp src/MarkovParameters.h src/MyVariables.h src/Unique.cpp src/Unique.h src/Estimation.cpp src/Estimation.h) target_link_libraries(minimac4 ${STATGEN_LIBRARY} ${ZLIB_LIBRARIES}) install(TARGETS minimac4 RUNTIME DESTINATION bin) set(CPACK_PACKAGE_VERSION_MAJOR ${PROJECT_VERSION_MAJOR}) set(CPACK_PACKAGE_VERSION_MINOR ${PROJECT_VERSION_MINOR}) set(CPACK_PACKAGE_VERSION_PATCH ${PROJECT_VERSION_PATCH}) include(CPack) Minimac4-1.0.2/LICENSE000066400000000000000000001045131353222426400141670ustar00rootroot00000000000000 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 . Minimac4-1.0.2/README.md000066400000000000000000000036571353222426400144500ustar00rootroot00000000000000# Minimac4 Minimac4 is a lower memory and more computationally efficient implementation of the genotype imputation algorithms in minimac/mininac2/minimac3. <<< SEE http://genome.sph.umich.edu/wiki/Minimac4 FOR DOCUMENTATION >>> Users should follow the following steps to compile Minimac4 ## Prerequisites Automatic installation of Minimac4 requires [cget](http://cget.readthedocs.io/en/latest/src/intro.html#installing-cget) and cmake v3.2. These prerequisites can be installed as follows: Ubuntu 16.04 ``` sudo apt-get install cmake python-pip python-dev pip install cget ``` Ubuntu 14.04 ``` sudo apt-get install software-properties-common sudo add-apt-repository ppa:george-edison55/cmake-3.x sudo apt-get update sudo apt-get install cmake python-pip python-dev pip install cget ``` MacOS ``` brew install cmake sudo easy-install pip pip install --user cget --ignore-installed six ``` ## Installation The easiest way to install Minimac4 and its dependencies is to use the install.sh file provided. ``` cd Minimac4 bash install.sh ``` Alternatively, you can use cget as follows: ```bash cget install --prefix statgen/Minimac4 ``` Alternatively, you can setup a dev environment cmake directly. ```bash cd Minimac4 cget install -f ./requirements.txt # Install dependencies locally. mkdir build && cd build # Create out of source build directory. cmake -DCMAKE_TOOLCHAIN_FILE=../cget/cget/cget.cmake .. # Configure project with dependency paths. make # Build. ``` ## Usage A typical Minimac4 command line for imputation is as follows ```bash minimac4 --refHaps refPanel.m3vcf \ --haps targetStudy.vcf \ --prefix testRun ``` Here refPanel.m3vcf is the reference panel used in M3VCF format (e.g. 1000 Genomes), targetStudy.vcf is the phased GWAS data in VCF format, and testRun is the prefix for the output files. Minimac4-1.0.2/dep/000077500000000000000000000000001353222426400137265ustar00rootroot00000000000000Minimac4-1.0.2/dep/libstatgen.cmake000066400000000000000000000014061353222426400170650ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.2) project(libStatGen VERSION 1.0.0) #execute_process(COMMAND ./configure --prefix=${CMAKE_INSTALL_PREFIX} WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}) add_custom_target(libStatGen ALL COMMAND ${CMAKE_COMMAND} -E env CPATH=${CGET_PREFIX}/include make WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR} COMMENT "Builing libStatGen ...") file(GLOB_RECURSE LSG_HEADER_LIST "bam/*.h" "fastq/*.h" "general/*.h" "glf/*.h" "samtools/*.h" "vcf/*.h") install(FILES ${LSG_HEADER_LIST} DESTINATION include) if (BUILD_SHARED_LIBS) install(FILES ${CMAKE_SHARED_LIBRARY_PREFIX}StatGen${CMAKE_SHARED_LIBRARY_SUFFIX} DESTINATION lib) else() install(FILES ${CMAKE_STATIC_LIBRARY_PREFIX}StatGen${CMAKE_STATIC_LIBRARY_SUFFIX} DESTINATION lib) endif() Minimac4-1.0.2/install.sh000077500000000000000000000005511353222426400151640ustar00rootroot00000000000000#!/bin/sh rm -rf cget/ release-build/ install.log echo -e "Installing Dependencies - Libstatgen ..." cget install -f requirements.txt &> install.log mkdir release-build cd release-build/ echo -e "Generating MakeFiles ..." cmake -DCMAKE_TOOLCHAIN_FILE=../cget/cget/cget.cmake -DCMAKE_BUILD_TYPE=Release .. make echo "Binary created at /release-build/minimac4" Minimac4-1.0.2/package-linux.sh000077500000000000000000000014471353222426400162530ustar00rootroot00000000000000#!/bin/bash # Usage: docker build -t packaging-ubuntu16 -f packaging-dockerfile-ubuntu16 . # docker run -v `pwd`:/app -w /app packaging-ubuntu16 ./package-linux.sh set -euo pipefail src_dir=`pwd` build_dir=${src_dir}/pkg-build rm -rf ${build_dir} mkdir ${build_dir} cd ${build_dir} export CFLAGS="-fPIC" export CXXFLAGS="-fPIC" cget install -f ${src_dir}/requirements.txt unset CFLAGS unset CXXFLAGS cmake \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_TOOLCHAIN_FILE=cget/cget/cget.cmake \ -DCMAKE_EXE_LINKER_FLAGS="-static -static-libgcc -static-libstdc++" \ -DCPACK_GENERATOR="STGZ;DEB;RPM" \ -DCPACK_PACKAGE_CONTACT="csg-devel@umich.edu" \ ${src_dir} make #make manuals make package mkdir -p ${src_dir}/pkg/ cp minimac4-*.{sh,deb,rpm} ${src_dir}/pkg/ cd ${src_dir} rm -r ${build_dir} Minimac4-1.0.2/packaging-dockerfile-ubuntu16000066400000000000000000000003221353222426400206160ustar00rootroot00000000000000FROM ubuntu:16.04 RUN apt-get update && apt-get install -y \ build-essential \ curl \ cmake \ git \ help2man \ lsb-release \ python \ python-pip \ rpm RUN pip install cget Minimac4-1.0.2/requirements.txt000066400000000000000000000001301353222426400164340ustar00rootroot00000000000000zlib,http://zlib.net/zlib-1.2.11.tar.gz statgen/libStatGen --cmake dep/libstatgen.cmake Minimac4-1.0.2/src/000077500000000000000000000000001353222426400137455ustar00rootroot00000000000000Minimac4-1.0.2/src/Analysis.cpp000066400000000000000000001771441353222426400162520ustar00rootroot00000000000000#include "Analysis.h" #include "Estimation.h" #include #include "assert.h" # define RECOM_MIN 1e-05 void MyTokenize(vector &result, const char *input, const char *delimiter, int Number) { size_t wordCount = 1; result[0].clear(); std::string *word = &result[0]; while (*input) { if (*input==*delimiter) { // we got a delimeter, and since an empty word following // a delimeter still counts as a word, we allocate it here wordCount++; if((int)wordCount>Number) return; result[wordCount-1].clear(); word = &result[wordCount-1]; } else { word->push_back(*input); } input++; } } bool Analysis::CreateRecombinationMap() { int FirstIndex=0; while(referencePanel.VariantList[FirstIndex].bpmyModelVariables.referenceEstimates && !CreateRecombinationMap()) { cout << "\n Program Exiting ... \n\n"; return "Genetic.Map.Load.Error"; } if (!targetPanel.ScaffoldGWAStoReference(referencePanel,*MyAllVariables)) { cout << "\n Program Exiting ... \n\n"; return "Reference.Panel.Load.Error"; } cout<<"\n ------------------------------------------------------------------------------"<myOutFormat.memUsage) { cout<<" ------------------------------------------------------------------------------"<myModelVariables.cpus); if(MyAllVariables->myOutFormat.vcfBuffer >= targetPanel.numSamples) MyAllVariables->myOutFormat.vcfBuffer=targetPanel.numSamples; thisDataFast.InitializeOutputFiles(targetPanel, MyAllVariables->myOutFormat.vcfBuffer, MaxRefMarkerSize, MaxGwasMarkerSize); if(MyAllVariables->myOutFormat.memUsage) { cout<<" Estimating Memory based on a single chunk ..."<< endl; readm3vcfFileChunk(0, CurrentRefPanel); readVcfFileChunk(0, CurrentTarPanelChipOnly); GetCurrentPanelReady(0, CurrentRefPanel, CurrentRefPanelChipOnly, CurrentTarPanelChipOnly, thisDataFast); cout<myModelVariables.minimac3) thisDataFast.Minimac3ImputeThisChunk(i, CurrentRefPanel, CurrentTarPanelChipOnly, CurrentRefPanelChipOnly); else thisDataFast.ImputeThisChunk(i, CurrentRefPanel, CurrentTarPanelChipOnly, CurrentRefPanelChipOnly); //abort(); TimeToImpute+=(thisDataFast.TimeToImpute); TimeToWrite+=(thisDataFast.TimeToWrite); TimeToCompress+=(thisDataFast.TimeToCompress); AppendtoMainVcfFaster(i,thisDataFast.TotalNovcfParts); if(MyAllVariables->myOutFormat.meta) AppendtoMainLooVcfFaster(i,thisDataFast.TotalNovcfParts); PrintInfoFile(i); time_load = time(0) - time_prev; cout << "\n Time taken for this chunk = " << time_load << " seconds."<myHapDataVariables.end==0 && MyAllVariables->myOutFormat.TypedOnly) // assert(FileReadIndex==targetPanel.importIndexListSize); // asserassertt(OverCount==targetPanel.numOverlapMarkers); // assert(TypOnlyCount==targetPanel.numTypedOnlyMarkers); // assert(RefCOUNT==referencePanel.NoBlocks); CloseStreamOutputFiles(); return "Success"; } void Analysis::PrintInfoFile(int ChunkNo) { InfoPrintStringLength=0; int RefStartPos = MyRefVariantNumber[ChunkNo][0]; info = ifopen(MyAllVariables->myOutFormat.OutPrefix + ".info", "a"); int i=0; for (int index = 0; index < CurrentRefPanel.RefTypedTotalCount; index++) { if(CurrentRefPanel.RefTypedIndex[index]==-1) { variant &thisVariant = referencePanel.VariantList[i+RefStartPos]; if(i>=CurrentRefPanel.PrintStartIndex && i <= CurrentRefPanel.PrintEndIndex) { double TarFreq = stats.AlleleFrequency(i); InfoPrintStringLength+=sprintf(InfoPrintStringPointer+InfoPrintStringLength , "%s\t%s\t%s\t%.5f\t%.5f\t%.5f\t%.5f\t", MyAllVariables->myOutFormat.RsId ? thisVariant.rsid.c_str(): thisVariant.name.c_str(), thisVariant.refAlleleString.c_str(), thisVariant.altAlleleString.c_str(), TarFreq, TarFreq > 0.5 ? 1.0 - TarFreq : TarFreq, stats.AverageCallScore(i), stats.Rsq(i)); if (!CurrentRefPanel.Targetmissing[i]) { InfoPrintStringLength+=sprintf(InfoPrintStringPointer+InfoPrintStringLength , "Genotyped\t%.3f\t%.3f\t%.5f\t%.5f\t%.5f\n", stats.LooRsq(i), stats.EmpiricalR(i), stats.EmpiricalRsq(i), stats.LooMajorDose(i), stats.LooMinorDose(i)); } else InfoPrintStringLength+=sprintf(InfoPrintStringPointer+InfoPrintStringLength , "Imputed\t-\t-\t-\t-\t-\n"); } i++; } else { // if(ChunkNo==2 && index==26751) // abort(); int MappingIndex = CurrentRefPanel.RefTypedIndex[index]; if(MappingIndex>=CurrentTarPanelChipOnly.PrintTypedOnlyStartIndex && MappingIndex<=CurrentTarPanelChipOnly.PrintTypedOnlyEndIndex) { variant ThisTypedVariant = CurrentTarPanelChipOnly.TypedOnlyVariantList[MappingIndex]; double TarFreq = CurrentTarPanelChipOnly.GWASOnlyAlleleFreq[MappingIndex]; InfoPrintStringLength+=sprintf(InfoPrintStringPointer+InfoPrintStringLength , "%s\t%s\t%s\t%.5f\t%.5f\t-\t-\tTyped_Only\t-\t-\t-\t-\t-\n", MyAllVariables->myOutFormat.RsId ? ThisTypedVariant.rsid.c_str(): ThisTypedVariant.name.c_str(), ThisTypedVariant.refAlleleString.c_str(), ThisTypedVariant.altAlleleString.c_str(), TarFreq, TarFreq > 0.5 ? 1.0 - TarFreq : TarFreq); } } if(InfoPrintStringLength > 0.9 * (float)(MyAllVariables->myOutFormat.PrintBuffer)) { ifprintf(info,"%s",InfoPrintStringPointer); InfoPrintStringLength=0; } } if(InfoPrintStringLength >0) { ifprintf(info,"%s",InfoPrintStringPointer); InfoPrintStringLength=0; } ifclose(info); } void Analysis::AppendtoMainLooVcfFaster(int ChunkNo, int MaxIndex) { VcfPrintStringLength=0; int time_prev = time(0); int RefStartPos = MyRefVariantNumber[ChunkNo][0]; vector vcfLoodosepartialList(MaxIndex); vcfLoodosepartial = ifopen(MyAllVariables->myOutFormat.OutPrefix + ".empiricalDose.vcf" + (MyAllVariables->myOutFormat.gzip ? ".gz" : ""), "a", MyAllVariables->myOutFormat.gzip ?InputFile::BGZF:InputFile::UNCOMPRESSED); for(int i=1;i<=MaxIndex;i++) { string tempFileIndex(MyAllVariables->myOutFormat.OutPrefix); stringstream strs,strs1; strs<<(i); strs1<<(ChunkNo+1); tempFileIndex+=(".chunk."+(string)(strs1.str())+".empiricalDose.part." + (string)(strs.str())+".vcf.gz"); vcfLoodosepartialList[i-1] = ifopen(tempFileIndex.c_str(), "r"); } string line; int i=0; for (int index = 0; index < CurrentRefPanel.RefTypedTotalCount; index++) { if(CurrentRefPanel.RefTypedIndex[index]==-1) { if(i>=CurrentRefPanel.PrintStartIndex && i <= CurrentRefPanel.PrintEndIndex) { if(!CurrentRefPanel.Targetmissing[i]) { variant &tempVariant = referencePanel.VariantList[i+RefStartPos]; VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"%s\t%d\t%s\t%s\t%s\t.\tPASS", tempVariant.chr.c_str(), tempVariant.bp, MyAllVariables->myOutFormat.RsId?tempVariant.rsid.c_str():tempVariant.name.c_str(), tempVariant.refAlleleString.c_str(), tempVariant.altAlleleString.c_str()); VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"\tTYPED\tGT:LDS"); for(int j=1;j<=MaxIndex;j++) { line.clear(); vcfLoodosepartialList[j-1]->readLine(line); VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"%s",line.c_str()); } VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"\n"); } } i++; } if(VcfPrintStringLength > 0.9 * (float)(MyAllVariables->myOutFormat.PrintBuffer)) { ifprintf(vcfLoodosepartial,"%s",VcfPrintStringPointer); VcfPrintStringLength=0; } } if(VcfPrintStringLength > 0) { ifprintf(vcfLoodosepartial,"%s",VcfPrintStringPointer); VcfPrintStringLength=0; } for(int i=1;i<=MaxIndex;i++) { ifclose(vcfLoodosepartialList[i-1]); string tempFileIndex(MyAllVariables->myOutFormat.OutPrefix); stringstream strs,strs1; strs<<(i); strs1<<(ChunkNo+1); tempFileIndex+=(".chunk."+(string)(strs1.str())+".empiricalDose.part." + (string)(strs.str())+".vcf.gz"); remove(tempFileIndex.c_str()); } TimeToWrite+=( time(0) - time_prev); ifclose(vcfLoodosepartial); } void Analysis::AppendtoMainVcfFaster(int ChunkNo, int MaxIndex) { VcfPrintStringLength=0; int time_prev = time(0); int RefStartPos = MyRefVariantNumber[ChunkNo][0]; printf("\n Appending chunk to final output VCF File : %s ",(MyAllVariables->myOutFormat.OutPrefix + ".dose.vcf" + (MyAllVariables->myOutFormat.gzip ? ".gz" : "")).c_str() ); cout< vcfdosepartialList(MaxIndex); vcfdosepartial = ifopen(MyAllVariables->myOutFormat.OutPrefix + ".dose.vcf" + (MyAllVariables->myOutFormat.gzip ? ".gz" : ""), "a", MyAllVariables->myOutFormat.gzip ?InputFile::BGZF:InputFile::UNCOMPRESSED); for(int i=1;i<=MaxIndex;i++) { string tempFileIndex(MyAllVariables->myOutFormat.OutPrefix); stringstream strs,strs1; strs<<(i); strs1<<(ChunkNo+1); tempFileIndex+=(".chunk."+(string)(strs1.str())+".dose.part." + (string)(strs.str())+".vcf.gz"); vcfdosepartialList[i-1] = ifopen(tempFileIndex.c_str(), "r"); } string line; int i=0; for (int index = 0; index < CurrentRefPanel.RefTypedTotalCount; index++) { if(CurrentRefPanel.RefTypedIndex[index]==-1) { if(i>=CurrentRefPanel.PrintStartIndex && i <= CurrentRefPanel.PrintEndIndex) { variant &tempVariant = referencePanel.VariantList[i+RefStartPos]; VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"%s\t%d\t%s\t%s\t%s\t.\tPASS", tempVariant.chr.c_str(), tempVariant.bp, MyAllVariables->myOutFormat.RsId?tempVariant.rsid.c_str():tempVariant.name.c_str(), tempVariant.refAlleleString.c_str(), tempVariant.altAlleleString.c_str()); double freq = stats.AlleleFrequency(i); VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"\tAF=%.5f;MAF=%.5f;R2=%.5f", freq, freq > 0.5 ? 1.0 - freq : freq, stats.Rsq(i)); if(!CurrentRefPanel.Targetmissing[i]) VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,";ER2=%.5f;TYPED",stats.EmpiricalRsq(i)); else VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,";IMPUTED"); VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"\t%s",MyAllVariables->myOutFormat.formatStringForVCF.c_str()); for(int j=1;j<=MaxIndex;j++) { line.clear(); vcfdosepartialList[j-1]->readLine(line); VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"%s",line.c_str()); } VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"\n"); } i++; } else { int MappingIndex = CurrentRefPanel.RefTypedIndex[index]; if(MappingIndex>=CurrentTarPanelChipOnly.PrintTypedOnlyStartIndex && MappingIndex<=CurrentTarPanelChipOnly.PrintTypedOnlyEndIndex) { variant &ThisTypedVariant = (CurrentTarPanelChipOnly.TypedOnlyVariantList[CurrentRefPanel.RefTypedIndex[index]]); VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"%s\t%d\t%s\t%s\t%s\t.\tPASS", ThisTypedVariant.chr.c_str(), ThisTypedVariant.bp, MyAllVariables->myOutFormat.RsId? ThisTypedVariant.rsid.c_str():ThisTypedVariant.name.c_str(), ThisTypedVariant.refAlleleString.c_str(), ThisTypedVariant.altAlleleString.c_str()); double &freq = (CurrentTarPanelChipOnly.GWASOnlyAlleleFreq[CurrentRefPanel.RefTypedIndex[index]]); VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"\tAF=%.5f;MAF=%.5f;TYPED_ONLY", freq, freq > 0.5 ? 1.0 - freq : freq); VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"\t%s",MyAllVariables->myOutFormat.formatStringForVCF.c_str()); for(int j=1;j<=MaxIndex;j++) { line.clear(); vcfdosepartialList[j-1]->readLine(line); VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"%s",line.c_str()); } VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"\n"); } } if(VcfPrintStringLength > 0.9 * (float)(MyAllVariables->myOutFormat.PrintBuffer)) { ifprintf(vcfdosepartial,"%s",VcfPrintStringPointer); VcfPrintStringLength=0; } } if(VcfPrintStringLength > 0) { ifprintf(vcfdosepartial,"%s",VcfPrintStringPointer); VcfPrintStringLength=0; } for(int i=1;i<=MaxIndex;i++) { ifclose(vcfdosepartialList[i-1]); string tempFileIndex(MyAllVariables->myOutFormat.OutPrefix); stringstream strs,strs1; strs<<(i); strs1<<(ChunkNo+1); tempFileIndex+=(".chunk."+(string)(strs1.str())+".dose.part." + (string)(strs.str())+".vcf.gz"); remove(tempFileIndex.c_str()); } TimeToWrite+=( time(0) - time_prev); cout << " Appending successful (" << time(0) - time_prev << " seconds) !!!"< &ThisInfoVector = ThisRefPanel.ReducedStructureInfo; string line; int ThisInfoVectorIndex=0; int ThisChunkFilledTillRef = 0, ThisChunkStartFromRef = 0; int StartBlock=MyChunksInfoNumber[ChunkNo][0]; int EndBlock=MyChunksInfoNumber[ChunkNo][1]; int StartNextBlock=MyChunksInfoNumber[ChunkNo+1][0]; int blockIndex=StartBlock; int FilltheTop=0; while(FilltheTop < PrevChunkFilledTillRef) { ThisInfoVector[blockIndex-StartBlock] = ThisInfoVector[PrevChunkStartFromRef + FilltheTop] ; blockIndex++; FilltheTop++; } ThisChunkStartFromRef=FilltheTop; for(;blockIndex<=EndBlock;blockIndex++) { RefCOUNT++; line.clear(); RefFileStream->readLine(line); // assert(ThisInfoVectorIndex + PrevChunkFilledTillRef < MaxInfoVectorSize); ReducedHaplotypeInfo &tempBlock=ThisInfoVector[ThisInfoVectorIndex + PrevChunkFilledTillRef]; ThisInfoVectorIndex++; referencePanel.ReadBlockHeader(line, tempBlock); referencePanel.ReadThisBlock(RefFileStream, blockIndex, tempBlock); if(blockIndex>=StartNextBlock) { // assert(ThisChunkFilledTillRef < MaxInfoVectorSize); ThisChunkFilledTillRef++; } else { ThisChunkStartFromRef++; } } PrevChunkFilledTillRef=ThisChunkFilledTillRef; PrevChunkStartFromRef=ThisChunkStartFromRef; TimeToRead+=( time(0) - time_prev); } void Analysis::readVcfFileChunk(int ChunkNo, HaplotypeSet &ThisTargetPanel) { int time_prev = time(0); cout << " Reading chunk from target/GWAS panel ... "<=StartNextPos) { // assert( (ThisChunkStartTillTar) < MaxGwasMarkerSize); ThisChunkStartTillTar++; } else { ThisChunkStartFromTar++; } // assert(overlapImportIndexmyOutFormat.TypedOnly) { // assert( (GWASnumtoBeWrittenRecords + PrevChunkFilledTillTarOnly) < MaxTypedOnlyMarkerSize); variant tempVar=targetPanel.TypedOnlyVariantList[MainTypedOnlyImportIndex]; ThisTargetPanel.TypedOnlyVariantList[GWASnumtoBeWrittenRecords + PrevChunkFilledTillTarOnly]=tempVar; int haplotype_index = 0; for (int i = 0; i<(targetPanel.numSamples); i++) { //haplotype_index=(2*i); if(targetPanel.SampleNoHaplotypes[i]!=record.getNumGTs(i)) { cout << "\n ERROR !!! GWAS Sample "<< targetPanel.individualName[i]<<" changes its ploidy at variant "; cout << tempVar.name <=TypedOnlyNextStartPos) { // assert( (ThisChunkStartTillTarOnly) < MaxTypedOnlyMarkerSize); ThisChunkStartTillTarOnly++; } else { ThisChunkStartFromTarOnly++; } // assert(MainTypedOnlyImportIndexmyOutFormat.gzip; if(MyAllVariables->myOutFormat.vcfOutput) { VcfPrintStringPointer = (char*)malloc(sizeof(char) * (MyAllVariables->myOutFormat.PrintBuffer)); vcfdosepartial = ifopen(MyAllVariables->myOutFormat.OutPrefix + ".dose.vcf" + (gzip ? ".gz" : ""), "wb", gzip ?InputFile::BGZF:InputFile::UNCOMPRESSED); if(vcfdosepartial==NULL) { cout <<"\n\n ERROR !!! \n Could NOT create the following file : "<< MyAllVariables->myOutFormat.OutPrefix + ".dose.vcf" + (gzip ? ".gz" : "") <tm_year + 1900),(now->tm_mon + 1) ,now->tm_mday); ifprintf(vcfdosepartial,"##source=Minimac4.v%s\n",VERSION); ifprintf(vcfdosepartial,"##contig=\n",referencePanel.finChromosome.c_str()); ifprintf(vcfdosepartial,"##INFO=\n"); ifprintf(vcfdosepartial,"##INFO=\n"); ifprintf(vcfdosepartial,"##INFO=\n"); ifprintf(vcfdosepartial,"##INFO=\n"); ifprintf(vcfdosepartial,"##INFO=\n"); ifprintf(vcfdosepartial,"##INFO=\n"); ifprintf(vcfdosepartial,"##INFO=\n"); if(MyAllVariables->myOutFormat.GT) ifprintf(vcfdosepartial,"##FORMAT=\n"); if(MyAllVariables->myOutFormat.DS) ifprintf(vcfdosepartial,"##FORMAT=\n"); if(MyAllVariables->myOutFormat.HDS) ifprintf(vcfdosepartial,"##FORMAT=\n"); if(MyAllVariables->myOutFormat.GP) ifprintf(vcfdosepartial,"##FORMAT=\n"); if(MyAllVariables->myOutFormat.SD) ifprintf(vcfdosepartial,"##FORMAT=\n"); ifprintf(vcfdosepartial,"##minimac4_Command=%s\n",MyAllVariables->myOutFormat.CommandLine.c_str()); ifprintf(vcfdosepartial,"#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT"); for(int Id=0;IdmyOutFormat.meta) { vcfLoodosepartial = ifopen(MyAllVariables->myOutFormat.OutPrefix + ".empiricalDose.vcf" + (gzip ? ".gz" : ""), "wb", gzip ?InputFile::BGZF:InputFile::UNCOMPRESSED); if(vcfLoodosepartial==NULL) { cout <<"\n\n ERROR !!! \n Could NOT create the following file : "<< MyAllVariables->myOutFormat.OutPrefix + ".empiricalDose.vcf" + (gzip ? ".gz" : "") <tm_year + 1900),(now->tm_mon + 1) ,now->tm_mday); ifprintf(vcfLoodosepartial,"##source=Minimac4.v%s\n",VERSION); ifprintf(vcfLoodosepartial,"##contig=\n",referencePanel.finChromosome.c_str()); ifprintf(vcfLoodosepartial,"##INFO=\n"); ifprintf(vcfLoodosepartial,"##FORMAT=\n"); ifprintf(vcfLoodosepartial,"##FORMAT=\n"); ifprintf(vcfLoodosepartial,"##minimac4_Command=%s\n",MyAllVariables->myOutFormat.CommandLine.c_str()); ifprintf(vcfLoodosepartial,"#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT"); for(int Id=0;IdmyOutFormat.doseOutput) { dosages = ifopen(MyAllVariables->myOutFormat.OutPrefix + ".dose" + (gzip ? ".gz" : ""), "wb",(gzip ? InputFile::BGZF:InputFile::UNCOMPRESSED) ); if(dosages==NULL) { cout <<"\n\n ERROR !!! \n Could NOT create the following file : "<< MyAllVariables->myOutFormat.OutPrefix + ".dose" + (gzip ? ".gz" : "") <myOutFormat.PrintBuffer)); info = ifopen(MyAllVariables->myOutFormat.OutPrefix + ".info", "wb"); if(info==NULL) { cout <<"\n\n ERROR !!! \n Could NOT create the following file : "<< MyAllVariables->myOutFormat.OutPrefix + ".info" <myOutFormat.hapOutput && !MyAllVariables->myOutFormat.unphasedOutput) { ifclose(hapdose); } if(MyAllVariables->myOutFormat.vcfOutput) { ifclose(vcfdosepartial); } if(MyAllVariables->myOutFormat.meta) { ifclose(vcfLoodosepartial); } if(MyAllVariables->myOutFormat.doseOutput) { ifclose(dosages); } ifclose(RefFileStream); TarFileStream.close(); cout<<" ------------------------------------------------------------------------------"<1073741824) { Fact=1073741824; Tag="Gb"; } else if(Total>1048576) { Fact=1048576; Tag="Mb"; } else if(Total>1024) { Fact=1024; Tag="Kbytes"; } else { Fact=1; Tag="Bytes"; } printf("\n Memory occupied by Full Reference Panel ~ %.3f %s", (double) RefMem/(Fact),Tag.c_str()); printf("\n Memory occupied by Compressed Reference Panel ~ %.3f %s", (double) ComRefMem/(Fact),Tag.c_str()); printf("\n Memory occupied by Target/GWAS Panel ~ %.3f %s", (double) TarMem/(Fact),Tag.c_str()); printf("\n Memory occupied by Likelihood Matrices ~ %.3f %s", (double) ProbMem/(Fact),Tag.c_str()); printf("\n Memory occupied by Dosage Data ~ %.3f %s", (double) DosageMem/(Fact),Tag.c_str()); printf("\n TOTAL Memory by the process ~ %.3f %s", (double) (Total)/(Fact),Tag.c_str()); cout<myOutFormat.gzip; cout<myOutFormat.OutPrefix + ".info" <myOutFormat.hapOutput && !MyAllVariables->myOutFormat.unphasedOutput) { ifclose(hapdose); cout<<" Haplotype Dosage information written to : "<myOutFormat.OutPrefix + ".hapDose" + (gzip ? ".gz" : "")<myOutFormat.vcfOutput) { ifclose(vcfdosepartial); free(VcfPrintStringPointer); cout<<" Imputed VCF information written to : "<< MyAllVariables->myOutFormat.OutPrefix + ".dose.vcf" + (gzip ? ".gz" : "")<myOutFormat.meta) { ifclose(vcfLoodosepartial); cout<<" Empirical Dosage VCF written to : "<< MyAllVariables->myOutFormat.OutPrefix + ".empiricalDose.vcf" + (gzip ? ".gz" : "")<myOutFormat.doseOutput) { ifclose(dosages); cout<<" Dosage information written to : "<< MyAllVariables->myOutFormat.OutPrefix + ".dose" + (gzip ? ".gz" : "")<0) { int TOnlyStartPos = MyTypdedOnlyVariantNumber[ChunkNo][0]; int TOnlyEndPos = MyTypdedOnlyVariantNumber[ChunkNo][1]; int i=TOnlyStartPos; if(ChunkNo==0) { if(MyAllVariables->myHapDataVariables.CHR!="") { while(targetPanel.TypedOnlyVariantList[i].bp < MyAllVariables->myHapDataVariables.start) { i++; } } } else { while(targetPanel.TypedOnlyVariantList[i].bp < MyChunks[ChunkNo][1]) { i++; } } ThisTarPanel.PrintTypedOnlyStartIndex=i-TOnlyStartPos; if(ChunkNo==(noChunks-1)) { if(MyAllVariables->myHapDataVariables.CHR!="") { for(; i <= TOnlyEndPos; i++) if(targetPanel.TypedOnlyVariantList[i].bp > MyAllVariables->myHapDataVariables.end) break; } else i=TOnlyEndPos+1; } else { for(; i <= TOnlyEndPos; i++) if(targetPanel.TypedOnlyVariantList[i].bp > MyChunks[ChunkNo][2]) break; } ThisTarPanel.PrintTypedOnlyEndIndex=i-TOnlyStartPos-1; // assert(ThisTarPanel.PrintTypedOnlyStartIndex <= ThisTarPanel.numTypedOnlyMarkers); // assert(ThisTarPanel.PrintTypedOnlyEndIndex <= ThisTarPanel.numTypedOnlyMarkers); } int RefStartPos = MyRefVariantNumber[ChunkNo][0]; int RefEndPos = MyRefVariantNumber[ChunkNo][1]; int i=RefStartPos; if(ChunkNo==0) { if(MyAllVariables->myHapDataVariables.CHR!="") { while(referencePanel.VariantList[i].bp < MyAllVariables->myHapDataVariables.start) { i++; } } } else { while(referencePanel.VariantList[i].bp < MyChunks[ChunkNo][1]) { i++; } } ThisRefPanel.PrintStartIndex=i-RefStartPos; if(ChunkNo==(noChunks-1)) { if(MyAllVariables->myHapDataVariables.CHR!="") { for(; i <= RefEndPos; i++) if(referencePanel.VariantList[i].bp > MyAllVariables->myHapDataVariables.end) break; } else i=RefEndPos+1; } else { for(; i <= RefEndPos; i++) if(referencePanel.VariantList[i].bp > MyChunks[ChunkNo][2]) break; } ThisRefPanel.PrintEndIndex=i-RefStartPos-1; // assert(ThisRefPanel.PrintStartIndex < ThisRefPanel.numMarkers); // assert(ThisRefPanel.PrintEndIndex < ThisRefPanel.numMarkers); } void Analysis::GetCurrentPanelReady(int ChunkNo, HaplotypeSet &ThisRefPanel, HaplotypeSet &ThisRefChipOnlyPanel, HaplotypeSet &ThisTarPanel, Imputation &thisDataFast) { int RefStartPos = MyRefVariantNumber[ChunkNo][0]; int RefEndPos = MyRefVariantNumber[ChunkNo][1]; int TarStartPos = MyTargetVariantNumber[ChunkNo][0]; // int TarEndPos = MyTargetVariantNumber[ChunkNo][1]; int RefStartInfo = MyChunksInfoNumber[ChunkNo][0]; int RefEndInfo = MyChunksInfoNumber[ChunkNo][1]; int NoRefMarkers = RefEndPos - RefStartPos + 1; int NoGwasMarkers =MyTargetVariantNumber[ChunkNo][2]; int NoTOnlyMarkers =MyTypdedOnlyVariantNumber[ChunkNo][2]; // initialize typical variants ThisRefPanel.numMarkers=NoRefMarkers; ThisRefChipOnlyPanel.numMarkers=NoGwasMarkers; ThisRefPanel.NoBlocks = MyChunksInfoNumber[ChunkNo][2]; ThisTarPanel.numMarkers=NoGwasMarkers; ThisTarPanel.numOverlapMarkers=NoGwasMarkers; ThisTarPanel.numTypedOnlyMarkers=NoTOnlyMarkers; int i; // create new start and end indices for RefInfo { ThisRefPanel.ReducedStructureInfo[0].startIndex = 0; for(i=RefStartInfo; i &Mapper = ThisRefPanel.MarkerToReducedInfoMapper; int j; for(i=0;i0 // && targetPanel.TargetMissingTypedOnly[ThisIndex]!=-1 && targetPanel.TargetMissingTypedOnly[ThisIndex] < (RefStartPos)) { ThisIndex++; } int counter=RefStartPos; while(counter<=RefEndPos && ThisIndex<(int) targetPanel.TargetMissingTypedOnly.size()) { if(counter<=targetPanel.TargetMissingTypedOnly[ThisIndex]) { ThisRefPanel.RefTypedIndex.push_back(-1); counter++; } else { // assert(ThisMappedIndextargetPanel.TargetMissingTypedOnly[ThisIndex]) { // assert(ThisMappedIndex= 0); // assert( (targetPanel.MapTarToRef[i+TarStartPos] - RefStartPos ) < NoRefMarkers); ThisRefPanel.MapTarToRef[i] = targetPanel.MapTarToRef[i+TarStartPos] - RefStartPos; ThisRefPanel.Targetmissing[ThisRefPanel.MapTarToRef[i]]=false; // ThisTarPanel.VariantList[i]=targetPanel.OverlapOnlyVariantList[i+TarStartPos]; if(i>0) { ThisTarPanel.FlankRegionEnd[i-1]= (ThisRefPanel.MapTarToRef[i-1] + ThisRefPanel.MapTarToRef[i])/2; ThisTarPanel.FlankRegionStart[i]=ThisTarPanel.FlankRegionEnd[i-1]+1; } } ThisTarPanel.FlankRegionEnd[i-1]=NoRefMarkers-1; } // Create PrintStart and End Index and scaffold for target and Recom and Error and MAPTOREF for REF { fill(ThisRefPanel.MapRefToTar.begin(), ThisRefPanel.MapRefToTar.end(), -1); for(i=RefStartPos; i<=RefEndPos; i++) { if(MyAllVariables->myOutFormat.verbose) ThisRefPanel.VariantList[i-RefStartPos]=referencePanel.VariantList[i]; // ThisTarPanel.missing[i-RefStartPos]=targetPanel.missing[i]; if(i= 0); // assert( (targetPanel.MapRefToTar[i] - TarStartPos) < NoGwasMarkers); ThisRefPanel.MapRefToTar[i-RefStartPos] = targetPanel.MapRefToTar[i] - TarStartPos; } } } ThisRefPanel.CalculateAlleleFreq(); ThisTarPanel.CalculateGWASOnlyAlleleFreq(); if(!MyAllVariables->myModelVariables.minimac3) { int time_prev = time(0); cout << "\n Compressing reference panel at GWAS sites ... "<myModelVariables.intermediate=="") ThisRefChipOnlyPanel.UncompressTypedSitesNew(ThisRefPanel,ThisTarPanel,ChunkNo); else { stringstream strs; strs<<(ChunkNo+1); string ss = (string)MyAllVariables->myModelVariables.intermediate.c_str()+".chunk."+(string)strs.str()+".GWAS.m3vcf.gz"; ThisRefChipOnlyPanel.readm3vcfFile(ss.c_str(), "", 0, 0, 0); ThisRefChipOnlyPanel.CreateScaffoldedParameters(ThisRefPanel); } thisDataFast.TimeToCompress = time(0) - time_prev; time_prev=time(0); cout << " Re-compression successful (" << thisDataFast.TimeToCompress<< " seconds) !!!"<myModelVariables.cpus;i++) { thisDataFast.MainMarkovModel[i].AssignPanels(ThisRefPanel,ThisRefChipOnlyPanel,ThisTarPanel,ThisTarPanel,MyAllVariables); thisDataFast.MainMarkovModel[i].initializeMatrices(); } } else { int time_prev = time(0); for(int i=0;imyModelVariables.cpus;i++) { thisDataFast.MainMarkovModel[i].AssignPanels(ThisRefPanel,ThisTarPanel,MyAllVariables); thisDataFast.MainMarkovModel[i].initializeMatricesMinimac3(); } } } void Analysis::InitializeRefFileStream(String &Reffilename) { RefFileStream = ifopen(Reffilename, "r"); string line; RefFileStream->readLine(line); bool Header=true; while(Header) { line.clear(); RefFileStream->readLine(line); if(line.substr(0,6).compare("#CHROM")==0) break; } for(int tempIndex=0;tempIndexdiscardLine(); PrevChunkFilledTillRef=0; PrevChunkStartFromRef=0; PrevChunkFilledTillTar=0; PrevChunkStartFromTar=0; PrevChunkFilledTillTarOnly=0; PrevChunkStartFromTarOnly=0; InitializeRefChunkData(CurrentRefPanel); InitializeRefChipOnlyChunkData(CurrentRefPanelChipOnly); stats.PreInitialize(MaxRefMarkerSize); // if(MyAllVariables->myOutFormat.memUsage) // { // RefMem = CurrentRefPanel.size(); // ComRefMem = CurrentRefPanelChipOnly.size(); // } } void Analysis::InitializeTargetFileStream(String &Tarfilename) { VcfHeader header; TarFileStream.open(Tarfilename, header); TarFileStream.setSiteOnly(false); FileReadIndex=0; overlapImportIndex=0; importReadIndex=0; GWASOnlySkipIndexpoint = 0; MainTypedOnlyImportIndex =0; InitializeTargetChipOnlyChunkData(CurrentTarPanelChipOnly); // if(MyAllVariables->myOutFormat.memUsage) // { // TarMem = CurrentTarPanelChipOnly.size(); // } } String Analysis::RunEstimation(String &Reffilename, String &Recomfilename, String &Errorfilename) { // int time_prev=time(0); // if (!targetPanel.ScaffoldGWAStoReference(referencePanel,*MyAllVariables)) // { // cout << "\n Program Exiting ... \n\n"; // return "Reference.Panel.Load.Error"; // } // // cout<<"\n ------------------------------------------------------------------------------"<myOutFormat.memUsage) // { // cout<<" ------------------------------------------------------------------------------"<myModelVariables.cpus); // // if(MyAllVariables->myOutFormat.vcfBuffer >= targetPanel.numSamples) // MyAllVariables->myOutFormat.vcfBuffer=targetPanel.numSamples; // // thisDataFast.InitializeOutputFiles(targetPanel, MyAllVariables->myOutFormat.vcfBuffer, MaxRefMarkerSize, MaxGwasMarkerSize); // if(MyAllVariables->myOutFormat.memUsage) // { // // cout<<" Estimating Memory based on a single chunk ..."<< endl; // // readm3vcfFileChunk(0, CurrentRefPanel); // readVcfFileChunk(0, CurrentTarPanelChipOnly); // GetCurrentPanelReady(0, CurrentRefPanel, CurrentRefPanelChipOnly, CurrentTarPanelChipOnly, thisDataFast); // cout<myOutFormat.meta) // AppendtoMainLooVcfFaster(i,thisDataFast.TotalNovcfParts); // PrintInfoFile(i); // // time_load = time(0) - time_prev; // cout << "\n Time taken for this chunk = " << time_load << " seconds."<myHapDataVariables.end==0 && MyAllVariables->myOutFormat.TypedOnly) //// assert(FileReadIndex==targetPanel.importIndexListSize); //// asserassertt(OverCount==targetPanel.numOverlapMarkers); //// assert(TypOnlyCount==targetPanel.numTypedOnlyMarkers); //// assert(RefCOUNT==referencePanel.NoBlocks); // // CloseStreamOutputFiles(); return "Success"; } String Analysis::AnalyzeExperiment(String &Reffilename, String &Tarfilename, String &Recomfilename, String &Errorfilename, AllVariable& MyAllVariable) { String mysuccessresult="Error"; cout << " Starting Main Imputation/Estimation Analysis ... " << endl; cout << "\n Performing preliminary check on input parameters... " ; MyOutFormat=&MyAllVariable.myOutFormat; MyModelVariables=&MyAllVariable.myModelVariables; MyHapDataVariables=&MyAllVariable.myHapDataVariables; MyAllVariables=&MyAllVariable; int time_prev=time(0); mysuccessresult=CheckValidity(Reffilename, Tarfilename, Recomfilename, Errorfilename); TimeToRead+=( time(0) - time_prev); if(mysuccessresult!="Success") return mysuccessresult; if(!MyModelVariables->processReference) { mysuccessresult=RunAnalysis(Reffilename, Tarfilename, Recomfilename, Errorfilename); } else { Estimation MyEstimation; mysuccessresult = MyEstimation.RunEstimation(Reffilename, Recomfilename, Errorfilename, MyAllVariable); } if(mysuccessresult!="Success") return mysuccessresult; return "Success"; } bool Analysis::CheckGeneticMapFile() { std::cout << "\n Checking genetic map file : "<myHapDataVariables.mapFile << endl<myHapDataVariables.mapFile, "r"); string line; GeneticMapData.clear(); const char* tabSep="\t"; vector Pieces(4); vector AppendPiece(2); double PrevSumVal=0.0; if(fileStream) { while(fileStream->readLine(line)!=-1) { MyTokenize(Pieces, line.c_str(), tabSep,4); if(Pieces[0]==targetPanel.finChromosome) { AppendPiece[0]=atof(Pieces[3].c_str()); AppendPiece[1]=atof(Pieces[2].c_str())-PrevSumVal; PrevSumVal=atof(Pieces[2].c_str()); GeneticMapData.push_back(AppendPiece); //cout<myHapDataVariables.mapFile << endl; cout << "\n Program Exiting ... \n\n"; return false; } if(GeneticMapData.size()<2) { cout << "\n ERROR !!! Chromosome "<myHapDataVariables.mapFile << endl; cout << "\n Program Exiting ... \n\n"; return false; } ifclose(fileStream); cout<<" Successful !!! "<myModelVariables.CheckValidity()) { return "Command.Line.Error"; } if(!MyAllVariables->myHapDataVariables.CheckValidity()) { return "Command.Line.Error"; } if(!MyAllVariables->myOutFormat.CheckValidity()) { return "Command.Line.Error"; } // if(MyAllVariables->myOutFormat.verbose) // { // MyAllVariables->myHapDataVariables.ChunkLengthMb=299; // } if(!MyAllVariables->myModelVariables.processReference) { if (Tarfilename == "") { cout <<" ERROR !!! \n Missing \"--haps\", a required parameter (for imputation).\n"; cout <<" OR use \"--processReference\" to just process the reference panel.\n"; cout << "\n Program Exiting ... \n\n"; return "Command.Line.Error"; } } else if (Tarfilename != "") { cout <<" ERROR !!! \n \"--haps\" is NOT valid when \"--estimate\" is ON.\n"; cout <<" Parameter estimation only requires a reference panel. \n"; cout <<" No GWAS panel is required.\n"; cout << "\n Program Exiting ... \n\n"; return "Command.Line.Error"; } cout<<" ------------------------------------------------------------------------------"<myModelVariables.processReference) { if (!targetPanel.BasicCheckForTargetHaplotypes(Tarfilename, "GWAS", *MyAllVariables)) { return "Target.Panel.Load.Error"; } } if(!MyAllVariables->myModelVariables.referenceEstimates) { if (!CheckGeneticMapFile()) { return "Genetic.Map.File.Load.Error"; } } return "Success"; } Minimac4-1.0.2/src/Analysis.h000066400000000000000000000136101353222426400157020ustar00rootroot00000000000000#ifndef ANALYSIS_H_INCLUDED #define ANALYSIS_H_INCLUDED #if defined(_OPENMP) #include #endif #include "MyVariables.h" #include "Unique.h" #include "Imputation.h" #include "HaplotypeSet.h" //#include "StringBasics.h" //#include "VcfFileReader.h" //#include //#include //#include //#include #include using namespace std; class Analysis { public: // Basic Variables HaplotypeSet targetPanel,referencePanel; IFILE RefFileStream; VcfFileReader TarFileStream; VcfRecord record; vector< vector > GeneticMapData; // Swapping Variables for actual chunk IMPUTATION HaplotypeSet CurrentTarPanel,CurrentRefPanel; HaplotypeSet CurrentTarPanelChipOnly,CurrentRefPanelChipOnly; int PrevChunkFilledTillRef, PrevChunkStartFromRef; int PrevChunkFilledTillTar, PrevChunkStartFromTar; int PrevChunkFilledTillTarOnly, PrevChunkStartFromTarOnly; void InitializeTargetChipOnlyChunkData(HaplotypeSet &ThisTarPanel); void InitializeRefChipOnlyChunkData(HaplotypeSet &ThisRefPanel); void readm3vcfFileChunk(int ChunkNo, HaplotypeSet &ThisRefPanel); void readVcfFileChunk(int ChunkNo, HaplotypeSet &ThisTargetPanel); // Target PANEL Indexing Variables int overlapImportIndex, importReadIndex, FileReadIndex; int GWASOnlySkipIndexpoint , MainTypedOnlyImportIndex; // Output File Handle Streams IFILE dosages, hapdose, haps, vcfdosepartial, vcfLoodosepartial, info; ImputationStatistics stats; // Chunk Information int noChunks; vector< vector > MyChunks,MyChunksInfoNumber; vector< vector > MyRefVariantNumber, MyTargetVariantNumber, MyTypdedOnlyVariantNumber; vector< float > MyRatio; int MaxInfoVectorSize, MaxGwasMarkerSize, MaxRefMarkerSize, MaxTypedOnlyMarkerSize; // Temporary Variables to be deleted later for checking purposes. int OverCount, TypOnlyCount, RefCOUNT; // Time Variables int TimeToCompress, TimeToRead, TimeToImpute, TimeToWrite; // Memory Variables double RefMem, TarMem, ComRefMem, DosageMem, ProbMem; // Printing Text Variables char *VcfPrintStringPointer, *LooVcfPrintStringPointer, *InfoPrintStringPointer, *DosePrintStringPointer; int VcfPrintStringLength, InfoPrintStringLength, DosePrintStringLength; vector InfoforChunk; vector< vector > BPListMapper; HaplotypeSet *CurrentChunk, *NextChunk; HaplotypeSet MainReferenceFrame; OutputFormatVariable *MyOutFormat; ModelVariable *MyModelVariables; HaplotypeDataVariables *MyHapDataVariables; AllVariable *MyAllVariables; void PrintInfoFile(int ChunkNo); Analysis() { TimeToCompress=0; TimeToRead=0; TimeToImpute=0; TimeToWrite=0; RefMem =0.0; TarMem =0.0; ComRefMem =0.0; DosageMem =0.0; ProbMem = 0.0; } void AppendtoMainVcf(int ChunkNo, int MaxIndex); void AppendtoMainLooVcfFaster(int ChunkNo, int MaxIndex); void AppendtoMainVcfFaster(int ChunkNo, int MaxIndex); void MemDisplay(); void GetNumChunks(); String RunEstimation(String &Reffilename, String &Recomfilename, String &Errorfilename); String AnalyzeExperiment(String &Reffilename, String &Tarfilename, String &Recomfilename,String &Errorfilename, AllVariable& MyAllVariable); String CheckValidity(String &Reffilename, String &Tarfilename, String &Recomfilename, String &Errorfilename); String RunAnalysis(String &Reffilename, String &Tarfilename, String &Recomfilename, String &Errorfilename); void readm3vcfFileChunk(HaplotypeSet &ThisRefPanel, HaplotypeSet &NextRefPanel, int StartBlock, int EndBlock, int StartNextBlock); void readVcfFileChunk(HaplotypeSet &ThisTargetPanel, HaplotypeSet &NextTargetPanel, int StartPos, int EndPos, int StartNextPos, int ChunkNo); bool OpenStreamOutputFiles(); void CloseStreamOutputFiles(); void InitializeRefFileStream(String &Reffilename); void InitializeTargetFileStream(String &Tarfilename); void InitializeRefChunkData(HaplotypeSet &ThisRefPanel); void InitializeTargetChunkData(HaplotypeSet &ThisTarPanel); bool CreateRecombinationMap(); bool CreateChunks(); bool CreateChunksForParamEstimation(); void InitializeChunkVariables(); void CreateChunksFromReference(); void CreateChunksFromVCFReference(); void ImportChunksToTarget(); bool CheckChunkValidityandPrintChunk(); bool CheckChunkValidityForParamEstimationandPrintChunk(); bool CheckGeneticMapFile(); void CreatePrintIndices(int ChunkNo, HaplotypeSet &ThisRefPanel, HaplotypeSet &ThisTarPanel); void GetCurrentPanelReady(int ChunkNo, HaplotypeSet &ThisRefPanel, HaplotypeSet &ThisRefChipOnlyPanel, HaplotypeSet &ThisTarPanel,Imputation &thisDataFast); }; #endif // ANALYSIS_H_INCLUDED Minimac4-1.0.2/src/AnalysisChunks.cpp000066400000000000000000000446331353222426400174220ustar00rootroot00000000000000#include "Analysis.h" #include #include "assert.h" void Analysis::InitializeRefChunkData(HaplotypeSet &ThisRefPanel) { int NoRefHaps=referencePanel.numHaplotypes; ThisRefPanel.numHaplotypes=NoRefHaps; ThisRefPanel.numSamples=referencePanel.numSamples; ThisRefPanel.SampleNoHaplotypes=referencePanel.SampleNoHaplotypes; ThisRefPanel.CummulativeSampleNoHaplotypes=referencePanel.CummulativeSampleNoHaplotypes; ThisRefPanel.individualName=referencePanel.individualName; ThisRefPanel.maxBlockSize=referencePanel.maxBlockSize; ThisRefPanel.maxRepSize=referencePanel.maxRepSize; ThisRefPanel.ReducedStructureInfo.resize(MaxInfoVectorSize); ThisRefPanel.MyAllVariables=MyAllVariables; ThisRefPanel.MapRefToTar.resize(MaxRefMarkerSize); ThisRefPanel.MapTarToRef.resize(MaxGwasMarkerSize); int Mem=0; for(int i=0;imyOutFormat.verbose) { ThisRefPanel.VariantList.resize(MaxRefMarkerSize); } } void Analysis::InitializeRefChipOnlyChunkData(HaplotypeSet &ThisRefPanel) { int NoRefHaps=referencePanel.numHaplotypes; ThisRefPanel.numHaplotypes=NoRefHaps; ThisRefPanel.numSamples=referencePanel.numSamples; ThisRefPanel.MarkerToReducedInfoMapper.resize(MaxGwasMarkerSize); ThisRefPanel.Recom.resize(MaxGwasMarkerSize); ThisRefPanel.Error.resize(MaxGwasMarkerSize); ThisRefPanel.AlleleFreq.resize(MaxGwasMarkerSize); ThisRefPanel.MyAllVariables=MyAllVariables; if(MyAllVariables->myOutFormat.verbose) { ThisRefPanel.individualName=referencePanel.individualName; ThisRefPanel.SampleNoHaplotypes=referencePanel.SampleNoHaplotypes; ThisRefPanel.VariantList.resize(MaxGwasMarkerSize); } } void Analysis::InitializeTargetChipOnlyChunkData(HaplotypeSet &ThisTarPanel) { int tempnumHaplotypes=targetPanel.numHaplotypes; ThisTarPanel.MyAllVariables=MyAllVariables; ThisTarPanel.numHaplotypes=targetPanel.numHaplotypes; ThisTarPanel.numSamples=targetPanel.numSamples; ThisTarPanel.SampleNoHaplotypesPointer=&targetPanel.SampleNoHaplotypes; ThisTarPanel.SampleNoHaplotypes=targetPanel.SampleNoHaplotypes; ThisTarPanel.CummulativeSampleNoHaplotypes=targetPanel.CummulativeSampleNoHaplotypes; ThisTarPanel.individualName=targetPanel.individualName; ThisTarPanel.haplotypesUnscaffolded.resize(tempnumHaplotypes); ThisTarPanel.MissingSampleUnscaffolded.resize(tempnumHaplotypes); if(MyAllVariables->myOutFormat.TypedOnly) { ThisTarPanel.GWASOnlyhaplotypesUnscaffolded.resize(tempnumHaplotypes); ThisTarPanel.GWASOnlyMissingSampleUnscaffolded.resize(tempnumHaplotypes); } for (int i = 0; imyOutFormat.TypedOnly) { ThisTarPanel.TypedOnlyVariantList.resize(MaxTypedOnlyMarkerSize); ThisTarPanel.GWASOnlyhaplotypesUnscaffolded[i].resize(MaxTypedOnlyMarkerSize, '0'); ThisTarPanel.GWASOnlyMissingSampleUnscaffolded[i].resize(MaxTypedOnlyMarkerSize, '0'); } } ThisTarPanel.GWASOnlyAlleleFreq.resize(MaxTypedOnlyMarkerSize); ThisTarPanel.FlankRegionStart.resize(MaxGwasMarkerSize); ThisTarPanel.FlankRegionEnd.resize(MaxGwasMarkerSize); } void Analysis::InitializeChunkVariables() { int i; MyChunks.resize(noChunks); MyChunksInfoNumber.resize(noChunks+1); // extra element added just to reduce checks later on MyRefVariantNumber.resize(noChunks+1); // extra element added just to reduce checks later on MyTargetVariantNumber.resize(noChunks+1); // extra element added just to reduce checks later on MyTypdedOnlyVariantNumber.resize(noChunks+1); // extra element added just to reduce checks later on MyRatio.resize(noChunks+1,-1.0); // extra element added just to reduce checks later on for(i=0;i<(noChunks);i++) { MyChunks[i].resize(4); MyChunksInfoNumber[i].resize(3); MyRefVariantNumber[i].resize(3); MyTargetVariantNumber[i].resize(3,-3); MyTypdedOnlyVariantNumber[i].resize(3,-3); } MyChunksInfoNumber[i].resize(1,99999999); // extra element added just to reduce checks later on MyRefVariantNumber[i].resize(1,99999999); // extra element added just to reduce checks later on MyTargetVariantNumber[i].resize(1,99999999); // extra element added just to reduce checks later on MyTypdedOnlyVariantNumber[i].resize(1,99999999); // extra element added just to reduce checks later on } void Analysis::CreateChunksFromReference() { vector &RefInfo=referencePanel.ReducedStructureInfoSummary; vector &VarList=referencePanel.VariantList; vector &InfoMapper=referencePanel.MarkerToReducedInfoMapper; int NoMarkers=referencePanel.numMarkers; int i=0,index; MyChunksInfoNumber[0][0]=0; MyRefVariantNumber[0][0]=0; MyChunks[0][0]=VarList[0].bp; MyChunks[0][1]=VarList[0].bp; if(noChunks>1) { MyChunksInfoNumber[0][1]=InfoMapper[0 + MyHapDataVariables->ChunkSize + MyHapDataVariables->ChunkWindow]; MyRefVariantNumber[0][1]= RefInfo[MyChunksInfoNumber[0][1]].endIndex ; MyChunks[0][2]=VarList[0 + MyHapDataVariables->ChunkSize].bp; MyChunks[0][3]=VarList[MyRefVariantNumber[0][1]].bp; for(i=1;i<(noChunks-1);i++) { index=(i*MyHapDataVariables->ChunkSize); MyChunksInfoNumber[i][0]=InfoMapper[index-MyHapDataVariables->ChunkWindow]; MyChunksInfoNumber[i][1]=InfoMapper[index+MyHapDataVariables->ChunkSize+MyHapDataVariables->ChunkWindow]; MyRefVariantNumber[i][0]=RefInfo[MyChunksInfoNumber[i][0]].startIndex; MyRefVariantNumber[i][1]= RefInfo[MyChunksInfoNumber[i][1]].endIndex; MyChunks[i][0]=VarList[MyRefVariantNumber[i][0]].bp; MyChunks[i][1]=MyChunks[i-1][2]+1; MyChunks[i][2]=VarList[index+MyHapDataVariables->ChunkSize].bp; MyChunks[i][3]=VarList[MyRefVariantNumber[i][1]].bp; } index=(i*MyHapDataVariables->ChunkSize); MyChunksInfoNumber[i][0]=InfoMapper[index-MyHapDataVariables->ChunkWindow]; MyRefVariantNumber[i][0]=RefInfo[MyChunksInfoNumber[i][0]].startIndex; MyChunks[i][0]=VarList[MyRefVariantNumber[i][0]].bp; MyChunks[i][1]=MyChunks[i-1][2]+1; } MyChunks[i][2]=VarList[NoMarkers-1].bp; MyChunks[i][3]=VarList[NoMarkers-1].bp; MyChunksInfoNumber[i][1]=InfoMapper[NoMarkers-1]; MyRefVariantNumber[i][1]=NoMarkers-1; for(int i=0;i &VarList=referencePanel.VariantList; int NoMarkers=referencePanel.numMarkers; int index; MyRefVariantNumber[0][0]=0; MyChunks[0][0]=VarList[0].bp; MyChunks[0][1]=VarList[0].bp; i=0; if(noChunks>1) { MyChunks[0][2]=VarList[0 + MyHapDataVariables->ChunkSize].bp; MyChunks[0][3]=VarList[0 + MyHapDataVariables->ChunkSize + MyHapDataVariables->ChunkWindow].bp; MyRefVariantNumber[0][1]=MyHapDataVariables->ChunkSize + MyHapDataVariables->ChunkWindow; for(i=1;i<(noChunks-1);i++) { index=(i*MyHapDataVariables->ChunkSize); MyRefVariantNumber[i][0]=index-MyHapDataVariables->ChunkWindow; MyChunks[i][0]=VarList[index-MyHapDataVariables->ChunkWindow].bp; MyChunks[i][1]=MyChunks[i-1][2]+1; MyChunks[i][2]=VarList[index+MyHapDataVariables->ChunkSize].bp; MyChunks[i][3]=VarList[index+MyHapDataVariables->ChunkSize+MyHapDataVariables->ChunkWindow].bp; MyRefVariantNumber[i][1]= index+MyHapDataVariables->ChunkSize+MyHapDataVariables->ChunkWindow; } index=(i*MyHapDataVariables->ChunkSize); MyRefVariantNumber[i][0]=index-MyHapDataVariables->ChunkWindow; MyChunks[i][0]=VarList[index-MyHapDataVariables->ChunkWindow].bp; MyChunks[i][1]=MyChunks[i-1][2]+1; } MyChunks[i][2]=VarList[NoMarkers-1].bp; MyChunks[i][3]=VarList[NoMarkers-1].bp; MyRefVariantNumber[i][1]=NoMarkers-1; for(int i=0;i0) { while(i MyTargetVariantNumber[i][0]? MyTargetVariantNumber[i][1] + 1 - MyTargetVariantNumber[i][0]: 0 ); MyTypdedOnlyVariantNumber[i][2] = ( MyTypdedOnlyVariantNumber[i][1] + 1 >MyTypdedOnlyVariantNumber[i][0]? MyTypdedOnlyVariantNumber[i][1] + 1 - MyTypdedOnlyVariantNumber[i][0]: 0 ); } } bool Analysis::CheckChunkValidityandPrintChunk() { int MinRefMarkerSize=MyRefVariantNumber[0][2], InIndex=0; int MinGwasMarkerSize=MyTargetVariantNumber[0][2], MaIndex=0; float minRatio=100.0,raIndex=0; MaxInfoVectorSize=0; MaxRefMarkerSize=0; MaxGwasMarkerSize=0; MaxTypedOnlyMarkerSize=0; cout<<" No LeftBuffer LeftEnd RightPoint RightBuffer #Sites(GWAS/Ref/%)"< MaxInfoVectorSize ) MaxInfoVectorSize = MyChunksInfoNumber[i][2]; if( MyRefVariantNumber[i][2] > MaxRefMarkerSize ) MaxRefMarkerSize = MyRefVariantNumber[i][2]; if( MyRefVariantNumber[i][2] < MinRefMarkerSize ) { InIndex=i; MinRefMarkerSize = MyRefVariantNumber[i][2]; } if( MyTargetVariantNumber[i][2] > MaxGwasMarkerSize ) MaxGwasMarkerSize = MyTargetVariantNumber[i][2]; if( MyTargetVariantNumber[i][2] < MinGwasMarkerSize ) { MaIndex=i; MinGwasMarkerSize = MyTargetVariantNumber[i][2]; } if( MyTypdedOnlyVariantNumber[i][2] > MaxTypedOnlyMarkerSize ) MaxTypedOnlyMarkerSize = MyTypdedOnlyVariantNumber[i][2]; if(MyTargetVariantNumber[i][2] >0 && MyRefVariantNumber[i][2] > 0 ) { MyRatio[i]=100.0*(float)MyTargetVariantNumber[i][2]/(float)MyRefVariantNumber[i][2]; if(minRatio>MyRatio[i]) { minRatio=MyRatio[i]; raIndex=i; } } cout<myHapDataVariables.minRatio)) { cout<<"\n ERROR !!! ERROR !!! ERROR !!! "<myHapDataVariables.minRatio <<"\% of variants from the GWAS panel overlapping with the reference panel ... "< MaxRefMarkerSize ) MaxRefMarkerSize = MyRefVariantNumber[i][2]; if( MyRefVariantNumber[i][2] < MinRefMarkerSize ) { InIndex=i; MinRefMarkerSize = MyRefVariantNumber[i][2]; } cout<ChunkSize <<" variants in each chunk ... " << endl<ChunkSize <<" variants in each chunk ... " << endl<myHapDataVariables.ChunkOverlapMb)); if(noOverLaps==0) noOverLaps=1; MyHapDataVariables->ChunkWindow=(NoMarkers/noOverLaps); noChunks = ((int)(EndPos-StartPos)/(int)(1000000 *MyAllVariables->myHapDataVariables.ChunkLengthMb)); if(noChunks==0) noChunks=1; MyHapDataVariables->ChunkSize=(NoMarkers/noChunks); return; } Minimac4-1.0.2/src/DosageData.cpp000066400000000000000000000410531353222426400164500ustar00rootroot00000000000000#include "DosageData.h" #include "HaplotypeSet.h" #include "assert.h" void DosageData::FlushPartialVcf(int NovcfParts) { PrintStringLength=0; PrintEmpStringLength=0; int time_Start = time(0); string PartialVcfFileName(MyAllVariables->myOutFormat.OutPrefix); string PartialMetaVcfFileName(MyAllVariables->myOutFormat.OutPrefix); stringstream strs,strs1; strs<<(NovcfParts); strs1<<(ChunkNo+1); PartialVcfFileName+=(".chunk."+(string)(strs1.str())+ ".dose.part."+ (string)(strs.str())+".vcf.gz"); PartialMetaVcfFileName+=(".chunk."+(string)(strs1.str())+ ".empiricalDose.part."+ (string)(strs.str())+".vcf.gz"); IFILE vcfdosepartial = ifopen(PartialVcfFileName.c_str(), "wb", InputFile::BGZF); IFILE vcfLoodosepartial = NULL; if(MyAllVariables->myOutFormat.meta) vcfLoodosepartial=ifopen(PartialMetaVcfFileName.c_str(), "wb", InputFile::UNCOMPRESSED); for(int Id=0;IdSampleNoHaplotypes[FullSamID]; } int i=0; for (int index = 0; index < rHapFull->RefTypedTotalCount; index++) { if(rHapFull->RefTypedIndex[index]==-1) { if(i>=rHapFull->PrintStartIndex && i <= rHapFull->PrintEndIndex) { PrintDosageForVcfOutputForID(i); } i++; } else { int MappingIndex = rHapFull->RefTypedIndex[index]; if(MappingIndex>=tHapFull->PrintTypedOnlyStartIndex && MappingIndex<=tHapFull->PrintTypedOnlyEndIndex) { PrintGWASOnlyForVcfOutputForID(MappingIndex); } } if(PrintStringLength > 0.9 * (float)(MyAllVariables->myOutFormat.PrintBuffer)) { ifprintf(vcfdosepartial,"%s",PrintStringPointer); PrintStringLength=0; } if(PrintEmpStringLength > 0.9 * (float)(MyAllVariables->myOutFormat.PrintBuffer)) { ifprintf(vcfLoodosepartial,"%s",PrintEmpStringPointer); PrintEmpStringLength=0; } } if(PrintStringLength>0) { ifprintf(vcfdosepartial,"%s",PrintStringPointer); PrintStringLength=0; } if(PrintEmpStringLength >0) { ifprintf(vcfLoodosepartial,"%s",PrintEmpStringPointer); PrintEmpStringLength=0; } ifclose(vcfdosepartial); if(MyAllVariables->myOutFormat.meta) ifclose(vcfLoodosepartial); TimeToWrite=time(0) - time_Start; } void DosageData::PrintDiploidDosage(float &x, float &y) { bool colonIndex=false; PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"\t"); if(!MyAllVariables->myOutFormat.longZero && x<0.0005 && y<0.0005) { if(MyAllVariables->myOutFormat.GT) { if(!MyAllVariables->myOutFormat.unphasedOutput) PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"0|0"); else { PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"0/0"); } colonIndex=true; } if(MyAllVariables->myOutFormat.DS) { if(colonIndex) PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,":"); PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"0"); colonIndex=true; } if(MyAllVariables->myOutFormat.HDS) { if(colonIndex) PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,":"); PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"0,0"); colonIndex=true; } if(MyAllVariables->myOutFormat.GP) { if(colonIndex) PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,":"); colonIndex=true; PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"1,0,0"); } if(MyAllVariables->myOutFormat.SD) { if(colonIndex) PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,":"); colonIndex=true; PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"0"); } return; } if(MyAllVariables->myOutFormat.GT) { if(!MyAllVariables->myOutFormat.unphasedOutput) PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"%d|%d",(x>0.5),(y>0.5)); else { bool a1=(x>0.5); bool a2=(y>0.5); if((a1^a2)==1) PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"0/1"); else if(a1 && a2) PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"1/1"); else PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"0/0"); } colonIndex=true; } if(MyAllVariables->myOutFormat.DS) { if(colonIndex) PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,":"); PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"%.3f",x+ y); colonIndex=true; } if(MyAllVariables->myOutFormat.HDS) { if(colonIndex) PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,":"); PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"%.3f,%.3f",x , y); colonIndex=true; } if(MyAllVariables->myOutFormat.GP) { if(colonIndex) PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,":"); colonIndex=true; PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"%.3f,%.3f,%.3f",(1-x)*(1-y),x*(1-y)+y*(1-x),x*y); } if(MyAllVariables->myOutFormat.SD) { if(colonIndex) PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,":"); colonIndex=true; PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"%.3f", x*(1-x) + y*(1-y)); } } void DosageData::PrintHaploidDosage(float &x) { bool colonIndex=false; PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"\t"); if(!MyAllVariables->myOutFormat.longZero && x<0.0005) { if(MyAllVariables->myOutFormat.GT) { PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"0"); colonIndex=true; } if(MyAllVariables->myOutFormat.DS) { if(colonIndex) PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,":"); PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"0"); colonIndex=true; } if(MyAllVariables->myOutFormat.HDS) { if(colonIndex) PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,":"); PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"0"); colonIndex=true; } if(MyAllVariables->myOutFormat.GP) { if(colonIndex) PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,":"); colonIndex=true; PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"1,0"); } if(MyAllVariables->myOutFormat.SD) { if(colonIndex) PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,":"); colonIndex=true; PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"0"); } return; } if(MyAllVariables->myOutFormat.GT) { PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"%d",(x>0.5)); colonIndex=true; } if(MyAllVariables->myOutFormat.DS) { if(colonIndex) PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,":"); PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"%.3f",x); colonIndex=true; } if(MyAllVariables->myOutFormat.HDS) { if(colonIndex) PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,":"); PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"%.3f",x ); colonIndex=true; } if(MyAllVariables->myOutFormat.GP) { if(colonIndex) PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,":"); colonIndex=true; PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"%.3f,%.3f",1-x,x); } if(MyAllVariables->myOutFormat.SD) { if(colonIndex) PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,":"); colonIndex=true; PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"%.3f", x*(1-x)); } } void DosageData::PrintDiploidLooDosage(float &x, float &y, AlleleType a, AlleleType b) { PrintEmpStringLength+=sprintf(PrintEmpStringPointer+PrintEmpStringLength,"\t"); PrintEmpStringLength+=sprintf(PrintEmpStringPointer+PrintEmpStringLength,"%c|%c",a,b); PrintEmpStringLength+=sprintf(PrintEmpStringPointer+PrintEmpStringLength,":"); PrintEmpStringLength+=sprintf(PrintEmpStringPointer+PrintEmpStringLength,"%.3f|%.3f",x , y); } void DosageData::PrintHaploidLooDosage(float &x, AlleleType a) { PrintEmpStringLength+=sprintf(PrintEmpStringPointer+PrintEmpStringLength,"\t"); PrintEmpStringLength+=sprintf(PrintEmpStringPointer+PrintEmpStringLength,"%c",a); PrintEmpStringLength+=sprintf(PrintEmpStringPointer+PrintEmpStringLength,":"); PrintEmpStringLength+=sprintf(PrintEmpStringPointer+PrintEmpStringLength,"%.3f",x); } void DosageData::PrintDosageForVcfOutputForID(int MarkerIndex) { for(int Id=0;IdmyOutFormat.meta && !rHapFull->Targetmissing[MarkerIndex] ) { int gwasHapIndex = tHapFull->CummulativeSampleNoHaplotypes[SampleIndex[IndexId]]; int TypedMarkerIndex = rHapFull->MapRefToTar[MarkerIndex]; // assert(TypedMarkerIndexMissingSampleUnscaffolded[0].size()); // assert(gwasHapIndexMissingSampleUnscaffolded.size()); if(NoHaps==2) { if( tHapFull->MissingSampleUnscaffolded[gwasHapIndex][TypedMarkerIndex] =='1' || tHapFull->MissingSampleUnscaffolded[gwasHapIndex+1][TypedMarkerIndex]=='1') { PrintEmpStringLength+=sprintf(PrintEmpStringPointer+PrintEmpStringLength,"\t.|.:.|."); } else { PrintDiploidLooDosage((LoohapDosage[2*IndexId])[TypedMarkerIndex] , (LoohapDosage[2*IndexId+1])[TypedMarkerIndex] , tHapFull->haplotypesUnscaffolded[gwasHapIndex][TypedMarkerIndex], tHapFull->haplotypesUnscaffolded[gwasHapIndex+1][TypedMarkerIndex]); } } else if(NoHaps==1) { if( tHapFull->MissingSampleUnscaffolded[gwasHapIndex][TypedMarkerIndex]=='1') { PrintEmpStringLength+=sprintf(PrintEmpStringPointer+PrintEmpStringLength,"\t.:."); } else { PrintHaploidLooDosage((LoohapDosage[2*IndexId])[TypedMarkerIndex] , tHapFull->haplotypesUnscaffolded[gwasHapIndex][TypedMarkerIndex]); } } else abort(); } } PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"\n"); if(MyAllVariables->myOutFormat.meta && !rHapFull->Targetmissing[MarkerIndex] ) PrintEmpStringLength+=sprintf(PrintEmpStringPointer+PrintEmpStringLength,"\n"); } void DosageData::PrintGWASOnlyForVcfOutputForID(int MarkerIndex) { float freq=(float)tHapFull->GWASOnlyAlleleFreq[MarkerIndex]; float x,y; for(int Id=0;IdCummulativeSampleNoHaplotypes[SampleIndex[IndexId]]; int NoHaps=BufferSampleNoHaplotypes[IndexId]; // assert(FullSamID==(Id+FirstHapId)); if(NoHaps==2) { AlleleType a1=tHapFull->GWASOnlyMissingSampleUnscaffolded[gwasHapIndex][MarkerIndex]; AlleleType a2=tHapFull->GWASOnlyMissingSampleUnscaffolded[gwasHapIndex+1][MarkerIndex]; if(a1=='1' || a2=='1') PrintDiploidDosage(freq,freq); else { x=(float)(tHapFull->GWASOnlyhaplotypesUnscaffolded[gwasHapIndex][MarkerIndex]-'0'); y=(float)(tHapFull->GWASOnlyhaplotypesUnscaffolded[gwasHapIndex+1][MarkerIndex]-'0'); PrintDiploidDosage(x, y); } } else if(NoHaps==1) { AlleleType a1=tHapFull->GWASOnlyMissingSampleUnscaffolded[gwasHapIndex][MarkerIndex]; if(a1=='1') PrintHaploidDosage(freq); else { x=(float)(tHapFull->GWASOnlyhaplotypesUnscaffolded[gwasHapIndex][MarkerIndex]-'0'); PrintHaploidDosage(x); } } else abort(); } PrintStringLength+=sprintf(PrintStringPointer+PrintStringLength,"\n"); } void DosageData::BindSampleMModel(MarkovModel &MM, int Index, int HapNo) { MM.DosageHap=&hapDosage[ (2*Index) + HapNo] ; MM.LooDosageHap=&LoohapDosage[ (2*Index) + HapNo] ; } pair DosageData::IndexSample(int SampleId) { pair Result; InvertSampleIndex[SampleId-FirstHapId]=NoSamplesIndexed; SampleIndex[NoSamplesIndexed++]=SampleId; Result.second=NoSamplesIndexed-1; if(NoSamplesIndexed==BuffernumSamples) { Result.first=1; } return Result; } void DosageData::InitializePartialDosageData(HaplotypeSet &tarInitializer, int MaxNoSamples, int MaxNoRefVariants, int MaxNoTarVariants, AllVariable *MyAllVariable) { MyAllVariables=MyAllVariable; ActualnumHaplotypes = tarInitializer.numHaplotypes; ActualnumSamples = tarInitializer.numSamples; BuffernumSamples = MaxNoSamples; BuffernumHaplotypes = 2*MaxNoSamples; hapDosage.resize(BuffernumHaplotypes); LoohapDosage.resize(BuffernumHaplotypes); BufferSampleNoHaplotypes.resize(BuffernumSamples); SampleIndex.resize(BuffernumSamples); InvertSampleIndex.resize(BuffernumSamples); for(int i=0;imyOutFormat.PrintBuffer)); if(MyAllVariables->myOutFormat.meta) PrintEmpStringPointer = (char*)malloc(sizeof(char) * (MyAllVariables->myOutFormat.PrintBuffer)); individualName=tarInitializer.individualName; } void DosageData::ReParameterizePartialDosageData(int No, HaplotypeSet &refFullHap, HaplotypeSet &tarFullHap) { ChunkNo=No; rHapFull=&refFullHap; tHapFull=&tarFullHap; FirstHapId=0; numMarkers = rHapFull->numMarkers; noGWASSites= tHapFull->numTypedOnlyMarkers; NoSamplesIndexed=0; } void DosageData::UpdatePartialDosageData(int NewMaxVal, int NewFirstHapId) { if(NewMaxVal<=0) return; BuffernumSamples = NewMaxVal; BuffernumHaplotypes = 2*NewMaxVal; NoSamplesIndexed=0; FirstHapId=NewFirstHapId; } Minimac4-1.0.2/src/DosageData.h000066400000000000000000000057711353222426400161240ustar00rootroot00000000000000#ifndef DOSAGEDATA_H_INCLUDED #define DOSAGEDATA_H_INCLUDED #include "StringBasics.h" #include "MyVariables.h" #include "VcfFileReader.h" #include "Unique.h" #include #include #include #include #include #include #include "HaplotypeSet.h" #include "MyVariables.h" #include "MarkovModel.h" using namespace std; class DosageData { public: // Basic Variables int ChunkNo, FirstHapId; int ActualnumHaplotypes, BuffernumHaplotypes; int ActualnumSamples, BuffernumSamples; int numMarkers, noGWASSites; HaplotypeSet *tHapFull; HaplotypeSet *rHapFull; vector individualName; // Indexing Samples Variable int NoSamplesIndexed; vector SampleIndex; vector InvertSampleIndex; vector BufferSampleNoHaplotypes; // Main Data Variable vector > hapDosage; vector > LoohapDosage; // Formatting Variables AllVariable *MyAllVariables; // Time Variables int TimeToWrite; // Printing Text Variables char *PrintStringPointer; char *PrintEmpStringPointer; int PrintStringLength; int PrintEmpStringLength; double size() { double S=0; S+=BufferSampleNoHaplotypes.size() * sizeof(int); S+=InvertSampleIndex.size() * sizeof(int); S+=SampleIndex.size() * sizeof(int); for(int i=0;i<(int)hapDosage.size();i++) { S+=hapDosage[i].size() * sizeof(float); S+=LoohapDosage[i].size() * sizeof(float); } for(int i=0;i<(int)individualName.size();i++) { S+=individualName[i].size(); } return (S); }; void PrintDiploidLooDosage(float &x, float &y, AlleleType a, AlleleType b); void PrintHaploidLooDosage(float &x, AlleleType a); void InitializePartialDosageData(HaplotypeSet &tarInitializer, int MaxNoSamples, int MaxNoRefVariants, int MaxNoTarVariants, AllVariable *MyAllVariable); void ReParameterizePartialDosageData(int No, HaplotypeSet &refFullHap, HaplotypeSet &tarFullHap); void UpdatePartialDosageData(int NewMaxVal, int NewFirstHapId); pair IndexSample(int SampleId); void BindSampleMModel(MarkovModel &MM, int Index, int HapNo); void FlushPartialVcf(int NovcfParts); void PrintDiploidDosage(float &x, float &y); void PrintHaploidDosage(float &x); void PrintDosageForVcfOutputForID(int MarkerIndex); void PrintDosageForVcfOutputForIDFast(int MarkerIndex); void PrintGWASOnlyForVcfOutputForID(int MarkerIndex); DosageData () {}; }; #endif // DOSAGEDATA_H_INCLUDED Minimac4-1.0.2/src/Estimation.cpp000066400000000000000000002013101353222426400165620ustar00rootroot00000000000000#include "Estimation.h" #include #include "assert.h" String Estimation::RunEstimation(String &Reffilename, String &Recomfilename, String &Errorfilename, AllVariable& MyAllVariable) { MyOutFormat=&MyAllVariable.myOutFormat; MyModelVariables=&MyAllVariable.myModelVariables; MyHapDataVariables=&MyAllVariable.myHapDataVariables; MyAllVariables=&MyAllVariable; int time_prev=time(0); if (!referencePanel.BasicCheckForM3VCFReferenceHaplotypes(Reffilename,*MyAllVariables)) { return "Reference.Panel.Load.Error"; } if (!referencePanel.ReadM3VCFChunkingInformation(Reffilename,"")) { cout << "\n Program Exiting ... \n\n"; return "Reference.Panel.Load.Error"; } if (!referencePanel.ScaffoldGWAStoReference(referencePanel,*MyAllVariables)) { cout << "\n Program Exiting ... \n\n"; return "Reference.Panel.Load.Error"; } cout<<"\n ------------------------------------------------------------------------------"<myOutFormat.memUsage) { cout<<" ------------------------------------------------------------------------------"<myModelVariables.cpus); for(int i=0;imyOutFormat.meta) // AppendtoMainLooVcfFaster(i,thisDataFast.TotalNovcfParts); // PrintInfoFile(i); // // time_load = time(0) - time_prev; // cout << "\n Time taken for this chunk = " << time_load << " seconds."<myHapDataVariables.end==0 && MyAllVariables->myOutFormat.TypedOnly) //// assert(FileReadIndex==targetPanel.importIndexListSize); //// asserassertt(OverCount==targetPanel.numOverlapMarkers); //// assert(TypOnlyCount==targetPanel.numTypedOnlyMarkers); //// assert(RefCOUNT==referencePanel.NoBlocks); // // CloseStreamOutputFiles(); // return "Success"; } void Estimation::PrintInfoFile(int ChunkNo) { InfoPrintStringLength=0; int RefStartPos = MyRefVariantNumber[ChunkNo][0]; int i=0; for (int index = 0; index < CurrentRefPanel.RefTypedTotalCount; index++) { if(CurrentRefPanel.RefTypedIndex[index]==-1) { variant &thisVariant = referencePanel.VariantList[i+RefStartPos]; if(i>=CurrentRefPanel.PrintStartIndex && i <= CurrentRefPanel.PrintEndIndex) { double TarFreq = stats.AlleleFrequency(i); InfoPrintStringLength+=sprintf(InfoPrintStringPointer+InfoPrintStringLength , "%s\t%s\t%s\t%.5f\t%.5f\t%.5f\t%.5f\t", MyAllVariables->myOutFormat.RsId ? thisVariant.rsid.c_str(): thisVariant.name.c_str(), thisVariant.refAlleleString.c_str(), thisVariant.altAlleleString.c_str(), TarFreq, TarFreq > 0.5 ? 1.0 - TarFreq : TarFreq, stats.AverageCallScore(i), stats.Rsq(i)); if (!CurrentRefPanel.Targetmissing[i]) { InfoPrintStringLength+=sprintf(InfoPrintStringPointer+InfoPrintStringLength , "Genotyped\t%.3f\t%.3f\t%.5f\t%.5f\t%.5f\n", stats.LooRsq(i), stats.EmpiricalR(i), stats.EmpiricalRsq(i), stats.LooMajorDose(i), stats.LooMinorDose(i)); } else InfoPrintStringLength+=sprintf(InfoPrintStringPointer+InfoPrintStringLength , "Imputed\t-\t-\t-\t-\t-\n"); } i++; } else { // if(ChunkNo==2 && index==26751) // abort(); int MappingIndex = CurrentRefPanel.RefTypedIndex[index]; if(MappingIndex>=CurrentTarPanelChipOnly.PrintTypedOnlyStartIndex && MappingIndex<=CurrentTarPanelChipOnly.PrintTypedOnlyEndIndex) { variant ThisTypedVariant = CurrentTarPanelChipOnly.TypedOnlyVariantList[MappingIndex]; double TarFreq = CurrentTarPanelChipOnly.GWASOnlyAlleleFreq[MappingIndex]; InfoPrintStringLength+=sprintf(InfoPrintStringPointer+InfoPrintStringLength , "%s\t%s\t%s\t%.5f\t%.5f\t-\t-\tTyped_Only\t-\t-\t-\t-\t-\n", MyAllVariables->myOutFormat.RsId ? ThisTypedVariant.rsid.c_str(): ThisTypedVariant.name.c_str(), ThisTypedVariant.refAlleleString.c_str(), ThisTypedVariant.altAlleleString.c_str(), TarFreq, TarFreq > 0.5 ? 1.0 - TarFreq : TarFreq); } } if(InfoPrintStringLength > 0.9 * (float)(MyAllVariables->myOutFormat.PrintBuffer)) { ifprintf(info,"%s",InfoPrintStringPointer); InfoPrintStringLength=0; } } if(InfoPrintStringLength >0) { ifprintf(info,"%s",InfoPrintStringPointer); InfoPrintStringLength=0; } } void Estimation::AppendtoMainLooVcfFaster(int ChunkNo, int MaxIndex) { VcfPrintStringLength=0; int time_prev = time(0); int RefStartPos = MyRefVariantNumber[ChunkNo][0]; vector vcfLoodosepartialList(MaxIndex); for(int i=1;i<=MaxIndex;i++) { string tempFileIndex(MyAllVariables->myOutFormat.OutPrefix); stringstream strs,strs1; strs<<(i); strs1<<(ChunkNo+1); tempFileIndex+=(".chunk."+(string)(strs1.str())+".empiricalDose.part." + (string)(strs.str())+".vcf.gz"); vcfLoodosepartialList[i-1] = ifopen(tempFileIndex.c_str(), "r"); } string line; int i=0; for (int index = 0; index < CurrentRefPanel.RefTypedTotalCount; index++) { if(CurrentRefPanel.RefTypedIndex[index]==-1) { if(i>=CurrentRefPanel.PrintStartIndex && i <= CurrentRefPanel.PrintEndIndex) { if(!CurrentRefPanel.Targetmissing[i]) { variant &tempVariant = referencePanel.VariantList[i+RefStartPos]; VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"%s\t%d\t%s\t%s\t%s\t.\tPASS", tempVariant.chr.c_str(), tempVariant.bp, MyAllVariables->myOutFormat.RsId?tempVariant.rsid.c_str():tempVariant.name.c_str(), tempVariant.refAlleleString.c_str(), tempVariant.altAlleleString.c_str()); VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"\tTYPED\tGT:LDS"); for(int j=1;j<=MaxIndex;j++) { line.clear(); vcfLoodosepartialList[j-1]->readLine(line); VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"%s",line.c_str()); } VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"\n"); } } i++; } if(VcfPrintStringLength > 0.9 * (float)(MyAllVariables->myOutFormat.PrintBuffer)) { ifprintf(vcfLoodosepartial,"%s",VcfPrintStringPointer); VcfPrintStringLength=0; } } if(VcfPrintStringLength > 0) { ifprintf(vcfLoodosepartial,"%s",VcfPrintStringPointer); VcfPrintStringLength=0; } for(int i=1;i<=MaxIndex;i++) { ifclose(vcfLoodosepartialList[i-1]); string tempFileIndex(MyAllVariables->myOutFormat.OutPrefix); stringstream strs,strs1; strs<<(i); strs1<<(ChunkNo+1); tempFileIndex+=(".chunk."+(string)(strs1.str())+".empiricalDose.part." + (string)(strs.str())+".vcf.gz"); remove(tempFileIndex.c_str()); } TimeToWrite+=( time(0) - time_prev); } void Estimation::AppendtoMainVcfFaster(int ChunkNo, int MaxIndex) { VcfPrintStringLength=0; int time_prev = time(0); int RefStartPos = MyRefVariantNumber[ChunkNo][0]; printf("\n Appending chunk to final output VCF File : %s ",(MyAllVariables->myOutFormat.OutPrefix + ".dose.vcf" + (MyAllVariables->myOutFormat.gzip ? ".gz" : "")).c_str() ); cout< vcfdosepartialList(MaxIndex); for(int i=1;i<=MaxIndex;i++) { string tempFileIndex(MyAllVariables->myOutFormat.OutPrefix); stringstream strs,strs1; strs<<(i); strs1<<(ChunkNo+1); tempFileIndex+=(".chunk."+(string)(strs1.str())+".dose.part." + (string)(strs.str())+".vcf.gz"); vcfdosepartialList[i-1] = ifopen(tempFileIndex.c_str(), "r"); } string line; int i=0; for (int index = 0; index < CurrentRefPanel.RefTypedTotalCount; index++) { if(CurrentRefPanel.RefTypedIndex[index]==-1) { if(i>=CurrentRefPanel.PrintStartIndex && i <= CurrentRefPanel.PrintEndIndex) { variant &tempVariant = referencePanel.VariantList[i+RefStartPos]; VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"%s\t%d\t%s\t%s\t%s\t.\tPASS", tempVariant.chr.c_str(), tempVariant.bp, MyAllVariables->myOutFormat.RsId?tempVariant.rsid.c_str():tempVariant.name.c_str(), tempVariant.refAlleleString.c_str(), tempVariant.altAlleleString.c_str()); double freq = stats.AlleleFrequency(i); VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"\tAF=%.5f;MAF=%.5f;R2=%.5f", freq, freq > 0.5 ? 1.0 - freq : freq, stats.Rsq(i)); if(!CurrentRefPanel.Targetmissing[i]) VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,";ER2=%.5f;TYPED",stats.EmpiricalRsq(i)); else VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,";IMPUTED"); VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"\t%s",MyAllVariables->myOutFormat.formatStringForVCF.c_str()); for(int j=1;j<=MaxIndex;j++) { line.clear(); vcfdosepartialList[j-1]->readLine(line); VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"%s",line.c_str()); } VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"\n"); } i++; } else { int MappingIndex = CurrentRefPanel.RefTypedIndex[index]; if(MappingIndex>=CurrentTarPanelChipOnly.PrintTypedOnlyStartIndex && MappingIndex<=CurrentTarPanelChipOnly.PrintTypedOnlyEndIndex) { variant &ThisTypedVariant = (CurrentTarPanelChipOnly.TypedOnlyVariantList[CurrentRefPanel.RefTypedIndex[index]]); VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"%s\t%d\t%s\t%s\t%s\t.\tPASS", ThisTypedVariant.chr.c_str(), ThisTypedVariant.bp, MyAllVariables->myOutFormat.RsId? ThisTypedVariant.rsid.c_str():ThisTypedVariant.name.c_str(), ThisTypedVariant.refAlleleString.c_str(), ThisTypedVariant.altAlleleString.c_str()); double &freq = (CurrentTarPanelChipOnly.GWASOnlyAlleleFreq[CurrentRefPanel.RefTypedIndex[index]]); VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"\tAF=%.5f;MAF=%.5f;TYPED_ONLY", freq, freq > 0.5 ? 1.0 - freq : freq); VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"\t%s",MyAllVariables->myOutFormat.formatStringForVCF.c_str()); for(int j=1;j<=MaxIndex;j++) { line.clear(); vcfdosepartialList[j-1]->readLine(line); VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"%s",line.c_str()); } VcfPrintStringLength+=sprintf(VcfPrintStringPointer + VcfPrintStringLength,"\n"); } } if(VcfPrintStringLength > 0.9 * (float)(MyAllVariables->myOutFormat.PrintBuffer)) { ifprintf(vcfdosepartial,"%s",VcfPrintStringPointer); VcfPrintStringLength=0; } } if(VcfPrintStringLength > 0) { ifprintf(vcfdosepartial,"%s",VcfPrintStringPointer); VcfPrintStringLength=0; } for(int i=1;i<=MaxIndex;i++) { ifclose(vcfdosepartialList[i-1]); string tempFileIndex(MyAllVariables->myOutFormat.OutPrefix); stringstream strs,strs1; strs<<(i); strs1<<(ChunkNo+1); tempFileIndex+=(".chunk."+(string)(strs1.str())+".dose.part." + (string)(strs.str())+".vcf.gz"); remove(tempFileIndex.c_str()); } TimeToWrite+=( time(0) - time_prev); cout << " Appending successful (" << time(0) - time_prev << " seconds) !!!"< &ThisInfoVector = ThisRefPanel.ReducedStructureInfo; string line; int ThisInfoVectorIndex=0; int ThisChunkFilledTillRef = 0, ThisChunkStartFromRef = 0; int StartBlock=MyChunksInfoNumber[ChunkNo][0]; int EndBlock=MyChunksInfoNumber[ChunkNo][1]; int StartNextBlock=MyChunksInfoNumber[ChunkNo+1][0]; int blockIndex=StartBlock; int FilltheTop=0; while(FilltheTop < PrevChunkFilledTillRef) { ThisInfoVector[blockIndex-StartBlock] = ThisInfoVector[PrevChunkStartFromRef + FilltheTop] ; blockIndex++; FilltheTop++; } ThisChunkStartFromRef=FilltheTop; for(;blockIndex<=EndBlock;blockIndex++) { RefCOUNT++; line.clear(); RefFileStream->readLine(line); // assert(ThisInfoVectorIndex + PrevChunkFilledTillRef < MaxInfoVectorSize); ReducedHaplotypeInfo &tempBlock=ThisInfoVector[ThisInfoVectorIndex + PrevChunkFilledTillRef]; ThisInfoVectorIndex++; referencePanel.ReadBlockHeader(line, tempBlock); referencePanel.ReadThisBlock(RefFileStream, blockIndex, tempBlock); if(blockIndex>=StartNextBlock) { // assert(ThisChunkFilledTillRef < MaxInfoVectorSize); ThisChunkFilledTillRef++; } else { ThisChunkStartFromRef++; } } PrevChunkFilledTillRef=ThisChunkFilledTillRef; PrevChunkStartFromRef=ThisChunkStartFromRef; TimeToRead+=( time(0) - time_prev); } void Estimation::readVcfFileChunk(int ChunkNo, HaplotypeSet &ThisTargetPanel) { int time_prev = time(0); cout << " Reading chunk from target/GWAS panel ... "<=StartNextPos) { // assert( (ThisChunkStartTillTar) < MaxGwasMarkerSize); ThisChunkStartTillTar++; } else { ThisChunkStartFromTar++; } // assert(overlapImportIndexmyOutFormat.TypedOnly) { // assert( (GWASnumtoBeWrittenRecords + PrevChunkFilledTillTarOnly) < MaxTypedOnlyMarkerSize); variant tempVar=targetPanel.TypedOnlyVariantList[MainTypedOnlyImportIndex]; ThisTargetPanel.TypedOnlyVariantList[GWASnumtoBeWrittenRecords + PrevChunkFilledTillTarOnly]=tempVar; int haplotype_index = 0; for (int i = 0; i<(targetPanel.numSamples); i++) { //haplotype_index=(2*i); if(targetPanel.SampleNoHaplotypes[i]!=record.getNumGTs(i)) { cout << "\n ERROR !!! GWAS Sample "<< targetPanel.individualName[i]<<" changes its ploidy at variant "; cout << tempVar.name <=TypedOnlyNextStartPos) { // assert( (ThisChunkStartTillTarOnly) < MaxTypedOnlyMarkerSize); ThisChunkStartTillTarOnly++; } else { ThisChunkStartFromTarOnly++; } // assert(MainTypedOnlyImportIndexmyOutFormat.gzip; m3vcfPrintStringPointer = (char*)malloc(sizeof(char) * (MyAllVariables->myOutFormat.PrintBuffer)); m3vcfpartial = ifopen(MyAllVariables->myOutFormat.OutPrefix + ".m3vcf" + (gzip ? ".gz" : ""), "wb", gzip ?InputFile::BGZF:InputFile::UNCOMPRESSED); if(m3vcfpartial==NULL) { cout <<"\n\n ERROR !!! \n Could NOT create the following file : "<< MyAllVariables->myOutFormat.OutPrefix + ".m3vcf" + (gzip ? ".gz" : "") <tm_year + 1900),(now->tm_mon + 1) ,now->tm_mday); ifprintf(m3vcfpartial,"##source=Minimac4.v%s\n",VERSION); ifprintf(m3vcfpartial,"##contig=\n",referencePanel.finChromosome.c_str()); ifprintf(m3vcfpartial,"##INFO=\n"); ifprintf(m3vcfpartial,"##INFO=\n"); ifprintf(m3vcfpartial,"##minimac4_Command=%s\n",MyAllVariables->myOutFormat.CommandLine.c_str()); ifprintf(m3vcfpartial,"#CHROM\tPOS\tID\tREF\tALT\tQUAL\tFILTER\tINFO\tFORMAT"); for(int Id=0;IdmyOutFormat.PrintBuffer)); recfile = ifopen(MyAllVariables->myOutFormat.OutPrefix + ".rec", "wb"); if(recfile==NULL) { cout <<"\n\n ERROR !!! \n Could NOT create the following file : "<< MyAllVariables->myOutFormat.OutPrefix + ".rec" <myOutFormat.hapOutput && !MyAllVariables->myOutFormat.unphasedOutput) { ifclose(hapdose); } if(MyAllVariables->myOutFormat.vcfOutput) { ifclose(vcfdosepartial); } if(MyAllVariables->myOutFormat.meta) { ifclose(vcfLoodosepartial); } if(MyAllVariables->myOutFormat.doseOutput) { ifclose(dosages); } ifclose(RefFileStream); TarFileStream.close(); cout<<" ------------------------------------------------------------------------------"<1073741824) { Fact=1073741824; Tag="Gb"; } else if(Total>1048576) { Fact=1048576; Tag="Mb"; } else if(Total>1024) { Fact=1024; Tag="Kbytes"; } else { Fact=1; Tag="Bytes"; } printf("\n Memory occupied by Full Reference Panel ~ %.3f %s", (double) RefMem/(Fact),Tag.c_str()); printf("\n Memory occupied by Compressed Reference Panel ~ %.3f %s", (double) ComRefMem/(Fact),Tag.c_str()); printf("\n Memory occupied by Target/GWAS Panel ~ %.3f %s", (double) TarMem/(Fact),Tag.c_str()); printf("\n Memory occupied by Likelihood Matrices ~ %.3f %s", (double) ProbMem/(Fact),Tag.c_str()); printf("\n Memory occupied by Dosage Data ~ %.3f %s", (double) DosageMem/(Fact),Tag.c_str()); printf("\n TOTAL Memory by the process ~ %.3f %s", (double) (Total)/(Fact),Tag.c_str()); cout<myOutFormat.gzip; cout<myOutFormat.OutPrefix + ".info" <myOutFormat.hapOutput && !MyAllVariables->myOutFormat.unphasedOutput) { ifclose(hapdose); cout<<" Haplotype Dosage information written to : "<myOutFormat.OutPrefix + ".hapDose" + (gzip ? ".gz" : "")<myOutFormat.vcfOutput) { ifclose(vcfdosepartial); free(VcfPrintStringPointer); cout<<" Imputed VCF information written to : "<< MyAllVariables->myOutFormat.OutPrefix + ".dose.vcf" + (gzip ? ".gz" : "")<myOutFormat.meta) { ifclose(vcfLoodosepartial); cout<<" Empirical Dosage VCF written to : "<< MyAllVariables->myOutFormat.OutPrefix + ".empiricalDose.vcf" + (gzip ? ".gz" : "")<myOutFormat.doseOutput) { ifclose(dosages); cout<<" Dosage information written to : "<< MyAllVariables->myOutFormat.OutPrefix + ".dose" + (gzip ? ".gz" : "")<myHapDataVariables.CHR!="") { while(referencePanel.VariantList[i].bp < MyAllVariables->myHapDataVariables.start) { i++; } } } else { while(referencePanel.VariantList[i].bp < MyChunks[ChunkNo][1]) { i++; } } ThisRefPanel.PrintStartIndex=i-RefStartPos; if(ChunkNo==(noChunks-1)) { if(MyAllVariables->myHapDataVariables.CHR!="") { for(; i <= RefEndPos; i++) if(referencePanel.VariantList[i].bp > MyAllVariables->myHapDataVariables.end) break; } else i=RefEndPos+1; } else { for(; i <= RefEndPos; i++) if(referencePanel.VariantList[i].bp > MyChunks[ChunkNo][2]) break; } ThisRefPanel.PrintEndIndex=i-RefStartPos-1; // assert(ThisRefPanel.PrintStartIndex < ThisRefPanel.numMarkers); // assert(ThisRefPanel.PrintEndIndex < ThisRefPanel.numMarkers); } void Estimation::GetCurrentPanelReady(int ChunkNo, HaplotypeSet &ThisRefPanel, Imputation &thisDataFast) { int RefStartPos = MyRefVariantNumber[ChunkNo][0]; int RefEndPos = MyRefVariantNumber[ChunkNo][1]; int RefStartInfo = MyChunksInfoNumber[ChunkNo][0]; int RefEndInfo = MyChunksInfoNumber[ChunkNo][1]; int NoRefMarkers = RefEndPos - RefStartPos + 1; // initialize typical variants ThisRefPanel.numMarkers=NoRefMarkers; ThisRefPanel.NoBlocks = MyChunksInfoNumber[ChunkNo][2]; int i; // create new start and end indices for RefInfo { ThisRefPanel.ReducedStructureInfo[0].startIndex = 0; for(i=RefStartInfo; i &Mapper = ThisRefPanel.MarkerToReducedInfoMapper; int j; for(i=0;imyOutFormat.verbose) ThisRefPanel.VariantList[i-RefStartPos]=referencePanel.VariantList[i]; // ThisTarPanel.missing[i-RefStartPos]=targetPanel.missing[i]; if(referencePanel.Recom.size()>0) { if (i < RefEndPos) ThisRefPanel.Recom[i - RefStartPos] = referencePanel.Recom[i]; ThisRefPanel.Error[i - RefStartPos] = referencePanel.Error[i]; } } } ThisRefPanel.CalculateAlleleFreq(); int time_prev = time(0); for(int i=0;imyModelVariables.cpus;i++) { thisDataFast.MainMarkovModel[i].AssignPanels(ThisRefPanel,MyAllVariables); thisDataFast.MainMarkovModel[i].initializeMatricesMinimac3(); } } void Estimation::InitializeRefFileStream(String &Reffilename) { RefFileStream = ifopen(Reffilename, "r"); string line; RefFileStream->readLine(line); bool Header=true; while(Header) { line.clear(); RefFileStream->readLine(line); if(line.substr(0,6).compare("#CHROM")==0) break; } for(int tempIndex=0;tempIndexdiscardLine(); PrevChunkFilledTillRef=0; PrevChunkStartFromRef=0; PrevChunkFilledTillTar=0; PrevChunkStartFromTar=0; PrevChunkFilledTillTarOnly=0; PrevChunkStartFromTarOnly=0; MaxGwasMarkerSize=MaxRefMarkerSize; InitializeRefChunkData(CurrentRefPanel); InitializeRefChunkData(CurrentRefPanelLoo); InitializeTargetLooChunkData(CurrentTarPanelLoo); //InitializeRefChipOnlyChunkData(CurrentRefPanelChipOnly); // stats.PreInitialize(MaxRefMarkerSize); // if(MyAllVariables->myOutFormat.memUsage) // { // RefMem = CurrentRefPanel.size(); // ComRefMem = CurrentRefPanelChipOnly.size(); // } } void Estimation::InitializeTargetFileStream(String &Tarfilename) { VcfHeader header; TarFileStream.open(Tarfilename, header); TarFileStream.setSiteOnly(false); FileReadIndex=0; overlapImportIndex=0; importReadIndex=0; GWASOnlySkipIndexpoint = 0; MainTypedOnlyImportIndex =0; InitializeTargetChipOnlyChunkData(CurrentTarPanelChipOnly); // if(MyAllVariables->myOutFormat.memUsage) // { // TarMem = CurrentTarPanelChipOnly.size(); // } } String Estimation::RunEstimation(String &Reffilename, String &Recomfilename, String &Errorfilename) { // int time_prev=time(0); // if (!targetPanel.ScaffoldGWAStoReference(referencePanel,*MyAllVariables)) // { // cout << "\n Program Exiting ... \n\n"; // return "Reference.Panel.Load.Error"; // } // // cout<<"\n ------------------------------------------------------------------------------"<myOutFormat.memUsage) // { // cout<<" ------------------------------------------------------------------------------"<myModelVariables.cpus); // // if(MyAllVariables->myOutFormat.vcfBuffer >= targetPanel.numSamples) // MyAllVariables->myOutFormat.vcfBuffer=targetPanel.numSamples; // // thisDataFast.InitializeOutputFiles(targetPanel, MyAllVariables->myOutFormat.vcfBuffer, MaxRefMarkerSize, MaxGwasMarkerSize); // if(MyAllVariables->myOutFormat.memUsage) // { // // cout<<" Estimating Memory based on a single chunk ..."<< endl; // // readm3vcfFileChunk(0, CurrentRefPanel); // readVcfFileChunk(0, CurrentTarPanelChipOnly); // GetCurrentPanelReady(0, CurrentRefPanel, CurrentRefPanelChipOnly, CurrentTarPanelChipOnly, thisDataFast); // cout<myOutFormat.meta) // AppendtoMainLooVcfFaster(i,thisDataFast.TotalNovcfParts); // PrintInfoFile(i); // // time_load = time(0) - time_prev; // cout << "\n Time taken for this chunk = " << time_load << " seconds."<myHapDataVariables.end==0 && MyAllVariables->myOutFormat.TypedOnly) //// assert(FileReadIndex==targetPanel.importIndexListSize); //// asserassertt(OverCount==targetPanel.numOverlapMarkers); //// assert(TypOnlyCount==targetPanel.numTypedOnlyMarkers); //// assert(RefCOUNT==referencePanel.NoBlocks); // // CloseStreamOutputFiles(); return "Success"; } String Estimation::AnalyzeExperiment(String &Reffilename, String &Tarfilename, String &Recomfilename, String &Errorfilename, AllVariable& MyAllVariable) { String mysuccessresult="Error"; cout << " Starting Main Imputation Estimation ... " << endl; cout << "\n Performing preliminary check on input parameters... " ; MyOutFormat=&MyAllVariable.myOutFormat; MyModelVariables=&MyAllVariable.myModelVariables; MyHapDataVariables=&MyAllVariable.myHapDataVariables; MyAllVariables=&MyAllVariable; int time_prev=time(0); mysuccessresult=CheckValidity(Reffilename, Tarfilename, Recomfilename, Errorfilename); TimeToRead+=( time(0) - time_prev); if(mysuccessresult!="Success") return mysuccessresult; // if(!MyModelVariables->processReference) // { // mysuccessresult=RunEstimation(Reffilename, Tarfilename, Recomfilename, Errorfilename); // } // else // { // mysuccessresult=RunEstimation(Reffilename, Recomfilename, Errorfilename); // } if(mysuccessresult!="Success") return mysuccessresult; return "Success"; } String Estimation::CheckValidity(String &Reffilename, String &Tarfilename, String &Recomfilename, String &Errorfilename) { cout<myModelVariables.CheckValidity()) { return "Command.Line.Error"; } if(!MyAllVariables->myHapDataVariables.CheckValidity()) { return "Command.Line.Error"; } if(!MyAllVariables->myOutFormat.CheckValidity()) { return "Command.Line.Error"; } // if(MyAllVariables->myOutFormat.verbose) // { // MyAllVariables->myHapDataVariables.ChunkLengthMb=299; // } if(!MyAllVariables->myModelVariables.processReference) { if (Tarfilename == "") { cout <<" ERROR !!! \n Missing \"--haps\", a required parameter (for imputation).\n"; cout <<" OR use \"--processReference\" to just process the reference panel.\n"; cout << "\n Program Exiting ... \n\n"; return "Command.Line.Error"; } } else { cout << "\n ERROR !!! The current version of Minimac4 does NOT support \"--processReference\" "<myModelVariables.processReference) { if (!targetPanel.BasicCheckForTargetHaplotypes(Tarfilename, "GWAS", *MyAllVariables)) { return "Target.Panel.Load.Error"; } } else { if (!referencePanel.BasicCheckForVCFReferenceHaplotypes(Reffilename, "Reference", *MyAllVariables)) { return "Reference.Panel.Load.Error"; } } return "Success"; } void Estimation::InitializeRefChunkData(HaplotypeSet &ThisRefPanel) { int NoRefHaps=referencePanel.numHaplotypes; ThisRefPanel.numHaplotypes=NoRefHaps; ThisRefPanel.numSamples=referencePanel.numSamples; ThisRefPanel.SampleNoHaplotypes=referencePanel.SampleNoHaplotypes; ThisRefPanel.CummulativeSampleNoHaplotypes=referencePanel.CummulativeSampleNoHaplotypes; ThisRefPanel.individualName=referencePanel.individualName; ThisRefPanel.maxBlockSize=referencePanel.maxBlockSize; ThisRefPanel.maxRepSize=referencePanel.maxRepSize; ThisRefPanel.ReducedStructureInfo.resize(MaxInfoVectorSize); ThisRefPanel.MyAllVariables=MyAllVariables; ThisRefPanel.MapRefToTar.resize(MaxRefMarkerSize); ThisRefPanel.MapTarToRef.resize(MaxRefMarkerSize); int Mem=0; for(int i=0;imyOutFormat.verbose) { ThisRefPanel.VariantList.resize(MaxRefMarkerSize); } } void Estimation::InitializeRefChipOnlyChunkData(HaplotypeSet &ThisRefPanel) { int NoRefHaps=referencePanel.numHaplotypes; ThisRefPanel.numHaplotypes=NoRefHaps; ThisRefPanel.numSamples=referencePanel.numSamples; ThisRefPanel.MarkerToReducedInfoMapper.resize(MaxGwasMarkerSize); ThisRefPanel.Recom.resize(MaxGwasMarkerSize); ThisRefPanel.Error.resize(MaxGwasMarkerSize); ThisRefPanel.AlleleFreq.resize(MaxGwasMarkerSize); ThisRefPanel.MyAllVariables=MyAllVariables; if(MyAllVariables->myOutFormat.verbose) { ThisRefPanel.individualName=referencePanel.individualName; ThisRefPanel.SampleNoHaplotypes=referencePanel.SampleNoHaplotypes; ThisRefPanel.VariantList.resize(MaxGwasMarkerSize); } } void Estimation::InitializeTargetLooChunkData(HaplotypeSet &ThisTarPanel) { int tempnumHaplotypes=targetPanel.numHaplotypes; ThisTarPanel.MyAllVariables=MyAllVariables; ThisTarPanel.numHaplotypes=1; ThisTarPanel.numSamples=1; ThisTarPanel.haplotypesUnscaffolded.resize(1); ThisTarPanel.MissingSampleUnscaffolded.resize(1); for (int i = 0; imyOutFormat.TypedOnly) { ThisTarPanel.GWASOnlyhaplotypesUnscaffolded.resize(tempnumHaplotypes); ThisTarPanel.GWASOnlyMissingSampleUnscaffolded.resize(tempnumHaplotypes); } for (int i = 0; imyOutFormat.TypedOnly) { ThisTarPanel.TypedOnlyVariantList.resize(MaxTypedOnlyMarkerSize); ThisTarPanel.GWASOnlyhaplotypesUnscaffolded[i].resize(MaxTypedOnlyMarkerSize, false); ThisTarPanel.GWASOnlyMissingSampleUnscaffolded[i].resize(MaxTypedOnlyMarkerSize, false); } } ThisTarPanel.GWASOnlyAlleleFreq.resize(MaxTypedOnlyMarkerSize); ThisTarPanel.FlankRegionStart.resize(MaxGwasMarkerSize); ThisTarPanel.FlankRegionEnd.resize(MaxGwasMarkerSize); } void Estimation::InitializeChunkVariables() { int i; MyChunks.resize(noChunks); MyChunksInfoNumber.resize(noChunks+1); // extra element added just to reduce checks later on MyRefVariantNumber.resize(noChunks+1); // extra element added just to reduce checks later on MyTargetVariantNumber.resize(noChunks+1); // extra element added just to reduce checks later on MyTypdedOnlyVariantNumber.resize(noChunks+1); // extra element added just to reduce checks later on MyRatio.resize(noChunks+1,-1.0); // extra element added just to reduce checks later on for(i=0;i<(noChunks);i++) { MyChunks[i].resize(4); MyChunksInfoNumber[i].resize(3); MyRefVariantNumber[i].resize(3); MyTargetVariantNumber[i].resize(3,-3); MyTypdedOnlyVariantNumber[i].resize(3,-3); } MyChunksInfoNumber[i].resize(1,99999999); // extra element added just to reduce checks later on MyRefVariantNumber[i].resize(1,99999999); // extra element added just to reduce checks later on MyTargetVariantNumber[i].resize(1,99999999); // extra element added just to reduce checks later on MyTypdedOnlyVariantNumber[i].resize(1,99999999); // extra element added just to reduce checks later on } void Estimation::CreateChunksFromReference() { vector &RefInfo=referencePanel.ReducedStructureInfoSummary; vector &VarList=referencePanel.VariantList; vector &InfoMapper=referencePanel.MarkerToReducedInfoMapper; int NoMarkers=referencePanel.numMarkers; int i=0,index; MyChunksInfoNumber[0][0]=0; MyRefVariantNumber[0][0]=0; MyChunks[0][0]=VarList[0].bp; MyChunks[0][1]=VarList[0].bp; if(noChunks>1) { MyChunksInfoNumber[0][1]=InfoMapper[0 + MyHapDataVariables->ChunkSize + MyHapDataVariables->ChunkWindow]; MyRefVariantNumber[0][1]= RefInfo[MyChunksInfoNumber[0][1]].endIndex ; MyChunks[0][2]=VarList[0 + MyHapDataVariables->ChunkSize].bp; MyChunks[0][3]=VarList[MyRefVariantNumber[0][1]].bp; for(i=1;i<(noChunks-1);i++) { index=(i*MyHapDataVariables->ChunkSize); MyChunksInfoNumber[i][0]=InfoMapper[index-MyHapDataVariables->ChunkWindow]; MyChunksInfoNumber[i][1]=InfoMapper[index+MyHapDataVariables->ChunkSize+MyHapDataVariables->ChunkWindow]; MyRefVariantNumber[i][0]=RefInfo[MyChunksInfoNumber[i][0]].startIndex; MyRefVariantNumber[i][1]= RefInfo[MyChunksInfoNumber[i][1]].endIndex; MyChunks[i][0]=VarList[MyRefVariantNumber[i][0]].bp; MyChunks[i][1]=MyChunks[i-1][2]+1; MyChunks[i][2]=VarList[index+MyHapDataVariables->ChunkSize].bp; MyChunks[i][3]=VarList[MyRefVariantNumber[i][1]].bp; } index=(i*MyHapDataVariables->ChunkSize); MyChunksInfoNumber[i][0]=InfoMapper[index-MyHapDataVariables->ChunkWindow]; MyRefVariantNumber[i][0]=RefInfo[MyChunksInfoNumber[i][0]].startIndex; MyChunks[i][0]=VarList[MyRefVariantNumber[i][0]].bp; MyChunks[i][1]=MyChunks[i-1][2]+1; } MyChunks[i][2]=VarList[NoMarkers-1].bp; MyChunks[i][3]=VarList[NoMarkers-1].bp; MyChunksInfoNumber[i][1]=InfoMapper[NoMarkers-1]; MyRefVariantNumber[i][1]=NoMarkers-1; for(int i=0;i &VarList=referencePanel.VariantList; int NoMarkers=referencePanel.numMarkers; int index; MyRefVariantNumber[0][0]=0; MyChunks[0][0]=VarList[0].bp; MyChunks[0][1]=VarList[0].bp; i=0; if(noChunks>1) { MyChunks[0][2]=VarList[0 + MyHapDataVariables->ChunkSize].bp; MyChunks[0][3]=VarList[0 + MyHapDataVariables->ChunkSize + MyHapDataVariables->ChunkWindow].bp; MyRefVariantNumber[0][1]=MyHapDataVariables->ChunkSize + MyHapDataVariables->ChunkWindow; for(i=1;i<(noChunks-1);i++) { index=(i*MyHapDataVariables->ChunkSize); MyRefVariantNumber[i][0]=index-MyHapDataVariables->ChunkWindow; MyChunks[i][0]=VarList[index-MyHapDataVariables->ChunkWindow].bp; MyChunks[i][1]=MyChunks[i-1][2]+1; MyChunks[i][2]=VarList[index+MyHapDataVariables->ChunkSize].bp; MyChunks[i][3]=VarList[index+MyHapDataVariables->ChunkSize+MyHapDataVariables->ChunkWindow].bp; MyRefVariantNumber[i][1]= index+MyHapDataVariables->ChunkSize+MyHapDataVariables->ChunkWindow; } index=(i*MyHapDataVariables->ChunkSize); MyRefVariantNumber[i][0]=index-MyHapDataVariables->ChunkWindow; MyChunks[i][0]=VarList[index-MyHapDataVariables->ChunkWindow].bp; MyChunks[i][1]=MyChunks[i-1][2]+1; } MyChunks[i][2]=VarList[NoMarkers-1].bp; MyChunks[i][3]=VarList[NoMarkers-1].bp; MyRefVariantNumber[i][1]=NoMarkers-1; for(int i=0;i0) { while(i MyTargetVariantNumber[i][0]? MyTargetVariantNumber[i][1] + 1 - MyTargetVariantNumber[i][0]: 0 ); MyTypdedOnlyVariantNumber[i][2] = ( MyTypdedOnlyVariantNumber[i][1] + 1 >MyTypdedOnlyVariantNumber[i][0]? MyTypdedOnlyVariantNumber[i][1] + 1 - MyTypdedOnlyVariantNumber[i][0]: 0 ); } } bool Estimation::CheckChunkValidityandPrintChunkForEstimation() { int MinRefMarkerSize=MyRefVariantNumber[0][2], InIndex=0; MaxInfoVectorSize=0; MaxRefMarkerSize=0; cout<<" No LeftBuffer LeftEnd RightPoint RightBuffer #Sites"< MaxInfoVectorSize ) MaxInfoVectorSize = MyChunksInfoNumber[i][2]; if( MyRefVariantNumber[i][2] > MaxRefMarkerSize ) MaxRefMarkerSize = MyRefVariantNumber[i][2]; if( MyRefVariantNumber[i][2] < MinRefMarkerSize ) { InIndex=i; MinRefMarkerSize = MyRefVariantNumber[i][2]; } cout< MaxRefMarkerSize ) MaxRefMarkerSize = MyRefVariantNumber[i][2]; if( MyRefVariantNumber[i][2] < MinRefMarkerSize ) { InIndex=i; MinRefMarkerSize = MyRefVariantNumber[i][2]; } cout<ChunkSize <<" variants in each chunk ... " << endl<ChunkSize <<" variants in each chunk ... " << endl<myHapDataVariables.ChunkOverlapMb)); if(noOverLaps==0) noOverLaps=1; MyHapDataVariables->ChunkWindow=(NoMarkers/noOverLaps); noChunks = ((int)(EndPos-StartPos)/(int)(1000000 *MyAllVariables->myHapDataVariables.ChunkLengthMb)); if(noChunks==0) noChunks=1; MyHapDataVariables->ChunkSize=(NoMarkers/noChunks); return; } Minimac4-1.0.2/src/Estimation.h000066400000000000000000000130401353222426400162300ustar00rootroot00000000000000#ifndef MINIMAC4_ESTIMATION_H #define MINIMAC4_ESTIMATION_H #if defined(_OPENMP) #include #endif #include "MyVariables.h" #include "Unique.h" #include "Imputation.h" #include "HaplotypeSet.h" #include using namespace std; class Estimation { public: // Basic Variables HaplotypeSet targetPanel,referencePanel; IFILE RefFileStream; VcfFileReader TarFileStream; VcfRecord record; // Swapping Variables for actual chunk IMPUTATION HaplotypeSet CurrentTarPanel, CurrentRefPanel, CurrentRefPanelLoo, CurrentTarPanelLoo; HaplotypeSet CurrentTarPanelChipOnly,CurrentRefPanelChipOnly; int PrevChunkFilledTillRef, PrevChunkStartFromRef; int PrevChunkFilledTillTar, PrevChunkStartFromTar; int PrevChunkFilledTillTarOnly, PrevChunkStartFromTarOnly; void InitializeTargetChipOnlyChunkData(HaplotypeSet &ThisTarPanel); void InitializeRefChipOnlyChunkData(HaplotypeSet &ThisRefPanel); void readm3vcfFileChunk(int ChunkNo, HaplotypeSet &ThisRefPanel); void readVcfFileChunk(int ChunkNo, HaplotypeSet &ThisTargetPanel); // Target PANEL Indexing Variables int overlapImportIndex, importReadIndex, FileReadIndex; int GWASOnlySkipIndexpoint , MainTypedOnlyImportIndex; // Output File Handle Streams IFILE dosages, hapdose, haps, vcfdosepartial, vcfLoodosepartial, info; IFILE m3vcfpartial, recfile, errfile ; ImputationStatistics stats; // Chunk Information int noChunks; vector< vector > MyChunks,MyChunksInfoNumber; vector< vector > MyRefVariantNumber, MyTargetVariantNumber, MyTypdedOnlyVariantNumber; vector< float > MyRatio; int MaxInfoVectorSize, MaxGwasMarkerSize, MaxRefMarkerSize, MaxTypedOnlyMarkerSize; // Temporary Variables to be deleted later for checking purposes. int OverCount, TypOnlyCount, RefCOUNT; // Time Variables int TimeToCompress, TimeToRead, TimeToImpute, TimeToWrite; // Memory Variables double RefMem, TarMem, ComRefMem, DosageMem, ProbMem; // Printing Text Variables char *VcfPrintStringPointer, *LooVcfPrintStringPointer, *InfoPrintStringPointer, *DosePrintStringPointer; char *m3vcfPrintStringPointer, *recPrintStringPointer, *errPrintStringPointer; int VcfPrintStringLength, InfoPrintStringLength, DosePrintStringLength; int m3vcfPrintStringLength, recPrintStringLength, errPrintStringLength; vector InfoforChunk; vector< vector > BPListMapper; HaplotypeSet *CurrentChunk, *NextChunk; HaplotypeSet MainReferenceFrame; OutputFormatVariable *MyOutFormat; ModelVariable *MyModelVariables; HaplotypeDataVariables *MyHapDataVariables; AllVariable *MyAllVariables; void PrintInfoFile(int ChunkNo); Estimation() { TimeToCompress=0; TimeToRead=0; TimeToImpute=0; TimeToWrite=0; RefMem =0.0; TarMem =0.0; ComRefMem =0.0; DosageMem =0.0; ProbMem = 0.0; } void AppendtoMainVcf(int ChunkNo, int MaxIndex); void AppendtoMainLooVcfFaster(int ChunkNo, int MaxIndex); void AppendtoMainVcfFaster(int ChunkNo, int MaxIndex); void MemDisplay(); void GetNumChunks(); String RunEstimation(String &Reffilename, String &Recomfilename, String &Errorfilename, AllVariable& MyAllVariable); String RunEstimation(String &Reffilename, String &Recomfilename, String &Errorfilename); String AnalyzeExperiment(String &Reffilename, String &Tarfilename, String &Recomfilename,String &Errorfilename, AllVariable& MyAllVariable); String CheckValidity(String &Reffilename, String &Tarfilename, String &Recomfilename, String &Errorfilename); String RunAnalysis(String &Reffilename, String &Tarfilename, String &Recomfilename, String &Errorfilename); void readm3vcfFileChunk(HaplotypeSet &ThisRefPanel, HaplotypeSet &NextRefPanel, int StartBlock, int EndBlock, int StartNextBlock); void readVcfFileChunk(HaplotypeSet &ThisTargetPanel, HaplotypeSet &NextTargetPanel, int StartPos, int EndPos, int StartNextPos, int ChunkNo); bool OpenStreamOutputFiles(); void CloseStreamOutputFiles(); void InitializeRefFileStream(String &Reffilename); void InitializeTargetFileStream(String &Tarfilename); void InitializeRefChunkData(HaplotypeSet &ThisRefPanel); void InitializeTargetChunkData(HaplotypeSet &ThisTarPanel); bool CheckChunkValidityandPrintChunkForEstimation(); bool CreateChunks(); bool CreateChunksForParamEstimation(); void InitializeChunkVariables(); void CreateChunksFromReference(); void CreateChunksFromVCFReference(); void ImportChunksToTarget(); bool CheckChunkValidityandPrintChunk(); bool CheckChunkValidityForParamEstimationandPrintChunk(); void InitializeTargetLooChunkData(HaplotypeSet &ThisTarPanel); void CreatePrintIndices(int ChunkNo, HaplotypeSet &ThisRefPanel); void GetCurrentPanelReady(int ChunkNo, HaplotypeSet &ThisRefPanel, Imputation &thisDataFast); }; #endif //MINIMAC4_ESTIMATION_H Minimac4-1.0.2/src/HaplotypeSet.cpp000066400000000000000000002170531353222426400171020ustar00rootroot00000000000000#include "HaplotypeSet.h" #include "assert.h" #define ALT_DELIM ',' #define MONOMORPH_INDICATOR '-' #include "STLUtilities.h" void HaplotypeSet::UncompressTypedSitesNew(HaplotypeSet &rHap,HaplotypeSet &tHap,int ChunkNo) { // outFile=MyAllVariables->myOutFormat.OutPrefix; vcfType=false; int CPU=1; int blockSize = 500; int bufferSize = 5000; vector CompHaplotypes(CPU); int currentPiece=0; for(currentPiece=0;currentPiece BufferPosList(CPU); BufferPosList[0]=1; for(int BufferNo=1;BufferNo &RhapInfo=rHap.ReducedStructureInfo; // assert(numMarkers==tHap.numMarkers); for(int ThisPanelIndex=0; ThisPanelIndexmyOutFormat.verbose) { VariantList[ThisPanelIndex]=rHap.VariantList[RefmarkerIndex]; } CompHaplotypes[currentPiece].Push(j,ThisMarkerIndex); int NewPiece=CPU; if (CompHaplotypes[currentPiece].Length == bufferSize) { NewPiece=(currentPiece+1)%CPU; vector tempHaplotypes(numHaplotypes); if(NewPiece!=0) { int temp=CompHaplotypes[currentPiece].ReducedInfoMapper[bufferSize-1]; int temp2=CompHaplotypes[currentPiece].ReducedInfoVariantMapper[bufferSize-1]; CompHaplotypes[NewPiece].Clear(); CompHaplotypes[NewPiece].Push(temp,temp2); currentPiece=NewPiece; } } if(NewPiece==0 || ThisPanelIndex==(numMarkers-1)) { #pragma omp parallel for for(int ThisPiece=0;ThisPiece<=currentPiece;ThisPiece++) { int LastflushPos=BufferPosList[ThisPiece]-1; vector index(numHaplotypes),oldIndex; vector previousDifference(numHaplotypes); vector previousPredecessor(numHaplotypes); vector firstDifference(numHaplotypes-1,0); vector cost(bufferSize+1,0); vector bestSlice(bufferSize+1,0); vector bestComplexity(bufferSize+1,0); vector > bestIndex(bufferSize+1); ReducedStructureInfoBuffer[ThisPiece].clear(); findUnique RefUnique; RefUnique.updateCoeffs(MyAllVariables->myModelVariables.transFactor,MyAllVariables->myModelVariables.cisFactor); double blockedCost = 0.0; for(int i=0;i offsets(3,0); for (int i = 0; i < numHaplotypes; i++) { offsets[CompHaplotypes[ThisPiece].GetVal(i) - '0' + 1]++; } offsets[2]+=offsets[1]; oldIndex = index; for (int i = 0; i < numHaplotypes; i++) { index[offsets[CompHaplotypes[ThisPiece].GetVal(oldIndex[i],length - 1) - '0']++] = oldIndex[i]; } RefUnique.UpdateDeltaMatrix(CompHaplotypes[ThisPiece], index, firstDifference, length, blockSize, oldIndex, previousPredecessor, previousDifference); RefUnique.AnalyzeBlocks(index, firstDifference, length, blockSize, cost, bestSlice, bestComplexity, bestIndex); } if(CompHaplotypes[ThisPiece].Length>1) blockedCost += RefUnique.FlushBlocks(ReducedStructureInfoBuffer[ThisPiece], LastflushPos, CompHaplotypes[ThisPiece], cost, bestComplexity, bestSlice, bestIndex); } NoMarkersWritten+=(CPU*(bufferSize-1)); BufferPosList[0]=NoMarkersWritten; for(int BufferNo=1;BufferNomyOutFormat.verbose) { stringstream strs; strs<<(ChunkNo+1); string ss=(string)MyAllVariables->myOutFormat.OutPrefix+".chunk."+(string)(strs.str())+".GWAS"; String tempString(ss.c_str()); writem3vcfFile( tempString, MyAllVariables->myOutFormat.gzip); } } void HaplotypeSet::CreateScaffoldedParameters(HaplotypeSet &rHap) { for(int i=0;i0) { int index=rHap.MapTarToRef[i-1]; double temp=1.0; while(index 9) { tempString = string(pch); if(tempString.find('|')==string::npos) SampleNoHaplotypes[sampleCount]=1; else SampleNoHaplotypes[sampleCount]=2; sampleCount++; } pch = strtok_r (NULL,"\t", &end_str1); } for (int i = 1; i < numSamples; i++) CummulativeSampleNoHaplotypes[i] += CummulativeSampleNoHaplotypes[i - 1] + SampleNoHaplotypes[i - 1]; numHaplotypes = CummulativeSampleNoHaplotypes.back()+SampleNoHaplotypes.back(); } void HaplotypeSet::getm3VCFSampleNames(string &line) { individualName.clear(); SampleNoHaplotypes.clear(); CummulativeSampleNoHaplotypes.clear(); numSamples=0; numHaplotypes=0; char * pch; char *end_str1; string tempString2,tempString,tempString3; int colCount=0; pch = strtok_r ((char*)line.c_str(),"\t", &end_str1); numHaplotypes=0; while(pch!=NULL) { colCount++; if(m3vcfVERSION==1 && colCount>9) { numHaplotypes++; tempString=string(pch); tempString3=tempString.substr(tempString.size()-1,tempString.size()-1); tempString2=tempString.substr(0,tempString.size()-6); if(tempString3=="1") { numSamples++; individualName.push_back(tempString2); SampleNoHaplotypes.push_back(1); } else if(tempString3=="2") { SampleNoHaplotypes.back()=2; } else { cout<9) { numSamples++; tempString=string(pch); individualName.push_back(tempString); } pch = strtok_r (NULL,"\t", &end_str1); } if(m3vcfVERSION==1) { CummulativeSampleNoHaplotypes.resize(numSamples, 0); for (int i = 1; i < numSamples; i++) CummulativeSampleNoHaplotypes[i] += CummulativeSampleNoHaplotypes[i - 1] + SampleNoHaplotypes[i - 1]; } } void HaplotypeSet::UpdateParameterList() { MyOutFormat=&(MyAllVariables->myOutFormat); MyModelVariables=&(MyAllVariables->myModelVariables); MyHapDataVariables=&(MyAllVariables->myHapDataVariables); } bool HaplotypeSet::ReadBlockHeaderSummary(string &line, ReducedHaplotypeInfoSummary &tempBlocktoCheck) { const char* tabSep="\t"; vector BlockPieces(numHaplotypes+9); MyTokenize(BlockPieces, line.c_str(), tabSep, 9); tempBlocktoCheck.BlockSize=GetNumVariants(BlockPieces[7]); tempBlocktoCheck.RepSize=GetNumReps(BlockPieces[7]); if(CheckBlockPosFlag(line, MyHapDataVariables->CHR, MyHapDataVariables->START, MyHapDataVariables->END)==1) return true; return false; } void HaplotypeSet::GetVariantInfoFromBlock(IFILE m3vcfxStream, ReducedHaplotypeInfoSummary &tempBlock, int &NoMarkersImported) { string currID, rsID; string line; int blockEnterFlag=0; const char* tabSep="\t"; int NewBlockSizeCount=0; for(int tempIndex=0;tempIndexreadLine(line); MyTokenize(BlockPiecesforVarInfo, line.c_str(), tabSep,9); if(StartedThisPanel==false || tempIndex>0) { StartedThisPanel=true; currID=BlockPiecesforVarInfo[0]+":"+BlockPiecesforVarInfo[1]+":"+BlockPiecesforVarInfo[3]+":"+BlockPiecesforVarInfo[4]; rsID = BlockPiecesforVarInfo[2]; if(rsID==".") rsID=currID; variant tempVariant; tempVariant.assignValues(currID,rsID,BlockPiecesforVarInfo[0],atoi(BlockPiecesforVarInfo[1].c_str())); tempVariant.assignRefAlt(BlockPiecesforVarInfo[3],BlockPiecesforVarInfo[4]); VariantList.push_back(tempVariant); string Info=BlockPiecesforVarInfo[7]; double tempRecom=GetRecom(Info); double tempError=GetError(Info); if(MyAllVariables->myModelVariables.constantParam>0.0) { Recom.push_back(MyAllVariables->myModelVariables.constantParam); Error.push_back(0.00999); } else { if (tempRecom == -3.0 && MyAllVariables->myModelVariables.referenceEstimates) { cout << "\n ERROR !!! \n NO parameter estimates already found in M3VCF file !!!" << endl; cout << " Please remove handle \"--referenceEstimates\" to ignore this check " << endl; cout << " Else, use M3VCF file with parameter estimates " << endl; cout << "\n Program Exiting ... \n\n"; abort(); } Recom.push_back(tempRecom); Error.push_back(0.00999); } NewBlockSizeCount++; NoMarkersImported++; } if(blockEnterFlag==0) { tempBlock.startIndex=NoMarkersImported-1; blockEnterFlag=1; } tempBlock.endIndex=NoMarkersImported-1; } } void HaplotypeSet::reconstructHaplotype(vector &reHaplotypes,int &index) { int markerIndex=0,k; for(int j=0;j padded(rHap.numMarkers); rHap.reconstructHaplotype(padded,index); numMarkers=(int)padded.size(); haplotypesUnscaffolded[0]= padded; } bool HaplotypeSet::ReadBlockHeader(string &line, ReducedHaplotypeInfo &tempBlocktoCheck) { const char* tabSep="\t", *dashSep="|"; vector BlockPieces(numHaplotypes+9); MyTokenize(BlockPieces, line.c_str(), tabSep,numHaplotypes+9); tempBlocktoCheck.BlockSize=GetNumVariants(BlockPieces[7]); tempBlocktoCheck.RepSize=GetNumReps(BlockPieces[7]); if(CheckBlockPosFlag(line,MyHapDataVariables->CHR,MyHapDataVariables->START,MyHapDataVariables->END)==1) return true; fill(tempBlocktoCheck.uniqueCardinality.begin(), tempBlocktoCheck.uniqueCardinality.end(), 0); int index=0; if(m3vcfVERSION==1) { while (index < numHaplotypes) { int tempval = atoi(BlockPieces[index + 9].c_str()); tempBlocktoCheck.uniqueIndexMap[index] = tempval; tempBlocktoCheck.uniqueCardinality[tempval]++; index++; } } else if (m3vcfVERSION==2) { int haploIndex = 0; while (index < numSamples) { if(SampleNoHaplotypes[index]==2) { vector HaploPieces(2); MyTokenize(HaploPieces, BlockPieces[index + 9].c_str(), dashSep, 2); int tempval = atoi(HaploPieces[0].c_str()); tempBlocktoCheck.uniqueIndexMap[haploIndex++] = tempval; tempBlocktoCheck.uniqueCardinality[tempval]++; tempval = atoi(HaploPieces[1].c_str()); tempBlocktoCheck.uniqueIndexMap[haploIndex++] = tempval; tempBlocktoCheck.uniqueCardinality[tempval]++; } else { int tempval = atoi(BlockPieces[index + 9].c_str()); tempBlocktoCheck.uniqueIndexMap[haploIndex++] = tempval; tempBlocktoCheck.uniqueCardinality[tempval]++; } index++; } } for (int i = 0; i < tempBlocktoCheck.RepSize; i++) { tempBlocktoCheck.InvuniqueCardinality[i]=1.0/(float)tempBlocktoCheck.uniqueCardinality[i]; } return false; } void HaplotypeSet::GetTransUniqueHapsVERSION2(int index, ReducedHaplotypeInfo &tempBlock, string &tempString) { vector &TempHap = tempBlock.TransposedUniqueHaps[index]; fill(TempHap.begin(), TempHap.end(), '0'); vector AlternateAlleles; AlternateAlleles.clear(); int prevVal = 0; char *input=&tempString[0]; string word=""; while (*input) { if(*input==MONOMORPH_INDICATOR) { break; } if (*input==ALT_DELIM) { word.push_back('\0'); AlternateAlleles.push_back(prevVal+atoi(word.c_str())); prevVal=AlternateAlleles.back(); word.clear(); } else { word.push_back(*input); } input++; } if(word!="") { word.push_back('\0'); AlternateAlleles.push_back(prevVal+atoi(word.c_str())); } for(int i=0; i<(int)AlternateAlleles.size(); i++) { TempHap[AlternateAlleles[i]]='1'; } } void HaplotypeSet::ReadThisBlock(IFILE m3vcfxStream, int blockIndex, ReducedHaplotypeInfo &tempBlock) { string line; const char* tabSep="\t"; vector BlockPieces(9); for(int tempIndex=0;tempIndexreadLine(line); MyTokenize(BlockPieces, line.c_str(), tabSep,9); vector &TempHap = tempBlock.TransposedUniqueHaps[tempIndex]; string &tempString=BlockPieces[8]; if(m3vcfVERSION==1) { for (int index = 0; index < tempBlock.RepSize; index++) { char t = tempString[index]; TempHap[index] = (t); } } else if(m3vcfVERSION==2) { GetTransUniqueHapsVERSION2(tempIndex, tempBlock, tempString); } } } bool HaplotypeSet::BasicCheckForTargetHaplotypes(String &VCFFileName, String TypeofFile, AllVariable& MyAllVariable) { MyAllVariables=&MyAllVariable; std::cout << "\n Checking "<myModelVariables.rounds==0) { cout <<"\n NOTE: User has specified \"--rounds\" = 0 !!!\n"; cout<<" No parameter estimation will be done on VCF file.\n"; cout<<" Program will use default estimates leading to possibly inaccurate estimates."<0) { if(bp>MyAllVariable.myHapDataVariables.END || bp1) { notBiallelic++; flag = 1; } if (MyAllVariable.myHapDataVariables.passOnly && record.getFilter().getString(0).compare("PASS") != 0) { failFilter++; flag = 1; } } // Check ID for duplicate { stringstream strs3,strs4; strs3<<(cno); strs4<<(bp); currID=(string)strs3.str()+":"+(string)strs4.str()+":"+refAllele+":"+altAllele; if(id==".") id=currID; if(prevID==currID) { duplicates++; if(MyAllVariable.myOutFormat.verbose){cout << " WARNING !!! Duplicate Variant found chr:"<0) {cout<0){std::cout << " NOTE ! "<< outSideRegion<< " variants lie outside region [" <0){std::cout << " NOTE ! "<< duplicates<< " instance(s) of duplicated variants discarded ..." << endl;} if(notBiallelic>0){std::cout << " NOTE ! "<< notBiallelic<< " multi-allelic variant(s) discarded ..." << endl;} if(failFilter>0){std::cout << " NOTE ! "<< failFilter<< " variant(s) failed FILTER = PASS and were discarded ..." << endl;} if(inconsistent>0){std::cout << " NOTE ! "<< inconsistent<< " SNP(s) with inconsistent REF/ALT alleles discarded ..." << endl;} if(outSideRegion + duplicates + notBiallelic + failFilter + inconsistent>0) {cout< headerTag(2); string line; const char *equalSep="="; m3vcfVERSION=0; bool Header=true; while(Header) { line.clear(); m3vcfxStream->readLine(line); if(line.substr(0,2).compare("##")==0) Header=true; else break; MyTokenize(headerTag, line.c_str(), equalSep, 2); if(headerTag[0].compare("##n_blocks")==0) { NoBlocks=atoi(headerTag[1].c_str()); } if(m3vcfVERSION==0 && headerTag[0].compare("##fileformat")==0) { string tempVer = headerTag[1].substr(5,5).c_str(); if(tempVer.length()==0) m3vcfVERSION=1; else if (tempVer=="v2.0") m3vcfVERSION=2; else { cout << "\n ERROR !!! \n Invalid M3VCF Version : "<CHR!="") { std::cout << "\n Loading markers in region " << MyHapDataVariables->CHR<<":"<START<<"-"<END<<" ..."<< endl; } IFILE m3vcfxStream = ifopen(Reffilename, "r"); if(m3vcfxStream) { GetSummary(m3vcfxStream); if(numSamples==0) { cout << "\n ERROR !!! \n No samples found in M3VCF Input File : "<readLine(line)!=-1) { if(ReadHeader==0) { string tempLine = line.c_str() ; UpdatePloidySummary(tempLine); ReadHeader=1; } ReducedHaplotypeInfoSummary tempBlock; if(ReadBlockHeaderSummary(line, tempBlock)) { if(finChromosome!=checkChr) { cout << "\n ERROR !!! \n Reference Panel is on chromosome ["<discardLine(); line.clear(); continue; } if(finChromosome!=checkChr) { cout << "\n ERROR !!! \n Reference Panel is on chromosome ["<myHapDataVariables.CHR=="") { cout << "\n ERROR !!! \n No variants left to imported from reference haplotype file "<myHapDataVariables.CHR<<":" <myHapDataVariables.START<<"-"<myHapDataVariables.END <<"] in reference haplotype file "<myHapDataVariables.MyChromosome!="" && chr==MyAllVariables->myHapDataVariables.MyChromosome.c_str()) return true; string temp[]={"1","2","3","4","5","6","7","8","9","10","11" ,"12","13","14","15","16","17","18","19","20","21","22","23","X","Y" ,"chr1","chr2","chr3","chr4","chr5","chr6","chr7","chr8","chr9","chr10","chr11" ,"chr12","chr13","chr14","chr15","chr16","chr17","chr18","chr19","chr20" ,"chr21","chr22","chr23","chrX","chrY"}; std::vector ValidChromList (temp, temp + sizeof(temp) / sizeof(string) ); for(int counter=0;counter<(int)ValidChromList.size();counter++) if(chr==ValidChromList[counter]) result=true; return result; } void HaplotypeSet::writem3vcfFile(String filename,bool &gzip) { IFILE m3vcffile = ifopen(filename + ".m3vcf" + (gzip ? ".gz" : ""), "wb",(gzip ? InputFile::BGZF : InputFile::UNCOMPRESSED)); ifprintf(m3vcffile, "##fileformat=M3VCF\n"); ifprintf(m3vcffile, "##version=1.2\n"); ifprintf(m3vcffile, "##compression=block\n"); ifprintf(m3vcffile, "##n_blocks=%d\n",NoBlocks); ifprintf(m3vcffile, "##n_haps=%d\n",numHaplotypes); ifprintf(m3vcffile, "##n_markers=%d\n",numMarkers); if(finChromosome=="X" || finChromosome=="23") ifprintf(m3vcffile, "##chrxRegion=%s\n",PseudoAutosomal?"PseudoAutosomal":"NonPseudoAutosomal"); ifprintf(m3vcffile, "##\n"); ifprintf(m3vcffile, "#CHROM\t"); ifprintf(m3vcffile, "POS\t"); ifprintf(m3vcffile, "ID\t"); ifprintf(m3vcffile, "REF\t"); ifprintf(m3vcffile, "ALT\t"); ifprintf(m3vcffile, "QUAL\t"); ifprintf(m3vcffile, "FILTER\t"); ifprintf(m3vcffile, "INFO\t"); ifprintf(m3vcffile, "FORMAT"); int i,j,k; for(i=0;i<(int)numSamples;i++) { ifprintf(m3vcffile, "\t%s_HAP_1",individualName[i].c_str()); if(SampleNoHaplotypes[i]==2) ifprintf(m3vcffile, "\t%s_HAP_2",individualName[i].c_str()); } ifprintf(m3vcffile, "\n"); int length=NoBlocks; string cno; for(i=0;i\t.\t.\t.\t.\t",tempInfo.startIndex,tempInfo.endIndex); ifprintf(m3vcffile, "B%d;VARIANTS=%d;REPS=%d\t.",i+1,nvariants,reps); for(j=0;jmyOutFormat.RsId?VariantList[j+tempInfo.startIndex].rsid.c_str():VariantList[j+tempInfo.startIndex].name.c_str()); ifprintf(m3vcffile, "%s\t%s\t.\t.\t",VariantList[j+tempInfo.startIndex].refAlleleString.c_str(),VariantList[j+tempInfo.startIndex].altAlleleString.c_str()); ifprintf(m3vcffile, "B%d.M%d",i+1,j+1); if(Error.size()>0) ifprintf(m3vcffile, ";Err=%.5g;Recom=%.5g", Error[j+tempInfo.startIndex],(j+tempInfo.startIndex)<(int)Recom.size()?Recom[j+tempInfo.startIndex]:0); ifprintf(m3vcffile, "\t"); vector &TempHap = tempInfo.TransposedUniqueHaps[j]; for(k=0;kreadLine(line); if(line.length()<1) { ifclose(fileStream); return "Invalid"; } string tempString; tempString=(line.substr(0,17)); char temp[tempString.length() + 1]; std::strcpy(temp,tempString.c_str()); for (char *iter = temp; *iter != '\0'; ++iter) { *iter = std::tolower(*iter); } if(((string)temp).compare("##fileformat=m3vc")==0) { ifclose(fileStream); return "m3vcf"; } else if(((string)temp).compare("##fileformat=vcfv")==0) { ifclose(fileStream); return "vcf"; } else { ifclose(fileStream); return "Invalid"; } } else { ifclose(fileStream); return "NA"; } ifclose(fileStream); return "NA"; } bool HaplotypeSet::readm3vcfFile(String m3vcfFile,String CHR,int START,int END,int WINDOW) { string line,tempString,tempBlockPos,tempString2,tempString3,tempName,tempRsId,tempChr; variant tempVariant; variant tempVariant2; int InitialNMarkers=0,blockIndex,startIndexFlag=0,readIndex=0,writeBlockIndex=0,NoBlocks=0,tempPos,NoMarkersWritten=0,tempVarCount,tempRepCount; int OrigStartPos=START; int OrigEndPos=END; //cout<<"\n Reading Reference Haplotype information from M3VCF files : "< 0) { if (START-WINDOW < 0) START = 0; else START -= WINDOW; END += WINDOW; } if(CHR!="") { std::cout << "\n Loading markers from chromosome " << CHR; if(END>0) std::cout << " from base position "<readLine(line); if(line.compare("##fileformat=M3VCF")!=0 && line.compare("##fileformat=OPTM")!=0) { cout<<" Incorrect Header Information : "<readLine(line); if(line.substr(0,2).compare("##")==0) Header=true; else break; tempString = (string) strtok_r ((char*)line.c_str(),"=", &end_str1); pch = strtok_r (NULL, "=", &end_str1); if(tempString.compare("##n_blocks")==0) { NoBlocks=atoi(pch); continue; } else if(tempString.compare("##n_haps")==0) { numHaplotypes=atoi(pch); continue; } else if(tempString.compare("##n_markers")==0) { InitialNMarkers=atoi(pch); // abort(); continue; } else if(tempString.compare("##chrxRegion")==0) { tempString = (string) pch; if(tempString.compare("NonPseudoAutosomal")==0) PseudoAutosomal=false; else if(tempString.compare("PseudoAutosomal")==0) PseudoAutosomal=true; else { cout << "\n Inconsistent Tag for Chr X. "<9) { tempString2=string(pch); /////////////////////////// // if(colCount%2==0) individualName.push_back(tempString2.substr(0,tempString2.size()-6)); } pch = strtok_r (NULL,"\t", &end_str2); } cout<<" Reading "<readLine(line); char *end_str_new; pch = strtok_r ((char*)line.c_str(),"\t", &end_str_new); tempChr=string(pch); pch = strtok_r (NULL,"\t", &end_str_new); tempBlockPos=string(pch); char *end_str_new1; char *pch1; pch1 = strtok_r ((char*)tempBlockPos.c_str(),"-", &end_str_new1); int tempStartBlock=atoi(pch1); pch1 = strtok_r (NULL,"-", &end_str_new1); int tempEndBlock=atoi(pch1); if(CHR!="") { if(tempChr.compare(CHR.c_str())!=0) flag=1; else { if(END>0) { if(tempStartBlock>END) flag=1; } if(tempEndBlockdiscardLine(); continue; } tempBlock.TransposedUniqueHaps.resize(tempVarCount); tempBlock.RepSize=tempRepCount; tempBlock.BlockSize=tempVarCount; tempBlock.uniqueCardinality.resize(tempRepCount,0.0); tempBlock.InvuniqueCardinality.resize(tempRepCount,0.0); // vector &TempHap = tempBlock.TransposedUniqueHaps[tempIndex]; //tempBlock.TransposedUniqueHaps uniqueHaps.resize(tempRepCount); tempBlock.uniqueIndexMap.resize(numHaplotypes); pch = strtok_r (NULL,"\t", &end_str_new); pch = strtok_r (NULL,"\t", &end_str_new); int check=0; while(pch!=NULL) { int tempval=atoi(pch); tempBlock.uniqueIndexMap[check]=tempval; tempBlock.uniqueCardinality[tempval]++; check++; pch = strtok_r (NULL,"\t", &end_str_new); } for (int i = 0; i < tempRepCount; i++) { tempBlock.InvuniqueCardinality[i]=1.0/(float)tempBlock.uniqueCardinality[i]; } if(check!=numHaplotypes) { cout<readLine(line); end_str_new3=NULL; pch3 = strtok_r ((char*)line.c_str(),"\t", &end_str_new3); tempChr=(string)pch3; pch3 = strtok_r (NULL,"\t", &end_str_new3); tempPos=atoi(pch3); stringstream strs3; strs3<0) { if(tempPos>END || tempPos0) // to ensure a single marker from a block is NOT read. blocktoSave=1; blockEnterFlag=1; } if(tempPos>=OrigStartPos && startIndexFlag==0) { PrintStartIndex=writeBlockIndex; startIndexFlag=1; } // if(CHR=="" || tempPos<=OrigEndPos) // PrintEndIndex=writeBlockIndex; // if(CHR=="") { PrintEndIndex=writeBlockIndex; } else { if(OrigEndPos==0 || tempPos<=OrigEndPos) PrintEndIndex=writeBlockIndex; } variant tempVariant; tempVariant.assignValues(tempName,tempName,tempChr,tempPos); tempVariant.rsid=tempRsId; double tempRecom=-3.0,tempError=0.0; pch3 = strtok_r (NULL,"\t", &end_str_new3); string tempString98=(string)(pch3); pch3 = strtok_r (NULL,"\t", &end_str_new3); string tempString99=(string)(pch3); tempVariant.assignRefAlt(tempString98,tempString99); pch3 = strtok_r (NULL,"\t", &end_str_new3); pch3 = strtok_r (NULL,"\t", &end_str_new3); pch3 = strtok_r (NULL,"\t", &end_str_new3); tempString=(string)(pch3); char *pch4, *end_str_new4; pch4=strtok_r ((char*)tempString.c_str(),";", &end_str_new4); stringstream strs1,strs2; strs1<<(blockIndex+1); strs2<<(tempIndex+1); tempString3="B"+ (string)(strs1.str())+ ".M"+ (string)(strs2.str()); if(tempString3.compare((string)pch4)!=0) { cout< &TempHap = tempBlock.TransposedUniqueHaps[tempIndex]; TempHap.resize(tempRepCount); for(check=0;check0) // optEndPoints.push_back(ReducedStructureInfo[ReducedStructureInfo.size()-1].endIndex); if(Recom.size()>0) Recom.pop_back(); finChromosome=tempChr; } else { cout<<" Following M3VCF File Not Available : "< &TempHap = TempBlock.TransposedUniqueHaps[j-TempBlock.startIndex]; for (i = 0; i TotalSample(numTypedOnlyMarkers, 0); int i,K,j; int haplotypeIndex=0; for(K=0;K &result, const char *input, const char *delimiter, int Number) { size_t wordCount = 1; result[0].clear(); std::string *word = &result[0]; while (*input) { if (*input==*delimiter) { // we got a delimeter, and since an empty word following // a delimeter still counts as a word, we allocate it here wordCount++; if((int)wordCount>Number) return; result[wordCount-1].clear(); word = &result[wordCount-1]; } else { word->push_back(*input); } input++; } } string HaplotypeSet::FindTokenWithPrefix(const char *input,const char *delimiter, string CheckPrefix) { std::string word = ""; int Size = (int)CheckPrefix.size(); int FirstChar = 0; while (*input) { if ( FirstChar==0 || *input==*delimiter) { if(FirstChar==0) FirstChar=1; else ++input; int Index=0; while(*input) { word=word + (*input); if(Index tokens(2); vector PosTokens(2); MyTokenize(tokens, input.c_str(), tabSep,2); string tempChr=tokens[0]; MyTokenize(PosTokens, tokens[1].c_str(), dashSep, 2); int tempStartBlock=atoi(PosTokens[0].c_str()); int tempEndBlock=atoi(PosTokens[1].c_str()); if(finChromosome=="NULL") finChromosome=tempChr; if(CHR!="") { if(tempChr.compare(CHR.c_str())!=0) return 1; else { if(tempStartBlock>END) return 1; if(tempEndBlock NoVariantsToken(2); MyTokenize(NoVariantsToken, PrefixString.c_str(), equalSep, 2); return atof(NoVariantsToken[1].c_str()); } else { abort(); cout< NoVariantsToken(2); MyTokenize(NoVariantsToken, PrefixString.c_str(), equalSep, 2); return atof(NoVariantsToken[1].c_str()); } else { cout< NoVariantsToken(2); MyTokenize(NoVariantsToken, PrefixString.c_str(), equalSep, 2); return atof(NoVariantsToken[1].c_str()); } else return -3.0; } double HaplotypeSet::GetError(string &input) { const char *equalSep="=",*semicolSep=";"; string PrefixString = FindTokenWithPrefix(input.c_str(),semicolSep, "Err="); if(PrefixString!="") { vector NoVariantsToken(2); MyTokenize(NoVariantsToken, PrefixString.c_str(), equalSep, 2); return atof(NoVariantsToken[1].c_str()); } else return -3.0; } Minimac4-1.0.2/src/HaplotypeSet.h000066400000000000000000000300551353222426400165420ustar00rootroot00000000000000#ifndef HAPLOTYPESET_H_INCLUDED #define HAPLOTYPESET_H_INCLUDED #include "Unique.h" #include "MyVariables.h" #include "StringBasics.h" #include "VcfFileReader.h" #include #include #include #include #include using namespace std; class HaplotypeSet { public: // Basic Variables String inFileName; int numHaplotypes,numSamples; int numMarkers,NoBlocks; int numOverlapMarkers, numTypedOnlyMarkers; int maxBlockSize, maxRepSize; int RefTypedTotalCount; string finChromosome; bool PseudoAutosomal; int m3vcfVERSION; bool vcfType,m3vcfxType; // vector optEndPoints; // Reduced Haplotype Information vector ReducedStructureInfo; vector ReducedStructureInfoSummary; vector > ReducedStructureInfoBuffer; vector MarkerToReducedInfoMapper; bool readm3vcfFile(String m3vcfFile,String CHR,int START,int END,int WINDOW); // Special Haplotype Variables for GWAS Panel vector > haplotypesUnscaffolded; vector > MissingSampleUnscaffolded; vector > GWASOnlyhaplotypesUnscaffolded; vector > GWASOnlyMissingSampleUnscaffolded; // Variant and Sample Information and Allele Freq vector Targetmissing; vector individualName; vector SampleNoHaplotypes; vector CummulativeSampleNoHaplotypes; vector *SampleNoHaplotypesPointer; vector VariantList; vector TypedOnlyVariantList; vector OverlapOnlyVariantList; vector AlleleFreq; vector GWASOnlyAlleleFreq; vector Recom,Error; // Variables for Scaffolding and Import Indexing vector knownPosition; vector importIndexList; vector RefAlleleSwap; vector MapTarToRef; vector MapRefToTar; vector TargetMissingTypedOnly; vector RefTypedIndex; // Printing Indexing Variables int PrintStartIndex,PrintEndIndex; int PrintTypedOnlyStartIndex,PrintTypedOnlyEndIndex; vector FlankRegionStart,FlankRegionEnd; double size() { double S=0; S+=FlankRegionStart.size() * sizeof(int); S+=FlankRegionEnd.size() * sizeof(int); S+=Targetmissing.size() * sizeof(int); S+=knownPosition.size() * sizeof(int); S+=importIndexList.size() * sizeof(int); S+=MapTarToRef.size() * sizeof(int); S+=MapRefToTar.size() * sizeof(int); S+=TargetMissingTypedOnly.size() * sizeof(int); S+=RefAlleleSwap.size() * sizeof(bool); S+=RefTypedIndex.size() * sizeof(int); // S+=optEndPoints.size() * sizeof(int); S+=CummulativeSampleNoHaplotypes.size() * sizeof(int); S+=SampleNoHaplotypes.size() * sizeof(bool); S+=MarkerToReducedInfoMapper.size() * sizeof(int); S+=AlleleFreq.size() * sizeof(double); S+=GWASOnlyAlleleFreq.size() * sizeof(double); S+=Recom.size() * sizeof(double); S+=Error.size() * sizeof(double); for(int i=0;i<(int)individualName.size();i++) { S+=individualName[i].size(); } for(int i=0;i<(int)VariantList.size();i++) { S+=VariantList[i].size(); } for(int i=0;i<(int)VariantList.size();i++) { S+=VariantList[i].size(); } for(int i=0;i<(int)TypedOnlyVariantList.size();i++) { S+=TypedOnlyVariantList[i].size(); } for(int i=0;i<(int)OverlapOnlyVariantList.size();i++) { S+=OverlapOnlyVariantList[i].size(); } for(int i=0;i<(int)ReducedStructureInfo.size();i++) { S+=ReducedStructureInfo[i].size(); } for(int i=0;i<(int)ReducedStructureInfoSummary.size();i++) { S+=ReducedStructureInfoSummary[i].size(); } for(int j=0;j<(int)ReducedStructureInfoBuffer.size();j++) for(int i=0;i<(int)ReducedStructureInfoBuffer[j].size();i++) { S+=ReducedStructureInfoBuffer[j][i].size(); } for(int i=0;i<(int)haplotypesUnscaffolded.size();i++) { S+=haplotypesUnscaffolded[i].size() * sizeof(AlleleType); S+=MissingSampleUnscaffolded[i].size() * sizeof(AlleleType); } for(int i=0;i<(int)GWASOnlyhaplotypesUnscaffolded.size();i++) { S+=GWASOnlyhaplotypesUnscaffolded[i].size() * sizeof(AlleleType); S+=GWASOnlyMissingSampleUnscaffolded[i].size() * sizeof(AlleleType); } return (S); }; // Formatting Variables OutputFormatVariable *MyOutFormat; ModelVariable *MyModelVariables; HaplotypeDataVariables *MyHapDataVariables; AllVariable *MyAllVariables; // temp variables for checking, deleted later int importIndexListSize; // Minor variables for formatting stuff bool StartedThisPanel; int NoLinesToDiscardatBeginning; bool AlreadyReadMiddle; vector BlockPiecesforVarInfo; void UpdatePloidySummary(string line); void UncompressTypedSitesNew(HaplotypeSet &rHap,HaplotypeSet &tHap,int ChunkNo); void CreateScaffoldedParameters(HaplotypeSet &rHap); void CreateAfterUncompressSummary(); void InvertUniqueIndexMap(); void CreateSiteSummary(); void getm3VCFSampleNames(string &line); void UpdateParameterList(); void GetTransUniqueHapsVERSION2(int index, ReducedHaplotypeInfo &tempBlock, string &tempString); bool ReadBlockHeaderSummary(string &line, ReducedHaplotypeInfoSummary &tempBlocktoCheck); void GetVariantInfoFromBlock(IFILE m3vcfxStream, ReducedHaplotypeInfoSummary &tempBlock,int &NoMarkersImported); bool ReadBlockHeader(string &line, ReducedHaplotypeInfo &tempBlocktoCheck); void ReadThisBlock(IFILE m3vcfxStream, int blockIndex, ReducedHaplotypeInfo &tempBlock); void Create(int index, HaplotypeSet &rHap); void reconstructHaplotype(vector &reHaplotypes,int &index); bool BasicCheckForM3VCFReferenceHaplotypes(String &Reffilename, AllVariable& MyAllVariable); bool BasicCheckForTargetHaplotypes(String &VCFFileName, String TypeofFile, AllVariable& MyAllVariable); bool BasicCheckForVCFReferenceHaplotypes(String &VCFFileName, String TypeofFile, AllVariable& MyAllVariable); bool GetVariantInfofromVCFFile(String &VCFFileName, String TypeofFile, AllVariable& MyAllVariable); bool ScaffoldGWAStoReference(HaplotypeSet &rHap, AllVariable& MyAllVariable); void GetSummary(IFILE m3vcfxStream); bool ReadM3VCFChunkingInformation(String &Reffilename,string checkChr); bool CheckValidChrom (string chr); void writem3vcfFile (String filename,bool &gzip); string DetectFileType (String filename); void CalculateGWASOnlyAlleleFreq(); void CalculateAlleleFreq(); AlleleType RetrieveMissingScaffoldedHaplotype(int sample,int marker); AlleleType RetrieveScaffoldedHaplotype(int sample,int marker); void MyTokenize(vector &result,const char *input,const char *delimiter, int Number); string FindTokenWithPrefix(const char *input,const char *delimiter,string CheckPrefix); int CheckBlockPosFlag(string &input,String &CHR,int &START,int &END); int GetNumVariants(string &input); int GetNumReps(string &input); double GetRecom(string &input); double GetError(string &input); // // // // //bool ReadVCFChunkingInformation(String &Tarfilename, HaplotypeSet &rHapforChunk); // // // // // // //bool readm3vcfFileNew(String m3vcfFile,String CHR,int START,int END,int WINDOW); // // // // // // // // // //vector > CrossPanelReducedHapInfo; // //bool FindBasicSummaryM3VCF(String &Reffilename); // // // //bool ReadChunkingInformation(String &Reffilename); // // // // // // // // // // // // // // // void UncompressTypedSites(HaplotypeSet &rHap,HaplotypeSet &tHap); // // // // // // bool CopyVcfTargetHaplotypes(HaplotypeSet &rHap,HaplotypeSet &tHap); // // bool getScaffoldedHaplotype (int sample,int marker); // bool getMissingScaffoldedHaplotype (int sample,int marker); // void Create (int index, HaplotypeSet &rHap); // void calculateFreq (); // void CalculateFreq (); // void CalculateGWASOnlyFreq (); // bool FasterLoadHaplotypes (String filename, int maxIndiv, int maxMarker,String CNO, // int START,int END,int WINDOW,bool rsid,bool compressOnly, // bool filter, String &outfile, bool &gz); // bool LoadTargetHaplotypes (String filename, String targetSnpfile, vector &refSnpList,HaplotypeSet &rHap,bool typedOnly,bool passOnly); // bool LoadVcfTargetHaplotypes (String filename, String snpNames, vector &refSnpList,HaplotypeSet &rHap); // void PrintDosageGWASOnlyForVcfOutputForID (HaplotypeSet &tHap, // IFILE vcfdose, // int MarkerIndex); // void PrintDosageGWASOnlyForVcfOutputForIDMaleSamples (HaplotypeSet &tHap,IFILE vcfdose, // int MarkerIndex); // void SaveIndexForGWASOnlyForVcfOutput (int SamID,int HapId); // bool readm3vcfFile (String m3vcfFile,String CHR,int START,int END,int WINDOW); // void reconstructHaplotype (vector &reHaplotypes,int &index); // void SaveDosageForVcfOutput (int hapID,vector dose,vector impAlleles); // void SaveDosageForVcfOutputSampleWise (int SamID,string &SampleName, vector &dose1,vector &dose2,vector &impAlleles1,vector &impAlleles2); // void InitializeDosageForVcfOutput (int NHaps,int NMarkers); // void InitializePartialDosageForVcfOutput (int NHaps,int NMarkers, vector &Format); // void InitializePartialDosageForVcfOutputMaleSamples (int NHaps,int NMarkers, vector &Format); // void PrintDosageForVcfOutputForID (IFILE vcfdose, int MarkerIndex,bool majorIsReference,char refAllele); // void PrintPartialDosageForVcfOutputForID (IFILE vcfdose, int MarkerIndex,bool majorIsReference,char refAllele); // bool BasicCheckForTargetHaplotypes (String filename); // // // string DetectReferenceFileType (String filename); // void SaveDosageForVcfOutputSampleWiseChrX (int SamID,string &SampleName, vector &dose1, // vector &impAlleles1); // // // void CreateSummary (); // void PrintDosageForVcfOutputForIDMaleSamples (IFILE vcfdose, int MarkerIndex,bool majorIsReference,char refAllele); }; #endif // HAPLOTYPESET_H_INCLUDED Minimac4-1.0.2/src/Imputation.cpp000066400000000000000000000773561353222426400166240ustar00rootroot00000000000000#include "Imputation.h" void Imputation::ParameterEstimateThisChunk(int ChunkId, HaplotypeSet &FullrHap, HaplotypeSet &rHap_loo) { ChunkNo=ChunkId; rHapChunked=&FullrHap; int time_prev = time(0); int EstimationStates = MyAllVariables->myModelVariables.states; int EstimationRounds = MyAllVariables->myModelVariables.rounds; MarkovParameters *MP=new MarkovParameters(FullrHap.numMarkers); cout<<" ------------------------------------------------------------------------------"<0) { printf(" Reading pre-calculated estimates located in M3VCF file ...\n"); cout<Recom=FullrHap.Recom; MP->Error=FullrHap.Error; } printf(" Initializing Model Parameters (using EM and up to %d haplotypes) ...", EstimationStates); cout< PrevRightFoldedProb,CurrentRightProb,CurrentNoRecoRightProb,recomProb; // PrevRightFoldedProb.reserve(rHap.maxRepSize); // CurrentRightProb.reserve(rHap.maxRepSize); // CurrentNoRecoRightProb.reserve(rHap.maxRepSize); // recomProb.reserve(rHap.maxRepSize); // // // vector missing_loo(markerCount,false); // MarkovModel MM(tHap_loo,rHap_loo,missing_loo,rHap.major,LowMemory); // MM.CopyParameters(MP); // MM.initializeMatrices(rHap_loo,tHap_loo); // MM.ReinitializeMatrices(); // // // if(!missing_loo[0]) // { // if(!tHap_loo.getMissingScaffoldedHaplotype(0,0)) // { // ConditionJunctionProb(rHap_loo,0,MM.junctionLeftProb[0], // MM.Error[0], // tHap_loo.getScaffoldedHaplotype(0,0)? rHap.AlleleFreq[0] : 1-rHap.AlleleFreq[0], // tHap_loo.getScaffoldedHaplotype(0,0), // MM.backgroundError, // rHap_loo.ReducedStructureInfo[0]); // } // } // // for(int group=1;group<=rHap.NoBlocks;group++) // { // LeftTraverse(rHap_loo,tHap_loo,0,MM,group,recomProb,rHap); // } // // double tempLogLikelihoodValue=CalculateLikelihood(rHap_loo,MM); // // if(em) // { // for(int group=rHap.NoBlocks;group>0;group--) // { // EMTraverse(rHap_loo,tHap_loo,0,MM,group, // recomProb,PrevRightFoldedProb, // CurrentRightProb,CurrentNoRecoRightProb,rHap); // } // MM.empiricalCount++; // } // //#pragma omp critical // { // (*MP)+=MM; // LogLikelihoodValue+=tempLogLikelihoodValue; // } } // // // // MP->UpdateModel(); // // double crossovers = 0; // for (int i = 0; i < rHap.numMarkers - 1; i++) // crossovers += MP->Recom[i]; // // double errors = 0; // for (int i = 0; i < rHap.numMarkers ; i++) // { // double heterozygosity = 1.0 - pow(rHap.AlleleFreq[i],2) // - pow(1-rHap.AlleleFreq[i],2); // errors += MP->Error[i] * heterozygosity; // } // errors /= (double) rHap.numMarkers + 1e-30; // // printf(" %.0f mosaic crossovers expected per haplotype\n", crossovers); // printf(" %.3g errors in mosaic expected per marker\n", errors); // printf(" Log-Likelihood of this Iteration : %.5g", LogLikelihoodValue); // cout<Recom; // rHap.Error=MP->Error; // } // // // // printf("\n Saving estimated parameters for future use/reference to ..."); // cout<WriteParameters(rHap.markerName, outFile, false); // int time_load = time(0) - time_prev; // // cout << "\n Time taken for parameter estimation = " << time_load << " seconds. "<0) // { // std::cout << "\n Writing final reduced haplotype information to [.m3vcf] file : " <Recom=FullrHap.Recom; // MP->Error=FullrHap.Error; // stats->Initialize(FullrHap.numMarkers, tgwasHap.numMarkers); // // cout << "\n Starting Imputation ..."<myOutFormat.vcfBuffer,NumVcfWritten=0,NumVcfToBeWritten=0; // if((maxVcfSample)>=tgwasHap.numSamples) // maxVcfSample=tgwasHap.numSamples; // int TotalNumSamples=tgwasHap.numSamples; // // SinglePartialDosageData.ReParameterizePartialDosageData(ChunkNo, FullrHap, tgwasHap); // CurrentPartialDosageData=&SinglePartialDosageData; // // CurrentPartialDosageData->UpdatePartialDosageData(maxVcfSample, NumVcfToBeWritten); // // int StartSamId=0, EndSamId; // TimeToWrite=0; // // // // for(int batchNo=0; ; batchNo++) // { // EndSamId = StartSamId + (maxVcfSample) < TotalNumSamples ? StartSamId + (maxVcfSample) : TotalNumSamples; // // printf(" Imputing Samples %d-%d [%0.0f%%] out of %d samples ...", StartSamId + 1, EndSamId, 100*(float)EndSamId/TotalNumSamples, TotalNumSamples); // cout< SwapDosageData; // int hapId= tgwasHap.CummulativeSampleNoHaplotypes[SampleId]; // //(2*SampleId); // // vector PrevRightFoldedProb,CurrentRightProb,CurrentNoRecoRightProb,recomProb; // DosageData *ThisSamplePartialDosageData; // //#pragma omp critical (BindSample) // { //#ifdef _OPENMP // MMIndexId = omp_get_thread_num(); //#endif // ThisSamplePartialDosageData=CurrentPartialDosageData; // SwapDosageData=CurrentPartialDosageData->IndexSample(SampleId); // } // // // MarkovModel &MM=MainMarkovModel[MMIndexId]; // MM.CopyParametersNew(MP); // // int hapIdIndiv=hapId; // do{ // // MM.ThisHapId=hapIdIndiv; // MM.ReinitializeMatrices(); // ThisSamplePartialDosageData->BindSampleMModel(MM,SwapDosageData.second,hapIdIndiv-hapId); // // if(FullrHap.MapRefToTar[0]!=-1 && tgwasHap.RetrieveMissingScaffoldedHaplotype(hapIdIndiv,0)=='0') // { // // int TargetMarkerPosition = FullrHap.MapRefToTar[0]; // ConditionJunctionProb(FullrHap,0,MM.junctionLeftProb[0],MM.Error[0], // tgwasHap.RetrieveScaffoldedHaplotype(hapIdIndiv,TargetMarkerPosition)=='1'? FullrHap.AlleleFreq[0] : 1-FullrHap.AlleleFreq[0], // tgwasHap.RetrieveScaffoldedHaplotype(hapIdIndiv,TargetMarkerPosition),MM.backgroundError,FullrHap.ReducedStructureInfo[0]); // } // // for(int group=1;group<=FullrHap.NoBlocks;group++) // { // LeftTraverse(FullrHap,tgwasHap,hapIdIndiv,MM,group,recomProb); // } // // MM.CeateProbSum(FullrHap.NoBlocks,FullrHap.numHaplotypes); // for(int group=FullrHap.NoBlocks;group>0;group--) // { // ImputeTraverse(FullrHap, hapIdIndiv,MM,group, recomProb,PrevRightFoldedProb,CurrentRightProb,CurrentNoRecoRightProb); // } // //#pragma omp critical (StatUpdate) // { // stats->NewUpdate(FullrHap, tgwasHap, hapIdIndiv, MM.DosageHap, MM.LooDosageHap); // } // // if(tgwasHap.SampleNoHaplotypes[SampleId]==1) // { // break; // } // }while(hapId == hapIdIndiv++); // // // // if (MyAllVariables->myOutFormat.hapOutput && !MyAllVariables->myOutFormat.unphasedOutput) // { //#pragma omp critical (PrintHapData) // PrintHaplotypeData( hapIdIndiv, SampleId, MM.DosageHap); // } // // if(MyAllVariables->myOutFormat.doseOutput) // { //#pragma omp critical (PrintDoseData) // PrintDosageData(SampleId, ThisSamplePartialDosageData->hapDosage[(2*SwapDosageData.second)], ThisSamplePartialDosageData->hapDosage[(2*SwapDosageData.second)+1] ); // } // // if(MyAllVariables->myOutFormat.vcfOutput) // { // if(SwapDosageData.first==1) // { //#pragma omp critical (printVCF) // { // TotalNovcfParts++; // printf(" Saving Samples in temporary VCF file ... "); // cout<FlushPartialVcf(TotalNovcfParts); // // TimeToWrite+=ThisSamplePartialDosageData->TimeToWrite; // NumVcfToBeWritten = NumVcfWritten + maxVcfSample; // ThisSamplePartialDosageData->UpdatePartialDosageData(maxVcfSample < TotalNumSamples-NumVcfToBeWritten ? maxVcfSample : TotalNumSamples-NumVcfToBeWritten, NumVcfToBeWritten); // NumVcfWritten+=maxVcfSample; // } // } // } // // // // } // // StartSamId=EndSamId ; // // if(StartSamId>=TotalNumSamples) // break; // } // // delete MP; // TimeToImpute = time(0) - time_prev; cout <Recom=FullrHap.Recom; MP->Error=FullrHap.Error; stats->Initialize(FullrHap.numMarkers, tgwasHap.numMarkers); cout << "\n Starting Imputation ..."<myOutFormat.vcfBuffer,NumVcfWritten=0,NumVcfToBeWritten=0; if((maxVcfSample)>=tgwasHap.numSamples) maxVcfSample=tgwasHap.numSamples; int TotalNumSamples=tgwasHap.numSamples; SinglePartialDosageData.ReParameterizePartialDosageData(ChunkNo, FullrHap, tgwasHap); CurrentPartialDosageData=&SinglePartialDosageData; CurrentPartialDosageData->UpdatePartialDosageData(maxVcfSample, NumVcfToBeWritten); int StartSamId=0, EndSamId; TimeToWrite=0; for(int batchNo=0; ; batchNo++) { EndSamId = StartSamId + (maxVcfSample) < TotalNumSamples ? StartSamId + (maxVcfSample) : TotalNumSamples; printf(" Imputing Samples %d-%d [%0.0f%%] out of %d samples ...", StartSamId + 1, EndSamId, 100*(float)EndSamId/TotalNumSamples, TotalNumSamples); cout< SwapDosageData; int hapId= tgwasHap.CummulativeSampleNoHaplotypes[SampleId]; //(2*SampleId); vector PrevRightFoldedProb,CurrentRightProb,CurrentNoRecoRightProb,recomProb; DosageData *ThisSamplePartialDosageData; #pragma omp critical (BindSample) { #ifdef _OPENMP MMIndexId = omp_get_thread_num(); #endif ThisSamplePartialDosageData=CurrentPartialDosageData; SwapDosageData=CurrentPartialDosageData->IndexSample(SampleId); } MarkovModel &MM=MainMarkovModel[MMIndexId]; MM.CopyParametersNew(MP); int hapIdIndiv=hapId; do{ MM.ThisHapId=hapIdIndiv; MM.ReinitializeMatrices(); ThisSamplePartialDosageData->BindSampleMModel(MM,SwapDosageData.second,hapIdIndiv-hapId); if(FullrHap.MapRefToTar[0]!=-1 && tgwasHap.RetrieveMissingScaffoldedHaplotype(hapIdIndiv,0)=='0') { int TargetMarkerPosition = FullrHap.MapRefToTar[0]; ConditionJunctionProb(FullrHap,0,MM.junctionLeftProb[0],MM.Error[0], tgwasHap.RetrieveScaffoldedHaplotype(hapIdIndiv,TargetMarkerPosition)=='1'? FullrHap.AlleleFreq[0] : 1-FullrHap.AlleleFreq[0], tgwasHap.RetrieveScaffoldedHaplotype(hapIdIndiv,TargetMarkerPosition),MM.backgroundError,FullrHap.ReducedStructureInfo[0]); } for(int group=1;group<=FullrHap.NoBlocks;group++) { LeftTraverse(FullrHap,tgwasHap,hapIdIndiv,MM,group,recomProb); } MM.CeateProbSum(FullrHap.NoBlocks,FullrHap.numHaplotypes); for(int group=FullrHap.NoBlocks;group>0;group--) { ImputeTraverse(FullrHap, hapIdIndiv,MM,group, recomProb,PrevRightFoldedProb,CurrentRightProb,CurrentNoRecoRightProb); } #pragma omp critical (StatUpdate) { stats->NewUpdate(FullrHap, tgwasHap, hapIdIndiv, MM.DosageHap, MM.LooDosageHap); } if(tgwasHap.SampleNoHaplotypes[SampleId]==1) { break; } }while(hapId == hapIdIndiv++); #pragma omp critical (addCounter) { counter_sample_imputation_finished++; } // if (MyAllVariables->myOutFormat.hapOutput && !MyAllVariables->myOutFormat.unphasedOutput) // { // #pragma omp critical (PrintHapData) // PrintHaplotypeData( hapIdIndiv, SampleId, MM.DosageHap); // } // if(MyAllVariables->myOutFormat.doseOutput) // { // #pragma omp critical (PrintDoseData) // PrintDosageData(SampleId, ThisSamplePartialDosageData->hapDosage[(2*SwapDosageData.second)], ThisSamplePartialDosageData->hapDosage[(2*SwapDosageData.second)+1] ); // } if(MyAllVariables->myOutFormat.vcfOutput) { if(counter_sample_imputation_finished == EndSamId-StartSamId) //if(SwapDosageData.first==1) { #pragma omp critical (printVCF) { TotalNovcfParts++; printf(" Saving Samples in temporary VCF file ... "); cout<FlushPartialVcf(TotalNovcfParts); TimeToWrite+=ThisSamplePartialDosageData->TimeToWrite; NumVcfToBeWritten = NumVcfWritten + maxVcfSample; ThisSamplePartialDosageData->UpdatePartialDosageData(maxVcfSample < TotalNumSamples-NumVcfToBeWritten ? maxVcfSample : TotalNumSamples-NumVcfToBeWritten, NumVcfToBeWritten); NumVcfWritten+=maxVcfSample; } } } } StartSamId=EndSamId ; if(StartSamId>=TotalNumSamples) break; } delete MP; TimeToImpute = time(0) - time_prev; cout <looIndex) ToBlock.uniqueIndexMap[out++] = FromBlock.uniqueIndexMap[in]-1; } } else { ToBlock.TransposedUniqueHaps=FromBlock.TransposedUniqueHaps; for (int in = 0, out = 0; in <(rHap.numHaplotypes); in++) { if(in!=loo) ToBlock.uniqueIndexMap[out++] = FromBlock.uniqueIndexMap[in]; } } for (int in = 0; in < ToBlock.RepSize; in++) { ToBlock.InvuniqueCardinality[in]=1.0/(float)ToBlock.uniqueCardinality[in]; } } } void Imputation::ImputeThisChunk(int ChunkId, HaplotypeSet &FullrHap, HaplotypeSet &tgwasHap, HaplotypeSet &rgwasHap) { ChunkNo=ChunkId; THapUnchunked=&tgwasHap; rHapChunked=&FullrHap; int time_prev = time(0); MarkovParameters *MP=new MarkovParameters(rgwasHap.numMarkers); MP->Recom=rgwasHap.Recom; MP->Error=rgwasHap.Error; stats->Initialize(FullrHap.numMarkers, tgwasHap.numMarkers); cout << "\n Starting Imputation ..."<myOutFormat.vcfBuffer,NumVcfWritten=0,NumVcfToBeWritten=0; if((maxVcfSample)>=tgwasHap.numSamples) maxVcfSample=tgwasHap.numSamples; int TotalNumSamples=tgwasHap.numSamples; SinglePartialDosageData.ReParameterizePartialDosageData(ChunkNo, FullrHap, tgwasHap); CurrentPartialDosageData=&SinglePartialDosageData; CurrentPartialDosageData->UpdatePartialDosageData(maxVcfSample, NumVcfToBeWritten); int StartSamId=0, EndSamId; TimeToWrite=0; for(int batchNo=0; ; batchNo++) { EndSamId = StartSamId + (maxVcfSample) < TotalNumSamples ? StartSamId + (maxVcfSample) : TotalNumSamples; printf(" Imputing Samples %d-%d [%0.0f%%] out of %d samples ...", StartSamId + 1, EndSamId, 100*(float)EndSamId/TotalNumSamples, TotalNumSamples); cout< SwapDosageData; int hapId= tgwasHap.CummulativeSampleNoHaplotypes[SampleId]; //(2*SampleId); vector PrevRightFoldedProb,CurrentRightProb,CurrentNoRecoRightProb,recomProb; DosageData *ThisSamplePartialDosageData; #pragma omp critical (BindSample) { #ifdef _OPENMP MMIndexId = omp_get_thread_num(); #endif ThisSamplePartialDosageData=CurrentPartialDosageData; SwapDosageData=CurrentPartialDosageData->IndexSample(SampleId); } MarkovModel &MM=MainMarkovModel[MMIndexId]; MM.CopyParametersNew(MP); int hapIdIndiv=hapId; do{ MM.ThisHapId=hapIdIndiv; MM.ReinitializeMatrices(); ThisSamplePartialDosageData->BindSampleMModel(MM,SwapDosageData.second,hapIdIndiv-hapId); if(tgwasHap.RetrieveMissingScaffoldedHaplotype(hapIdIndiv,0)=='0') { ConditionJunctionProb(rgwasHap,0,MM.junctionLeftProb[0],MM.Error[0],tgwasHap.RetrieveScaffoldedHaplotype(hapIdIndiv,0)=='1'? rgwasHap.AlleleFreq[0] : 1-rgwasHap.AlleleFreq[0], tgwasHap.RetrieveScaffoldedHaplotype(hapIdIndiv,0),MM.backgroundError,rgwasHap.ReducedStructureInfo[0]); } for(int group=1;group<=rgwasHap.NoBlocks;group++) { LeftTraverse(rgwasHap,tgwasHap,hapIdIndiv,MM,group,recomProb); } MM.CeateProbSum(rgwasHap.NoBlocks,rgwasHap.numHaplotypes); for(int group=rgwasHap.NoBlocks;group>0;group--) { ImputeTraverse(rgwasHap, hapIdIndiv,MM,group, recomProb,PrevRightFoldedProb,CurrentRightProb,CurrentNoRecoRightProb); } #pragma omp critical (StatUpdate) { stats->NewUpdate(FullrHap, tgwasHap, hapIdIndiv, MM.DosageHap, MM.LooDosageHap); } if(tgwasHap.SampleNoHaplotypes[SampleId]==1) { break; } }while(hapId == hapIdIndiv++); } if(MyAllVariables->myOutFormat.vcfOutput) { TotalNovcfParts++; printf(" Saving Samples in temporary VCF file ... "); cout<FlushPartialVcf(TotalNovcfParts); TimeToWrite+=CurrentPartialDosageData->TimeToWrite; NumVcfToBeWritten = NumVcfWritten + maxVcfSample; CurrentPartialDosageData->UpdatePartialDosageData(maxVcfSample < TotalNumSamples-NumVcfToBeWritten ? maxVcfSample : TotalNumSamples-NumVcfToBeWritten, NumVcfToBeWritten); NumVcfWritten+=maxVcfSample; } StartSamId=EndSamId ; if(StartSamId>=TotalNumSamples) break; } delete MP; TimeToImpute = time(0) - time_prev; cout < &recomProb, vector &PrevRightFoldedProb, vector &CurrentRightProb, vector &CurrentNoRecoRightProb) { // vector &optStructure=rHap.optEndPoints; // // int Start=optStructure[group-1]; // int End=optStructure[group]; int Start=rHap.ReducedStructureInfo[group-1].startIndex; int End=rHap.ReducedStructureInfo[group-1].endIndex; MM.foldProbabilities(MM.ThisBlockRightProb[End-Start],group-1, rHap.ReducedStructureInfo[group-1],1,rHap.numHaplotypes); if(MyAllVariables->myModelVariables.minimac3) MM.ImputeSitesMinimac3(hapID, group-1); else MM.ImputeSites(hapID, group-1); splitFoldedProb(recomProb,MM.ThisBlockRightProb[0],MM.ThisBlockRightNoRecoProb[0]); MM.unfoldProbabilities(group-1,recomProb,MM.ThisBlockRightNoRecoProb[0], MM.ThisBlockRightProb[End-Start],1, rHap.ReducedStructureInfo,rHap.numHaplotypes); } void Imputation::LeftTraverse(HaplotypeSet &rHap,HaplotypeSet &tHap,int hapID, MarkovModel &MM,int group, vector &recomProb) { // vector &optStructure=rHap.optEndPoints; int Start=rHap.ReducedStructureInfo[group-1].startIndex; int End=rHap.ReducedStructureInfo[group-1].endIndex; vector > &ThisBlockLeftProb= MM.leftProb[group-1]; MM.foldProbabilities(ThisBlockLeftProb[0],group-1,rHap.ReducedStructureInfo[group-1], 0,rHap.numHaplotypes); MM.CurrentLeftNoRecoProb=ThisBlockLeftProb[0]; if(MyAllVariables->myModelVariables.minimac3) MM.WalkLeftMinimac3(hapID, group-1); else MM.WalkLeft(hapID, group-1); splitFoldedProb(recomProb,ThisBlockLeftProb[End-Start],MM.CurrentLeftNoRecoProb); MM.unfoldProbabilities(group-1,recomProb,MM.CurrentLeftNoRecoProb, ThisBlockLeftProb[0],0, rHap.ReducedStructureInfo,rHap.numHaplotypes); } void Imputation::FreeMemory() { free(SinglePartialDosageData.PrintStringPointer); if(MyAllVariables->myOutFormat.meta) free(SinglePartialDosageData.PrintEmpStringPointer); } void Imputation::InitializeOutputFiles(HaplotypeSet &tarInitializer, int maxSample, int maxRefVar, int maxTarVar) { SinglePartialDosageData.InitializePartialDosageData(tarInitializer, maxSample, maxRefVar, maxTarVar, MyAllVariables); // TwoPartialDosageData.resize(2); // TwoPartialDosageData[0].InitializePartialDosageData(tarInitializer, maxSample, maxVar, MyAllVariables); // TwoPartialDosageData[1].InitializePartialDosageData(tarInitializer, maxSample, maxVar, MyAllVariables); } void Imputation::PrintDosageData(int ThisSampleId, vector &ThisDosage1,vector &ThisDosage2) { // printf(" Outputting Individual %s for Dosage file...", THapUnchunked->individualName[ThisSampleId].c_str()); // cout<individualName[ThisSampleId].c_str()); // int i=0; // // vector *GWASDosage1, *GWASDosage2; // // if(MyAllVariables.myOutFormat.TypedOnly) // { // GWASDosage1 = &(THapUnchunked->GWASOnlyMissingSampleUnscaffolded[2*ThisSampleId]); // GWASDosage2 = THapUnchunked->GWASOnlyMissingSampleUnscaffolded[2*ThisSampleId + 1]; // } // // int NoHaps=THapUnchunked->SampleNoHaplotypes[ThisSampleId]; // // for (int index =0; index < rHapChunked->RefTypedTotalCount; index++) // { // // if(rHapChunked->RefTypedIndex[index]==-1) // { // // if(i>=rHapChunked->PrintStartIndex && i <= rHapChunked->PrintEndIndex) // { // if(NoHaps==1) // ifprintf(dosages, "\t%.3f", ThisDosage1[i]+ThisDosage2[i]); // else // ifprintf(dosages, "\t%.3f", ThisDosage1[i]); // } // i++; // // } // else // { // int MarkerIndex=rHapChunked->RefTypedIndex[index]; // // if(MarkerIndex>=THapUnchunked->PrintTypedOnlyStartIndex && MappingIndex<=THapUnchunked->PrintTypedOnlyEndIndex) // { // if(NoHaps==1) // { // ifprintf(dosages, "\t%.3f", (float)GWASDosage1[MarkerIndex]); // } // else // { // ifprintf(dosages, "\t%.3f", (float)((*GWASDosage1)[MarkerIndex]) + (float)((*GWASDosage2)[MarkerIndex])); // } // } // } // // ifprintf(dosages,"\n"); // } } void Imputation::PrintHaplotypeData(int ThisHapId, int ThisSampleId, vector *ThisimputedHap) { // printf(" Outputting HAPLO%d of Individual %s for Haplotype File...", // ThisHapId%2+1 ,THapUnchunked->individualName[ThisSampleId].c_str()); // cout<individualName[ThisSampleId].c_str(), ThisHapId%2+1 ); // int i=0; // vector &GWASDosage1 = THapUnchunked->GWASOnlyMissingSampleUnscaffolded[ThisHapId]; // // for (int index =0; index < rHapChunked->RefTypedTotalCount; index++) // { // if(rHapChunked->RefTypedIndex[index]==-1) // { // if(i>=rHapChunked->PrintStartIndex && i <= rHapChunked->PrintEndIndex) // { // ifprintf(hapdose, "\t%.5f", (*ThisimputedHap)[i]); // } // i++; // } // else // { // int MarkerIndex=rHapChunked->RefTypedIndex[index]; // ifprintf(hapdose, "\t%.5f", (float)GWASDosage1[MarkerIndex]); // } // } // // ifprintf(hapdose, "\n"); } void Imputation::splitFoldedProb(vector &SplitProb, vector &totalProb, vector &noRecomProb) { SplitProb.resize(totalProb.size()); if(MyAllVariables->myOutFormat.verbose) { for(int i=0;i<(int)totalProb.size();i++) { if(noRecomProb[i]>totalProb[i]) cout<<" DIFFERENCE = "<<(noRecomProb[i]-totalProb[i])<<"\t"<= 0.0); } } } void Imputation::ConditionJunctionProb(HaplotypeSet &rHap, int markerPos,vector &Prob, double e, double freq, AlleleType observed, double backgroundError, ReducedHaplotypeInfo &Info) { vector &TempHap = Info.TransposedUniqueHaps[markerPos-Info.startIndex]; double prandom = e*freq+backgroundError; double pmatch = (1.0 - e)+e*freq+backgroundError; int NoStates=rHap.numHaplotypes; for (int i = 0; i #include "Unique.h" #include #include #ifdef _OPENMP #include #endif using namespace std; class Imputation { public: // Haplotype Variables and Other Basic Variables HaplotypeSet *THapUnchunked, *rHapChunked; AllVariable *MyAllVariables; int ChunkNo, TotalNovcfParts; vector MainMarkovModel; // File Output Stream handling IFILE dosages, hapdose, haps, vcfdosepartial, info, m3vcfFile, recFile, errFile; ImputationStatistics *stats; // Dosage Date for Output DosageData SinglePartialDosageData; DosageData* CurrentPartialDosageData; // Time Variables int TimeToCompress, TimeToImpute, TimeToWrite; double Dosagesize() { double S=0; S+=SinglePartialDosageData.size(); return (S); }; double Probsize() { double S=0; for(int i=0;imyModelVariables.cpus;i++) { S+=MainMarkovModel[i].size(); } return (S); }; void Minimac3ImputeThisChunk(int ChunkId, HaplotypeSet &FullrHap, HaplotypeSet &tgwasHap, HaplotypeSet &rgwasHap); void performImputationBasedonTypedSites(HaplotypeSet &tHap, HaplotypeSet &rHap, HaplotypeSet &tHapOrig, HaplotypeSet &FullrHap); MarkovParameters* createEstimates (HaplotypeSet &rHap,HaplotypeSet &tHap,vector &optStructure,bool NoTargetEstimation); void splitFoldedProb (vector &SplitProb,vector &totalProb, vector &noRecomProb); void performImputation (HaplotypeSet &tHap,HaplotypeSet &rHap, String Golden); void ImputeThisChunk (int ChunkId, HaplotypeSet &rHapOriginal ,HaplotypeSet &tgwasHap, HaplotypeSet &rgwasHap); void performImputationNew (HaplotypeSet &tHap,HaplotypeSet &rHap); void LooOptimalStructure (int loo,HaplotypeSet &rHap, HaplotypeSet &HapLoo); double CalculateLikelihood (HaplotypeSet &rHap,MarkovModel &MM); void ImputeTraverse (HaplotypeSet &rHap,HaplotypeSet &tHap,int hapID, MarkovModel &MM,int group, vector &recomProb, vector &PrevRightFoldedProb, vector &CurrentRightProb, vector &CurrentNoRecoRightProb, HaplotypeSet &rHapMain); void ImputeTraverse (HaplotypeSet &rHap, int hapID, MarkovModel &MM,int group, vector &recomProb, vector &PrevRightFoldedProb, vector &CurrentRightProb, vector &CurrentNoRecoRightProb); void LeftTraverse (HaplotypeSet &rHap,HaplotypeSet &tHap,int hapID, MarkovModel &MM,int group, vector &recomProb); void EMTraverse (HaplotypeSet &rHap,HaplotypeSet &tHap,int hapID, MarkovModel &MM,int group, vector &recomProb, vector &PrevRightFoldedProb, vector &CurrentRightProb, vector &CurrentNoRecoRightProb, HaplotypeSet &rHapMain); void ConditionJunctionProb (HaplotypeSet &rHap, int markerPos,vector &Prob, double e, double freq, AlleleType observed, double backgroundError, ReducedHaplotypeInfo &Info); void FlushPartialVcf (HaplotypeSet &rHap,HaplotypeSet &tHap,HaplotypeSet &PartialDosage, string &filename,int &Index); void MergeFinalVcf (HaplotypeSet &rHap,HaplotypeSet &tHap,ImputationStatistics &stats,int MaxIndex); void MergeFinalVcfAllVariants (HaplotypeSet &rHap,HaplotypeSet &tHap,ImputationStatistics &stats,int MaxIndex); void PrintDosageData (int ThisSampleId, vector &ThisDosage1,vector &ThisDosage2); void PrintHaplotypeData (int ThisHapId, int ThisSampleId, vector *ThisimputedHap); void PrintInfoFile (HaplotypeSet &rHap,HaplotypeSet &tHap, ImputationStatistics &stats); void OutputFilesInitialize (HaplotypeSet &rHap,HaplotypeSet &tHapOrig); void InitializeOutputFiles (HaplotypeSet &tarInitializer, int maxSample, int maxRefVar, int maxTarVar); void FreeMemory (); void ParameterEstimateThisChunk (int ChunkId, HaplotypeSet &FullrHap, HaplotypeSet &rHap_loo); Imputation (AllVariable *MyAllVariable, IFILE Dosages, IFILE Hapdose,IFILE Haps,IFILE Vcfdosepartial, IFILE Info, ImputationStatistics &Stats) { MyAllVariables=MyAllVariable; dosages=Dosages; hapdose=Hapdose; haps=Haps; vcfdosepartial=Vcfdosepartial; info=Info; stats=&Stats; TimeToWrite=0; TimeToImpute=0; TimeToCompress=0; }; Imputation (AllVariable *MyAllVariable, IFILE m3vcf, IFILE recom, IFILE error) { MyAllVariables=MyAllVariable; m3vcfFile = m3vcf; recFile = recom; errFile = error; }; }; #endif // IMPUTATION_H_INCLUDED Minimac4-1.0.2/src/ImputationStatistics.cpp000066400000000000000000000073161353222426400206640ustar00rootroot00000000000000#include "ImputationStatistics.h" #include #include using namespace std; void ImputationStatistics::NewUpdate(HaplotypeSet &rHap,HaplotypeSet &tHap, int hapId, vector *doses, vector *loo) { for (int i = 0; i < numRefMarkers; i++) { float &DoseVal=(*doses)[i]; sum[i] += DoseVal; sumSq[i] += DoseVal * DoseVal; sumCall[i] += DoseVal > 0.5 ? DoseVal : 1.0 - DoseVal; count[i] ++; } vector &UnScaff = tHap.haplotypesUnscaffolded[hapId]; vector &MissUnScaff = tHap.MissingSampleUnscaffolded[hapId]; int index=0; for (int i = 0; i < numRefMarkers; i++) { if(!rHap.Targetmissing[i]) { // assert(index0) ovar=(sumSq[marker] - sum[marker] * sum[marker] / (count[marker] + 1e-30)) / (count[marker] + 1e-30); return ovar / (evar + 1e-30); } double ImputationStatistics::LooRsq(int marker) { if (looCount[marker] < 2) return 0.0; double f = looSum[marker] / (looCount[marker] + 1e-30); double evar = f * (1.0 - f); double ovar = 0.0; if(((looSumSq[marker] - looSum[marker] * looSum[marker] / (looCount[marker] + 1e-30)))>0) ovar = (looSumSq[marker] - looSum[marker] * looSum[marker] / (looCount[marker] + 1e-30)) / (looCount[marker] + 1e-30); return ovar / (evar + 1e-30); } double ImputationStatistics::AlleleFrequency(int marker) { if (count[marker] < 2) return 0.0; return sum[marker] / (count[marker] + 1e-30); } double ImputationStatistics::EmpiricalR(int marker) { if (looCount[marker] < 2) return 0.0; // n * Sum xy - Sum x * Sum y double p = looCount[marker] * looProduct[marker] - looSum[marker] * looObserved[marker]; double qx=0.0,qy=0.0; // sqrt(n*Sum xx - Sum x * Sum x) if((looCount[marker] * looSumSq[marker] - looSum[marker] * looSum[marker])>0) qx = sqrt((looCount[marker] * looSumSq[marker] - looSum[marker] * looSum[marker])); if((looCount[marker] * looObserved[marker] - looObserved[marker] * looObserved[marker])>0) qy = sqrt((looCount[marker] * looObserved[marker] - looObserved[marker] * looObserved[marker])); if (qx / (qy + 1e-30) < 1e-3) return 0.0; if (qy / (qx + 1e-30) < 1e-3) return 0.0; double r = p / (qx * qy + 1e-30); return r; } double ImputationStatistics::EmpiricalRsq(int marker) { double r = EmpiricalR(marker); return r * r; } double ImputationStatistics::LooMajorDose(int marker) { return looProduct[marker] / (looObserved[marker] + 1e-30); } double ImputationStatistics::LooMinorDose(int marker) { return (looSum[marker] - looProduct[marker]) / (looCount[marker] - looObserved[marker] + 1e-30); } double ImputationStatistics::AverageCallScore(int marker) { return sumCall[marker] / (count[marker] + 1e-30); } Minimac4-1.0.2/src/ImputationStatistics.h000066400000000000000000000041061353222426400203230ustar00rootroot00000000000000#ifndef __IMPUTATIONSTATISTICS_H__ #define __IMPUTATIONSTATISTICS_H__ #include "MathVector.h" #include "HaplotypeSet.h" #include "IntArray.h" class ImputationStatistics { public: int numRefMarkers, numTarMarkers; ImputationStatistics() {} ~ImputationStatistics() { } void Initialize(int nRef, int nTar) { numRefMarkers=nRef; numTarMarkers=nTar; fill(sum.begin(), sum.end(), 0.0); fill(sumSq.begin(), sumSq.end(), 0.0); fill(sumCall.begin(), sumCall.end(), 0.0); fill(looSum.begin(), looSum.end(), 0.0); fill(looSumSq.begin(), looSumSq.end(), 0.0); fill(looProduct.begin(), looProduct.end(), 0.0); fill(looObserved.begin(), looObserved.end(), 0.0); fill(count.begin(), count.end(), 0); fill(looCount.begin(), looCount.end(), 0); } void PreInitialize(int markers) { sum.resize(markers, 0.0); sumSq.resize(markers, 0.0); sumCall.resize(markers, 0.0); looSum.resize(markers, 0.0); looSumSq.resize(markers, 0.0); looProduct.resize(markers, 0.0); looObserved.resize(markers, 0.0); count.resize(markers,0); looCount.resize(markers,0); } void Update(vector &doses, vector &loo,vector &observed,vector &Miss, vector &major); void NewUpdate(HaplotypeSet &rHap, HaplotypeSet &tHap, int hapId, vector *doses, vector *loo); double Rsq(int marker); double AlleleFrequency(int marker); double AverageCallScore(int marker); double LooRsq(int marker); double LooMajorDose(int marker); double LooMinorDose(int marker); double EmpiricalR(int marker); double EmpiricalRsq(int marker); double GoldenR(int marker); double GoldenRsq(int marker); double GoldenRgeno(int marker); double GoldenRsqgeno(int marker); // private: vector sum, sumSq, sumCall, looSum, looSumSq, looProduct, looObserved, looObservedSq; vector count, looCount; }; #endif Minimac4-1.0.2/src/Main.cpp000066400000000000000000000222751353222426400153450ustar00rootroot00000000000000 #include #include #include #include "MyVariables.h" #include "Parameters.h" #include "StringBasics.h" #include "Analysis.h" #include #include #include using namespace std; void Minimac4Version(); void helpFile(); int main(int argc, char ** argv) { // Parameter Options String refHaps = ""; String haps = ""; String recFile = "", errFile = ""; bool log = false, help = false, params = false; AllVariable MyAllVariable; OutputFormatVariable &MyOutFormat=MyAllVariable.myOutFormat; ModelVariable &MyModelVariables=MyAllVariable.myModelVariables; HaplotypeDataVariables &MyHapDataVariables=MyAllVariable.myHapDataVariables; ParameterList inputParameters; PhoneHome::allThinning = 50; BEGIN_LONG_PARAMETERS(longParameterList) LONG_PARAMETER_GROUP("Reference Haplotypes") LONG_STRINGPARAMETER("refHaps", &refHaps) LONG_PARAMETER("passOnly", &MyHapDataVariables.passOnly) LONG_PARAMETER("rsid", &MyOutFormat.RsId) LONG_PARAMETER("referenceEstimates", &MyModelVariables.referenceEstimates) LONG_STRINGPARAMETER("mapFile", &MyHapDataVariables.mapFile) LONG_PARAMETER_GROUP("Target Haplotypes") LONG_STRINGPARAMETER("haps", &haps) LONG_PARAMETER_GROUP("Output Parameters") LONG_STRINGPARAMETER("prefix", &MyOutFormat.OutPrefix) LONG_PARAMETER("estimate" , &MyModelVariables.processReference) LONG_PARAMETER("nobgzip", &MyOutFormat.nobgzip) LONG_INTPARAMETER("vcfBuffer", &MyOutFormat.vcfBuffer) LONG_STRINGPARAMETER("format", &MyOutFormat.formatString) LONG_PARAMETER("allTypedSites", &MyOutFormat.TypedOnly) LONG_PARAMETER("meta", &MyOutFormat.meta) LONG_PARAMETER("memUsage", &MyOutFormat.memUsage) LONG_PARAMETER_GROUP("Chunking Parameters") LONG_DOUBLEPARAMETER("ChunkLengthMb", &MyHapDataVariables.ChunkLengthMb) LONG_DOUBLEPARAMETER("ChunkOverlapMb", &MyHapDataVariables.ChunkOverlapMb) LONG_PARAMETER_GROUP("Subset Parameters") LONG_STRINGPARAMETER("chr", &MyHapDataVariables.chr) LONG_INTPARAMETER("start", &MyHapDataVariables.start) LONG_INTPARAMETER("end", &MyHapDataVariables.end) LONG_INTPARAMETER("window", &MyHapDataVariables.window) //LONG_INTPARAMETER("block", &max_block) // LONG_PARAMETER_GROUP("Starting Parameters") // LONG_STRINGPARAMETER("rec", &recFile) // LONG_STRINGPARAMETER("err", &errFile) LONG_PARAMETER_GROUP("Approximation Parameters") // LONG_INTPARAMETER("rounds", &MyModelVariables.rounds) // LONG_INTPARAMETER("states", &MyModelVariables.states) LONG_PARAMETER("minimac3", &MyModelVariables.minimac3) LONG_DOUBLEPARAMETER("probThreshold", &MyModelVariables.probThreshold) LONG_DOUBLEPARAMETER("diffThreshold", &MyModelVariables.diffThreshold) LONG_DOUBLEPARAMETER("topThreshold", &MyModelVariables.topThreshold) LONG_PARAMETER_GROUP("Other Parameters") LONG_PARAMETER("log", &log) // LONG_PARAMETER("lowMemory", &MyModelVariables.lowMemory) LONG_PARAMETER("help", &help) LONG_INTPARAMETER("cpus", &MyModelVariables.cpus) LONG_PARAMETER("params", ¶ms) LONG_PHONEHOME(VERSION) BEGIN_LEGACY_PARAMETERS() LONG_STRINGPARAMETER("intermediate", &MyModelVariables.intermediate) LONG_PARAMETER("reEstimate", &MyModelVariables.reEstimate) LONG_DOUBLEPARAMETER("constantParam", &MyModelVariables.constantParam) LONG_INTPARAMETER("printBuffer", &MyOutFormat.PrintBuffer) LONG_PARAMETER("verbose", &MyOutFormat.verbose) LONG_DOUBLEPARAMETER("minRatioPercent", &MyHapDataVariables.minRatio) LONG_STRINGPARAMETER("MyChromosome", &MyHapDataVariables.MyChromosome) LONG_INTPARAMETER("ignoreDuplicates", &MyHapDataVariables.ignoreDuplicates) LONG_INTPARAMETER("transFactor", &MyModelVariables.transFactor) LONG_INTPARAMETER("cisFactor", &MyModelVariables.cisFactor) LONG_PARAMETER("allowRefDuplicates", &MyHapDataVariables.allowRefDuplicates) LONG_PARAMETER("unphasedOutput", &MyOutFormat.unphasedOutput) LONG_PARAMETER("longZero", &MyOutFormat.longZero) END_LONG_PARAMETERS(); //MyHapDataVariables.GetMapFileLocation(argc,argv); MyOutFormat.CreateCommandLine(argc,argv); inputParameters.Add(new LongParameters(" Command Line Options: ",longParameterList)); String compStatus; inputParameters.Read(argc, &(argv[0])); FILE *LogFile=NULL; if(log) LogFile=freopen(MyOutFormat.OutPrefix+".logfile","w",stdout); dup2(fileno(stdout), fileno(stderr)); Minimac4Version(); if (help) { helpFile(); return(-1); } inputParameters.Status(); int start_time = time(0); Analysis MyAnalysis; String MySuccessStatus="Error"; // MySuccessStatus = MyAnalysis.AnalyzeExperiment(refHaps, haps, recFile, errFile, MyAllVariable); if(MySuccessStatus!="Success") { compStatus=MySuccessStatus; PhoneHome::completionStatus(compStatus.c_str()); return(-1); } int time_tot = time(0) - start_time; cout << "\n Program Successfully Implemented... \n "; printf("\n Total Run completed in %d hours, %d mins, %d seconds.\n", time_tot / 3600, (time_tot % 3600) / 60, time_tot % 60); cout<<"\n Thank You for using Minimac4 !!! "< for detailed documentation ...\n\n"); cout<ReducedStructureInfo[group]; vector &alleleFreq=rHap->AlleleFreq; vector > &Leftprob =leftProb[group]; int &Start=Info.startIndex; int &End=Info.endIndex; noReducedStatesCurrent=Info.RepSize; for (int markerPos=Start+1; markerPos<=End; markerPos++) { LeftPrecisionJump[markerPos]=LeftTranspose(Leftprob[markerPos-Start-1], Leftprob[markerPos-Start],CurrentLeftNoRecoProb, Recom[markerPos-1],Info.uniqueCardinality); if (tHap->RetrieveMissingScaffoldedHaplotype(hapID,markerPos)=='0') { LeftCondition(markerPos,Leftprob[markerPos-Start], CurrentLeftNoRecoProb, tHap->RetrieveScaffoldedHaplotype(hapID,markerPos), Error[markerPos], tHap->RetrieveScaffoldedHaplotype(hapID,markerPos)=='1'? alleleFreq[markerPos] : 1-alleleFreq[markerPos],Info); } } } void MarkovModel::WalkLeftMinimac3(int &hapID, int group) { ReducedHaplotypeInfo &Info=rHap->ReducedStructureInfo[group]; vector &alleleFreq=rHap->AlleleFreq; vector > &Leftprob =leftProb[group]; int &Start=Info.startIndex; int &End=Info.endIndex; noReducedStatesCurrent=Info.RepSize; for (int markerPos=Start+1; markerPos<=End; markerPos++) { LeftPrecisionJump[markerPos]=LeftTranspose(Leftprob[markerPos-Start-1], Leftprob[markerPos-Start],CurrentLeftNoRecoProb, Recom[markerPos-1],Info.uniqueCardinality); int TargetMarkerPosition = rHap->MapRefToTar[markerPos]; if (TargetMarkerPosition!=-1 && tHap->RetrieveMissingScaffoldedHaplotype(hapID,TargetMarkerPosition)=='0') { LeftCondition(markerPos,Leftprob[markerPos-Start], CurrentLeftNoRecoProb, tHap->RetrieveScaffoldedHaplotype(hapID,TargetMarkerPosition), Error[markerPos], tHap->RetrieveScaffoldedHaplotype(hapID,TargetMarkerPosition)=='1'? alleleFreq[markerPos] : 1-alleleFreq[markerPos],Info); } } } void MarkovModel::ImputeSitesMinimac3(int hapID,int group) { vector &juncLeftprob = junctionLeftProb[group]; vector &juncRightProb = PrevjunctionRightProb; ReducedHaplotypeInfo &Info=rHap->ReducedStructureInfo[group]; vector &alleleFreq=rHap->AlleleFreq; ReCreateLeftNoRecoProbMinimac3(*tHap,hapID,group,Info,alleleFreq); vector > &Leftprob = leftProb[group]; vector > &leftNoRecomProb= ThisBlockLeftNoRecoProb; int startIndex=Info.startIndex; int endIndex=Info.endIndex; PrevRightFoldedProb = ThisBlockRightProb[endIndex-startIndex]; ThisBlockRightNoRecoProb[endIndex-startIndex] = ThisBlockRightProb[endIndex-startIndex]; noReducedStatesCurrent=Info.RepSize; fill(Constants.begin(), Constants.end(), 0.0); for(int i=0;istartIndex; markerPos--) { int TargetMarkerPosition = rHap->MapRefToTar[markerPos+1]; if (TargetMarkerPosition!=-1 && tHap->RetrieveMissingScaffoldedHaplotype(hapID, TargetMarkerPosition)=='0') { RightCondition(markerPos+1,ThisBlockRightProb[markerPos-startIndex+1], ThisBlockRightProb[markerPos-startIndex], ThisBlockRightNoRecoProb[markerPos-startIndex+1], ThisBlockRightNoRecoProb[markerPos-startIndex], tHap->RetrieveScaffoldedHaplotype(hapID, TargetMarkerPosition), Error[markerPos+1], tHap->RetrieveScaffoldedHaplotype(hapID, TargetMarkerPosition)=='1'? alleleFreq[markerPos+1] : 1-alleleFreq[markerPos+1],Info); } else { ThisBlockRightProb[markerPos-startIndex]= ThisBlockRightProb[markerPos-startIndex+1]; ThisBlockRightNoRecoProb[markerPos-startIndex]= ThisBlockRightNoRecoProb[markerPos-startIndex+1]; } RightPrecisionJump[markerPos] = RightTranspose(ThisBlockRightProb[markerPos-startIndex], ThisBlockRightNoRecoProb[markerPos-startIndex], Recom[markerPos], Info.uniqueCardinality); ImputeChunkMinimac3(group, hapID, markerPos, Leftprob[markerPos-startIndex], ThisBlockRightProb[markerPos-startIndex], leftNoRecomProb[markerPos-startIndex], ThisBlockRightNoRecoProb[markerPos-startIndex], Leftprob[0],PrevRightFoldedProb); } int TargetMarkerPosition = rHap->MapRefToTar[startIndex+1]; if (TargetMarkerPosition!=-1 && tHap->RetrieveMissingScaffoldedHaplotype(hapID,TargetMarkerPosition)=='0') { RightCondition(startIndex+1, ThisBlockRightProb[1], ThisBlockRightProb[0], ThisBlockRightNoRecoProb[1], ThisBlockRightNoRecoProb[0], tHap->RetrieveScaffoldedHaplotype(hapID, TargetMarkerPosition), Error[startIndex+1], tHap->RetrieveScaffoldedHaplotype(hapID, TargetMarkerPosition)=='1'? alleleFreq[startIndex+1] : 1-alleleFreq[startIndex+1],Info); } else { ThisBlockRightProb[0]= ThisBlockRightProb[1]; ThisBlockRightNoRecoProb[0]= ThisBlockRightNoRecoProb[1]; } RightPrecisionJump[startIndex] = RightTranspose(ThisBlockRightProb[0], ThisBlockRightNoRecoProb[0],Recom[startIndex], Info.uniqueCardinality); if(startIndex==0) { ImputeChunkMinimac3(group, hapID, startIndex, Leftprob[startIndex-startIndex], ThisBlockRightProb[startIndex-startIndex], leftNoRecomProb[startIndex-startIndex],ThisBlockRightNoRecoProb[0], Leftprob[0],PrevRightFoldedProb); } } void MarkovModel::ImputeChunkMinimac3( int group, int hapID, int position, vector &Leftprob,vector &rightProb, vector &leftNoRecoProb,vector &rightNoRecoProb, vector &leftEndProb,vector &rightEndProb) { ReducedHaplotypeInfo &Info=rHap->ReducedStructureInfo[group]; vector &alleleFreq=rHap->AlleleFreq; float Pref=0.0,Palt=0.0,ptotal; double tempVal; vector &TempHap = Info.TransposedUniqueHaps[position-Info.startIndex]; CurrentObsMissing=tHap->RetrieveMissingScaffoldedHaplotype(hapID,rHap->MapRefToTar[position]); CurrentObs=tHap->RetrieveScaffoldedHaplotype(hapID,rHap->MapRefToTar[position]); for(int i=0; i0.0f); if(CurrentObsMissing=='0') { double Err=Error[position]; double freq=CurrentObs == '1' ? alleleFreq[position] : 1-alleleFreq[position]; double fmatch = 1.0 / ( (1.0 - Err) + Err*freq + backgroundError); double fmismatch = 1.0 / (Err * freq + backgroundError); if(CurrentObs == '1') { Palt *= fmatch; Pref *= fmismatch; } else { Pref *= fmatch; Palt *= fmismatch; } ptotal =Pref+Palt; (*LooDosageHap)[rHap->MapRefToTar[position]] = (Palt / ptotal); } } void MarkovModel::ImputeSites(int hapID,int group) { vector &juncLeftprob = junctionLeftProb[group]; vector &juncRightProb = PrevjunctionRightProb; ReducedHaplotypeInfo &Info=rHap->ReducedStructureInfo[group]; vector &alleleFreq=rHap->AlleleFreq; ReCreateLeftNoRecoProb(*tHap,hapID,group,Info,alleleFreq); vector > &Leftprob = leftProb[group]; vector > &leftNoRecomProb= ThisBlockLeftNoRecoProb; int startIndex=Info.startIndex; int endIndex=Info.endIndex; PrevRightFoldedProb = ThisBlockRightProb[endIndex-startIndex]; ThisBlockRightNoRecoProb[endIndex-startIndex] = ThisBlockRightProb[endIndex-startIndex]; noReducedStatesCurrent=Info.RepSize; NoSitesToUnfold=0; MostProbableTemplate=-1; fill(Constants.begin(), Constants.end(), 0.0); for(int i=0;istartIndex; markerPos--) { if (tHap->RetrieveMissingScaffoldedHaplotype(hapID,markerPos+1)=='0') { RightCondition(markerPos+1,ThisBlockRightProb[markerPos-startIndex+1], ThisBlockRightProb[markerPos-startIndex], ThisBlockRightNoRecoProb[markerPos-startIndex+1], ThisBlockRightNoRecoProb[markerPos-startIndex], tHap->RetrieveScaffoldedHaplotype(hapID,markerPos+1), Error[markerPos+1], tHap->RetrieveScaffoldedHaplotype(hapID,markerPos+1)=='1'? alleleFreq[markerPos+1] : 1-alleleFreq[markerPos+1],Info); } else { ThisBlockRightProb[markerPos-startIndex]= ThisBlockRightProb[markerPos-startIndex+1]; ThisBlockRightNoRecoProb[markerPos-startIndex]= ThisBlockRightNoRecoProb[markerPos-startIndex+1]; } RightPrecisionJump[markerPos] = RightTranspose(ThisBlockRightProb[markerPos-startIndex], ThisBlockRightNoRecoProb[markerPos-startIndex], Recom[markerPos], Info.uniqueCardinality); ImputeChunk(group, hapID, markerPos, Leftprob[markerPos-startIndex], ThisBlockRightProb[markerPos-startIndex], leftNoRecomProb[markerPos-startIndex], ThisBlockRightNoRecoProb[markerPos-startIndex], Leftprob[0],PrevRightFoldedProb); } if (tHap->RetrieveMissingScaffoldedHaplotype(hapID,startIndex+1)=='0') { RightCondition(startIndex+1, ThisBlockRightProb[1], ThisBlockRightProb[0], ThisBlockRightNoRecoProb[1], ThisBlockRightNoRecoProb[0], tHap->RetrieveScaffoldedHaplotype(hapID,startIndex+1), Error[startIndex+1], tHap->RetrieveScaffoldedHaplotype(hapID,startIndex+1)=='1'? alleleFreq[startIndex+1] : 1-alleleFreq[startIndex+1],Info); } else { ThisBlockRightProb[0]= ThisBlockRightProb[1]; ThisBlockRightNoRecoProb[0]= ThisBlockRightNoRecoProb[1]; } RightPrecisionJump[startIndex] = RightTranspose(ThisBlockRightProb[0], ThisBlockRightNoRecoProb[0],Recom[startIndex], Info.uniqueCardinality); if(startIndex==0) { ImputeChunk(group, hapID, startIndex, Leftprob[startIndex-startIndex], ThisBlockRightProb[startIndex-startIndex], leftNoRecomProb[startIndex-startIndex],ThisBlockRightNoRecoProb[0], Leftprob[0],PrevRightFoldedProb); } } void MarkovModel::ImputeChunk(int group, int &hapID, int &position, vector &Leftprob,vector &rightProb, vector &leftNoRecoProb,vector &rightNoRecoProb, vector &leftEndProb,vector &rightEndProb) { ReducedHaplotypeInfo &Info=rHap->ReducedStructureInfo[group]; int startIndex=Info.startIndex; CurrentTypedSite=rHapFull->MapTarToRef[position]; CurrentObsMissing=tHap->RetrieveMissingScaffoldedHaplotype(hapID,position); CurrentObs=tHap->RetrieveScaffoldedHaplotype(hapID,position); FindPosteriorProbWithThreshold( group, position, Leftprob, rightProb, leftNoRecoProb,rightNoRecoProb, leftEndProb,rightEndProb); UnfoldTheseSites[NoSitesToUnfold++]=position; vector > &ThisLeftprob = leftProb[group]; int StartPoint=0, EndPoint=-1; if( (position==(rHap->ReducedStructureInfo[group].startIndex+1) && position!=1) || (position == 0) ) { EndPoint = NoSitesToUnfold - 1; } else if (KeepMovingLeft==0) { EndPoint = NoSitesToUnfold-2; } if(EndPoint>-1) { MidPoint = (UnfoldTheseSites[StartPoint] + UnfoldTheseSites[EndPoint])/2 - startIndex ; unfoldProbabilitiesWithThreshold(group, ThisBlockLeftNoRecoProb[MidPoint], ThisLeftprob[MidPoint], ThisBlockRightNoRecoProb[MidPoint], ThisBlockRightProb[MidPoint], leftEndProb, rightEndProb); for(int i=EndPoint;i>=StartPoint;i--) { int tempPosition = UnfoldTheseSites[i]; CurrentTypedSite=rHapFull->MapTarToRef[tempPosition]; ImputeRemainingSitesbyBlock( group, tempPosition, tHapFull->FlankRegionStart[tempPosition], CurrentTypedSite-1); ImputeRemainingSitesbyBlock( group, tempPosition, CurrentTypedSite+1, tHapFull->FlankRegionEnd[tempPosition]); } UnfoldTheseSites[StartPoint]=UnfoldTheseSites[EndPoint+1]; NoSitesToUnfold=1; return; } else if(MyAllVariables->myOutFormat.verbose) { cout<<" SKIPPED A SITE "< &Leftprob,vector &rightProb, vector &leftNoRecoProb,vector &rightNoRecoProb, vector &leftEndProb,vector &rightEndProb) { ReducedHaplotypeInfo &Info=rHap->ReducedStructureInfo[group]; vector &probHap = probHapMatrix[position-Info.startIndex]; vector &alleleFreq=rHap->AlleleFreq; float Pref=0.0,Palt=0.0,ptotal; double tempVal; vector &TempHap = Info.TransposedUniqueHaps[position-Info.startIndex]; if(LeftPrecisionJump[position+1]) InvPrevTotalSum*=JumpFix; if(RightPrecisionJump[position]) InvPrevTotalSum/=JumpFix; SumOfProb[position-Info.startIndex]=InvPrevTotalSum; if(MostProbableTemplate!=-1 && MostProbableTemplateVal > (1-MyAllVariables->myModelVariables.topThreshold) ) { int i=MostProbableTemplate; fill(probHap.begin(), probHap.end(), 0); probHap[i] = Constants[i]*(leftNoRecoProb[i]*rightNoRecoProb[i]/(leftEndProb[i]*rightEndProb[i]+1e-30)) +(Leftprob[i]*rightProb[i]-leftNoRecoProb[i]*rightNoRecoProb[i])*(Info.InvuniqueCardinality[i]); tempVal=probHap[i]*InvPrevTotalSum; if(tempVal>(1-MyAllVariables->myModelVariables.topThreshold)) { AlleleType hp = TempHap[i]; if(hp=='1') { (*DosageHap)[CurrentTypedSite] = 1.0; if(CurrentObsMissing=='0') (*LooDosageHap)[position] = 1.0; } else { (*DosageHap)[CurrentTypedSite] = 0.0; if(CurrentObsMissing=='0') (*LooDosageHap)[position] = 0.0; } if(position>(Info.startIndex+1)) KeepMovingLeft=1; else { KeepMovingLeft=0; } return ; } } FirstDiffValue=0.0; KeepMovingLeft=0; for(int i=0; imyModelVariables.diffThreshold ) { if(position>(Info.startIndex+1)) KeepMovingLeft=1; else { KeepMovingLeft=0; } } if(KeepMovingLeft==0) { FirstFoldedValue = probHap; } for (int i=0; i0.0); assert(isnan(ptotal)==false); (*DosageHap)[CurrentTypedSite] = (Palt / ptotal); if(CurrentObsMissing=='0') { double Err=Error[position]; double freq=CurrentObs == '1' ? alleleFreq[position] : 1-alleleFreq[position]; double fmatch = 1.0 / ( (1.0 - Err) + Err*freq + backgroundError); double fmismatch = 1.0 / (Err * freq + backgroundError); if(CurrentObs == '1') { Palt *= fmatch; Pref *= fmismatch; } else { Pref *= fmatch; Palt *= fmismatch; } ptotal =Pref+Palt; (*LooDosageHap)[position] = (Palt / ptotal); } MostProbableTemplateVal=0.0; for (int i=0; iMostProbableTemplateVal) { MostProbableTemplateVal=tempVal; MostProbableTemplate=i; } } MostProbableTemplateVal*=InvPrevTotalSum; // if(MyAllVariables->myModelVariables.probThreshold>0.0) // { //// sum=1.0/sum; // int Index=0; // NoBestMatchHaps=0; // for (int i=0; i= MyAllVariables->myModelVariables.probThreshold) // { // BestMatchHaps[Index++]=i; // NoBestMatchHaps++; // } // } // } } void MarkovModel::unfoldProbabilitiesWithThreshold(int bridgeIndex, vector &LeftNoRecomProb, vector &LeftTotalProb, vector &RightNoRecomProb, vector &RightTotalProb, vector &PrevLeftFoldedProb, vector &PrevRightFoldedProb) { vector &probHap = probHapMatrix[MidPoint]; double tempInvSum = SumOfProb[MidPoint]; double maxVal = 0.0, sum = 0.0; if(!MyAllVariables->myOutFormat.verbose) { int Index=0; NoBestMatchHaps=0; for (int i=0; i= MyAllVariables->myModelVariables.probThreshold) { BestMatchHaps[Index++]=i; NoBestMatchHaps++; } } if(NoBestMatchHaps==0) { NoBestMatchHaps=noReducedStatesCurrent; for (int i=0; imyOutFormat.verbose) { int Index=0; NoBestMatchHaps=0; sum = 0.0; for (int i=0; i= MyAllVariables->myModelVariables.probThreshold) { sum+=tempVal; BestMatchHaps[Index++]=i; NoBestMatchHaps++; } } cout<<" No_Best_MatchHaps = "<ReducedStructureInfo[bridgeIndex]; NoBestMatchFullRefHaps=0; double temp,tempInvCardinality; int i; for (int index=0; index &LeftPrev=junctionLeftProb[bridgeIndex]; vector &RightPrev=PrevjunctionRightProb; int UnMappedIndex; for (int index=0; indexmaxRepSize; i++) { if(FinalBestMatchfHapsIndicator[i]==1) FinalBestMatchfHaps[noNewReducedStates++]=i; } } void MarkovModel::ImputeRemainingSitesbyBlock(int bridgeIndex, int TypedMarkerId, int StartPos, int EndPos) { for(int position=StartPos;position<=EndPos;) { int NewBlockIndex=rHapFull->MarkerToReducedInfoMapper[position]; ReducedHaplotypeInfo &Info=rHapFull->ReducedStructureInfo[NewBlockIndex]; int TempEndPos= EndPos &ThisMapped=Info.TransposedUniqueHaps[tempPosition-ThisStartIndex]; double tempPALT = 0.0; for (int i=0; i< noNewReducedStates;i++) { MappedIndex=FinalBestMatchfHaps[i]; assert(FoldedProbValue[MappedIndex]>=0.0f); if(ThisMapped[MappedIndex] == '1') tempPALT+=FoldedProbValue[MappedIndex]; } (*DosageHap)[tempPosition] = min(1.0,(tempPALT * tempInvSum)); } } void MarkovModel::initializeMatricesMinimac3() { // Left Probabilities Initialize (NO NEED TO RE-INITIALIZE) leftProb.resize(rHap->NoBlocks); for(int i=0;iNoBlocks;i++) { vector > &TempLeft=leftProb[i]; TempLeft.resize(rHap->maxBlockSize); for(int j=0;jmaxBlockSize;j++) { TempLeft[j].resize(rHap->maxRepSize); } } // Left No Recom Probabilities Initialize (NO NEED TO RE-INITIALIZE) CurrentLeftNoRecoProb.resize(rHap->maxRepSize); ThisBlockLeftNoRecoProb.resize(rHap->maxBlockSize); ThisBlockRightNoRecoProb.resize(rHap->maxBlockSize); probHapMatrix.resize(rHap->maxBlockSize); ThisBlockRightProb.resize(rHap->maxBlockSize); PrevRightFoldedProb.resize(rHap->maxRepSize); SumOfProb.resize(rHap->maxBlockSize); probHapMinimac3.resize(rHap->maxRepSize); for(int i=0;imaxBlockSize;i++) { ThisBlockLeftNoRecoProb[i].resize(rHap->maxRepSize); ThisBlockRightNoRecoProb[i].resize(rHap->maxRepSize); ThisBlockRightProb[i].resize(rHap->maxRepSize); probHapMatrix[i].resize(rHap->maxRepSize); } // Junction Probabilities Initialize (ONLY junctionLeftProb[0] and // PrevjunctionRightProb nneds to be re-initialized. DONE junctionLeftProb.resize(rHap->NoBlocks+1); PrevjunctionRightProb.resize(rHap->numHaplotypes); for(int i=0;i<=rHap->NoBlocks;i++) { junctionLeftProb[i].resize(rHap->numHaplotypes); } // Other Variables Initialize (NO NEED TO RE-INITIALIZE Constants.resize(rHap->maxRepSize); LeftPrecisionJump.resize(rHap->numMarkers+1); // RE-INTIALIZE DONE RightPrecisionJump.resize(rHap->numMarkers); // RE-INTIALIZE DONE // Full Dimension Variable Initialize (NO NEED TO REINITLAIZE) } void MarkovModel::initializeMatrices() { // Left Probabilities Initialize (NO NEED TO RE-INITIALIZE) leftProb.resize(rHap->NoBlocks); for(int i=0;iNoBlocks;i++) { vector > &TempLeft=leftProb[i]; TempLeft.resize(rHap->maxBlockSize); for(int j=0;jmaxBlockSize;j++) { TempLeft[j].resize(rHap->maxRepSize); } } // Left No Recom Probabilities Initialize (NO NEED TO RE-INITIALIZE) CurrentLeftNoRecoProb.resize(rHap->maxRepSize); ThisBlockLeftNoRecoProb.resize(rHap->maxBlockSize); ThisBlockRightNoRecoProb.resize(rHap->maxBlockSize); probHapMatrix.resize(rHap->maxBlockSize); ThisBlockRightProb.resize(rHap->maxBlockSize); PrevRightFoldedProb.resize(rHap->maxRepSize); SumOfProb.resize(rHap->maxBlockSize); for(int i=0;imaxBlockSize;i++) { ThisBlockLeftNoRecoProb[i].resize(rHap->maxRepSize); ThisBlockRightNoRecoProb[i].resize(rHap->maxRepSize); ThisBlockRightProb[i].resize(rHap->maxRepSize); probHapMatrix[i].resize(rHap->maxRepSize); } // Junction Probabilities Initialize (ONLY junctionLeftProb[0] and // PrevjunctionRightProb nneds to be re-initialized. DONE junctionLeftProb.resize(rHap->NoBlocks+1); PrevjunctionRightProb.resize(rHap->numHaplotypes); for(int i=0;i<=rHap->NoBlocks;i++) { junctionLeftProb[i].resize(rHap->numHaplotypes); } // Other Variables Initialize (NO NEED TO RE-INITIALIZE Constants.resize(rHap->maxRepSize); LeftPrecisionJump.resize(rHap->numMarkers+1); // RE-INTIALIZE DONE RightPrecisionJump.resize(rHap->numMarkers); // RE-INTIALIZE DONE // Full Dimension Variable Initialize (NO NEED TO REINITLAIZE) FoldedProbValue.resize(rHapFull->maxRepSize); probHapFullAverage.resize(rHapFull->numHaplotypes); FirstFoldedValue.resize(rHap->maxRepSize); UnfoldTheseSites.resize(rHap->maxBlockSize); LeftAdj_Rec.resize(rHap->maxRepSize); LeftAdj_NoRrec.resize(rHap->maxRepSize); RightAdj_Rec.resize(rHap->maxRepSize); RightAdj_NoRec.resize(rHap->maxRepSize); FinalBestMatchfHaps.resize(rHapFull->maxRepSize); FinalBestMatchfHapsIndicator.resize(rHapFull->maxRepSize); BestMatchHaps.resize(rHap->maxRepSize); BestMatchFullRefHaps.resize(refCount); } void MarkovModel::ReinitializeMatrices() { NoPrecisionJumps=0; PrevTotalSum=-1.0; fill(LeftPrecisionJump.begin(), LeftPrecisionJump.end(), false); fill(RightPrecisionJump.begin(), RightPrecisionJump.end(), false); fill(junctionLeftProb[0].begin(), junctionLeftProb[0].end(), 1.0); fill(PrevjunctionRightProb.begin(), PrevjunctionRightProb.end(), 1.0); } void MarkovModel::ReCreateLeftNoRecoProb(HaplotypeSet &tHap, int &hapID, int group, ReducedHaplotypeInfo &Info, vector &alleleFreq) { int &Start=Info.startIndex; int &End=Info.endIndex; noReducedStatesCurrent=Info.RepSize; ThisBlockLeftNoRecoProb[0]=leftProb[group][0]; for (int markerPos=Start+1; markerPos<=End; markerPos++) { vector &NextnoRecomProb = ThisBlockLeftNoRecoProb[markerPos-Start]; double complement = 1. - Recom[markerPos-1]; NextnoRecomProb=ThisBlockLeftNoRecoProb[markerPos-Start-1]; for (int i = 0; i &TempHap = Info.TransposedUniqueHaps[markerPos-Info.startIndex]; for (int i = 0; i &alleleFreq) { int &Start=Info.startIndex; int &End=Info.endIndex; noReducedStatesCurrent=Info.RepSize; ThisBlockLeftNoRecoProb[0]=leftProb[group][0]; for (int markerPos=Start+1; markerPos<=End; markerPos++) { vector &NextnoRecomProb = ThisBlockLeftNoRecoProb[markerPos-Start]; double complement = 1. - Recom[markerPos-1]; NextnoRecomProb=ThisBlockLeftNoRecoProb[markerPos-Start-1]; int TargetMarkerPosition = rHap->MapRefToTar[markerPos]; for (int i = 0; i &TempHap = Info.TransposedUniqueHaps[markerPos-Info.startIndex]; for (int i = 0; i &foldProb,int bridgeIndex,ReducedHaplotypeInfo &Info,int direction,int noReference) //0 - left; 1 - right { vector *TempuniqueIndexMap=&Info.uniqueIndexMap; fill(foldProb.begin(), foldProb.end(), 0.0); if(direction==0) { vector *PrevjunctionLeftProb=&junctionLeftProb[bridgeIndex]; for(int i=0;i=0.0f); } } else if(direction==1) { for(int i=0;i=0.0f); assert(PrevjunctionRightProb[i]<1e18); assert(foldProb[(*TempuniqueIndexMap)[i]]>0.0f); assert(foldProb[(*TempuniqueIndexMap)[i]]<1e18); } } } void MarkovModel::unfoldProbabilities(int bridgeIndex,vector &recomProb, vector &noRecomProb,vector &PrevFoldedProb, int direction,vector &StructureInfo, int noReference) { ReducedHaplotypeInfo &thisInfo = StructureInfo[bridgeIndex]; int N = thisInfo.RepSize; vector adj_rec(N), adj_norec(N); for (int i=0; i=0.0f); assert(adj_norec[i]>=0.0f); assert(adj_norec[i]<1e18); } vector &prev = direction ? PrevjunctionRightProb : junctionLeftProb[bridgeIndex]; vector &next = direction ? PrevjunctionRightProb : junctionLeftProb[bridgeIndex+1]; if(direction) { //double min=adj_rec[thisInfo.uniqueIndexMap[0]] + adj_norec[thisInfo.uniqueIndexMap[0]]*prev[0], max=0.0, sum=0.0; for (int i=0; imax) // max=prev[i]; // if(prev[i]=0.0f); assert(prev[i]<1e18); } // cout<<" RIGHT MIN = "< > > leftProb; vector > ThisBlockLeftNoRecoProb ; vector CurrentLeftNoRecoProb; // Right Probabilities vector > ThisBlockRightProb; vector > ThisBlockRightNoRecoProb ; vector PrevRightFoldedProb; // Final Probability Matrix vector > probHapMatrix; vector SumOfProb; vector probHapMinimac3; // Junction Probabilities vector > junctionLeftProb; vector PrevjunctionRightProb; // UnfoldingWithThreshold Variables vector LeftAdj_Rec; vector LeftAdj_NoRrec; vector RightAdj_Rec; vector RightAdj_NoRec; // Variables for Successive Differences vector FirstFoldedValue; double FirstDiffValue; int KeepMovingLeft; vector UnfoldTheseSites; int NoSitesToUnfold; // Best Match Haplotypes vector BestMatchHaps, BestMatchFullRefHaps, FinalBestMatchfHaps; int NoBestMatchHaps, NoBestMatchFullRefHaps, noNewReducedStates; vector FinalBestMatchfHapsIndicator; // Final Best Batch Folded Probabilities for Dosage vector FoldedProbValue; vector probHapFullAverage; vector *DosageHap, *LooDosageHap; // Precision Jump Variables vector LeftPrecisionJump, RightPrecisionJump; int NoPrecisionJumps; float JumpThreshHold; float JumpFix; // Current Variables for Support AlleleType CurrentObsMissing, CurrentObs; int CurrentTypedSite; // Sum Variables for Support double PrevTotalSum,InvPrevTotalSum; // Other Variables for Support vector Constants; int MidPoint; bool LowMemory; double backgroundError; double tempMaxVal; int MostProbableTemplate; double MostProbableTemplateVal; void CeateProbSum (int bridgeIndex, int noReference); void RightCondition (int markerPos,vector &FromProb,vector &ToProb, vector &FromNoRecomProb, vector &ToNoRecomProb, AlleleType observed,double e,double freq,ReducedHaplotypeInfo &Info); bool RightTranspose (vector &fromTo, vector &noRecomProb, double reco,vector &uniqueCardinality); bool LeftTranspose (vector &from,vector &to, vector &noRecomProb, double reco,vector &uniqueCardinality); void LeftCondition (int markerPos,vector &Prob, vector &noRecomProb, AlleleType observed,double e,double freq,ReducedHaplotypeInfo &Info); void ImputeSitesMinimac3 (int hapID,int group); void ImputeChunkMinimac3 ( int group, int hapID, int position, vector &Leftprob,vector &rightProb, vector &leftNoRecoProb,vector &rightNoRecoProb, vector &leftEndProb,vector &rightEndProb); void ImputeSites (int hapID,int group); void WalkLeft (int &hapID, int group); void WalkLeftMinimac3 (int &hapID, int group); void ImputeChunk (int group, int &hapID, int &position, vector &Leftprob,vector &rightProb, vector &leftNoRecoProb,vector &rightNoRecoProb, vector &leftEndProb,vector &rightEndProb); void FindPosteriorProbWithThreshold (int group,int position, vector &Leftprob,vector &rightProb, vector &leftNoRecoProb,vector &rightNoRecoProb, vector &leftEndProb,vector &rightEndProb); void unfoldProbabilitiesWithThreshold(int bridgeIndex, vector &LeftNoRecomProb, vector &LeftTotalProb, vector &RightNoRecomProb, vector &RightTotalProb, vector &PrevLeftFoldedProb, vector &PrevRightFoldedProb); void unfoldProbabilitiesAllProb (int bridgeIndex, vector &LeftNoRecomProb, vector &LeftTotalProb, vector &RightNoRecomProb, vector &RightTotalProb, vector &PrevLeftFoldedProb, vector &PrevRightFoldedProb); void FoldBackProbabilitiesWithThreshold(ReducedHaplotypeInfo &Info); void FoldBackProbabilitiesAllProb (ReducedHaplotypeInfo &Info, ReducedHaplotypeInfo &TarInfo); void ImputeRemainingSitesbyBlock (int bridgeIndex, int TypedMarkerId, int StartPos, int EndPos); void ImputeIntermediateRegionFull (ReducedHaplotypeInfo &Info, int TypedMarkerId, int StartPos, int EndPos); void CreatePRefPAlt (ReducedHaplotypeInfo &Info, int StartPos, int EndPos); void CreateDosages (int TypedMarkerId, int StartPos, int EndPos); void CreateLooDosage (int &StartPos, int &TypedMarkerId, bool &observedMiss, bool &observed); void initializeMatricesMinimac3 (); void initializeMatrices (); void ReinitializeMatrices (); void foldProbabilities (vector &foldProb,int bridgeIndex,ReducedHaplotypeInfo &Info, int direction,int noReference); void unfoldProbabilities (int bridgeIndex,vector &recomProb, vector &noRecomProb, vector &PrevFoldedProb,int direction, vector &StructureInfo,int noReference); void ReCreateLeftNoRecoProb (HaplotypeSet &tHap, int &hapID, int group, ReducedHaplotypeInfo &Info, vector &alleleFreq); void ReCreateLeftNoRecoProbMinimac3 (HaplotypeSet &tHap, int &hapID, int group, ReducedHaplotypeInfo &Info, vector &alleleFreq); int Myfind (vector &MyVector, int Value); MarkovModel () { }; ~MarkovModel () { }; MarkovModel (const MarkovModel &L) { }; void AssignPanels (HaplotypeSet &refFullHap,HaplotypeSet &refChipHap, HaplotypeSet &tarFullHap,HaplotypeSet &tarChipHap, AllVariable *MyAllVariable) { MyAllVariables=MyAllVariable; rHapFull=&refFullHap; rHap=&refChipHap; tHapFull=&tarFullHap; tHap=&tarChipHap; refCount=rHapFull->numHaplotypes; tarCount=tHapFull->numHaplotypes; NoRefMarkers=rHapFull->numMarkers; NoChipSites=rHap->numMarkers; backgroundError = 1e-5; JumpThreshHold = 1e-20; JumpFix = 1e10; }; void AssignPanels (HaplotypeSet &refFullHap, HaplotypeSet &tarFullHap, AllVariable *MyAllVariable) { MyAllVariables=MyAllVariable; rHap=&refFullHap; tHap=&tarFullHap; refCount=rHap->numHaplotypes; tarCount=tHap->numHaplotypes; NoRefMarkers=rHap->numMarkers; NoChipSites=tHap->numMarkers; backgroundError = 1e-5; }; void AssignPanels (HaplotypeSet &refFullHap, AllVariable *MyAllVariable) { MyAllVariables=MyAllVariable; rHap=&refFullHap; refCount=rHap->numHaplotypes; NoRefMarkers=rHap->numMarkers; NoChipSites=rHap->numMarkers; backgroundError = 1e-5; }; void CountExpected (int hapID,int group); void CreatePosteriorProb (vector &Leftprob,vector &rightProb, vector &leftNoRecoProb,vector &rightNoRecoProb, vector &leftEndProb,vector &rightEndProb, ReducedHaplotypeInfo &Info); double CountRecombinants (vector &from, vector &to, double r,bool PrecisionMultiply); double CountErrors (int markerPos, AlleleType observed, double e,double freq, ReducedHaplotypeInfo &Info); double size() { double S=0; S+=(2*LeftPrecisionJump.size() * sizeof(bool)); S+=BestMatchHaps.size() * sizeof(int); S+=BestMatchFullRefHaps.size() * sizeof(int); S+=FinalBestMatchfHaps.size() * sizeof(int); S+=FinalBestMatchfHapsIndicator.size() * sizeof(int); S+=FirstFoldedValue.size() * sizeof(double); S+=UnfoldTheseSites.size() * sizeof(int); S+=PrevRightFoldedProb.size() * sizeof(float); S+=Constants.size() * sizeof(float); S+=PrevjunctionRightProb.size() * sizeof(float); S+=CurrentLeftNoRecoProb.size() * sizeof(float); S+=FoldedProbValue.size() * sizeof(double); S+=probHapFullAverage.size() * sizeof(double); S+=LeftAdj_Rec.size() * sizeof(double); S+=LeftAdj_NoRrec.size() * sizeof(double); S+=RightAdj_Rec.size() * sizeof(double); S+=RightAdj_NoRec.size() * sizeof(double); S+=SumOfProb.size() * sizeof(double); for(int i=0;i<(int)leftProb.size();i++) { for(int j=0;j<(int)leftProb[i].size();j++) { S+=leftProb[i][j].size() * sizeof(float); } } for(int i=0;i<(int)ThisBlockLeftNoRecoProb.size();i++) { S+=ThisBlockLeftNoRecoProb[i].size() * sizeof(float); } for(int i=0;i<(int)junctionLeftProb.size();i++) { S+=junctionLeftProb[i].size() * sizeof(float); } for(int i=0;i<(int)ThisBlockRightProb.size();i++) { S+=ThisBlockRightProb[i].size() * sizeof(float); } for(int i=0;i<(int)ThisBlockRightNoRecoProb.size();i++) { S+=ThisBlockRightNoRecoProb[i].size() * sizeof(float); } for(int i=0;i<(int)probHapMatrix.size();i++) { S+=probHapMatrix[i].size() * sizeof(double); } return (S); }; }; #endif Minimac4-1.0.2/src/MarkovParameters.cpp000066400000000000000000000171251353222426400177420ustar00rootroot00000000000000#include "MarkovParameters.h" using namespace std; // //void MarkovParameters::ScaffoldParameters(HaplotypeSet &rHap, HaplotypeSet &tHap,MarkovParameters FromParameters) //{ // // // // // for(int i=0;i<(int)tHap.numMarkers;i++) // { // // FromParameters.Error[i]=Error[tHap.UnScaffoldIndex[i]]; // // // // if(i>0) // { // int index=tHap.UnScaffoldIndex[i-1]; // // double temp=1.0; // while(index0) { char *end_str1; char * pch=strtok_r ((char*)line.c_str(),"\t", &end_str1);; pch = strtok_r (NULL, "\t", &end_str1); double val=atof(pch); if(val<0.0 || val > 1.0) { cout<<" Genotpying Error is outside boundary values [0.0 - 1.0] at position "<0) { char *end_str1; char * pch=strtok_r ((char*)line.c_str(),"\t", &end_str1);; pch = strtok_r (NULL, "\t", &end_str1); double val=atof(pch); if(val<0.0 || val > 1) { cout<<" Recombination Fraction is outside boundary values [0.0 - 1.0] at position "<noMarker) { cout<<"\n\n Run Time Error !!! Markov Parameters cannot be copied. Incosistent number of markers ...\n"; cout<<" Contact Author for more details ...\n"; cout<<" Program Exiting ...\n\n"; abort(); } empiricalCount=0; noMarker = rhs->noMarker; Recom = rhs->Recom; Error = rhs->Error; empError.resize(noMarker,0.0); empRecom.resize(noMarker-1,0.0); } void MarkovParameters::CopyParametersNew(MarkovParameters * rhs) { // if(noMarker!=rhs->noMarker) // { // cout<<"\n\n Run Time Error !!! Markov Parameters cannot be copied. Incosistent number of markers ...\n"; // cout<<" Contact Author for more details ...\n"; // cout<<" Program Exiting ...\n\n"; // abort(); // } // // empiricalCount=0; // noMarker = rhs->noMarker; Recom = rhs->Recom; Error = rhs->Error; // empError.resize(noMarker,0.0); // empRecom.resize(noMarker-1,0.0); } MarkovParameters & MarkovParameters::operator += (const MarkovParameters & rhs) { if(noMarker!=rhs.noMarker) { cout<<"\n\n Run Time Error !!! Markov Parameters cannot be copied. Incosistent number of markers ...\n"; cout<<" Contact Author for more details ...\n"; cout<<" Program Exiting ...\n\n"; abort(); } empiricalCount += rhs.empiricalCount; for (int i = 0; i < noMarker - 1; i++) { empError[i] += rhs.empError[i]; empRecom[i] += rhs.empRecom[i]; } empError[noMarker-1] += rhs.empError[noMarker-1]; return *this; } void MarkovParameters::WriteParameters(vector &markerNames,String prefix, bool gz) { String filename=prefix; WriteCrossoverRates(markerNames, filename + ".rec" + (gz ? ".gz" : "")); cout<<"\n Recombination Rates : "<< filename + ".rec" + (gz ? ".gz" : "")< & markerNames, const char * filename) { IFILE output = ifopen(filename, "wb"); if (output == NULL) return; ifprintf(output, "MarkerName\tErrorRate\n"); for (int i = 0; i < noMarker; i++) ifprintf(output, "%s\t%.5g\n", markerNames[i].c_str(), Error[i]); ifclose(output); } void MarkovParameters::WriteCrossoverRates(vector & markerNames, const char * filename) { IFILE output = ifopen(filename, "wb"); if (output == NULL) return; ifprintf(output, "Interval\tSwitchRate\n"); for (int i = 0; i < noMarker - 1; i++) ifprintf(output, "%s-%s\t%.5g\n", markerNames[i].c_str(), markerNames[i+1].c_str(), Recom[i]); ifclose(output); } void MarkovParameters::UpdateModel() { double scale = 1.0 /(double)empiricalCount; double backgroundR = 0.0; double backgroundE = 0.0; int backgroundEcount = 0, backgroundRcount = 0; for (int i = 0; i < noMarker ; i++) { if (empError[i] < 1.0) { backgroundE += empError[i]; backgroundEcount++; } if (i < noMarker - 1 && empRecom[i] < 2.0) { backgroundR += empRecom[i]; backgroundRcount++; } } backgroundR /= (double)empiricalCount * backgroundRcount + 1e-30; backgroundE /= (double)empiricalCount * backgroundEcount + 1e-30; for (int i = 0; i < noMarker - 1; i++) { Recom[i] = empRecom[i] >= 2.0 ? empRecom[i] * scale :backgroundR; Error[i] = empError[i] >= 1.0 ? empError[i] * scale : backgroundE; empError[i]=0.0; empRecom[i]=0.0; } Error[noMarker-1] = empError[noMarker-1] > 1.0 ? empError[noMarker-1] * scale : backgroundE; empError[noMarker-1] = 0; empiricalCount = 0; } Minimac4-1.0.2/src/MarkovParameters.h000066400000000000000000000046461353222426400174130ustar00rootroot00000000000000#ifndef __MARKOVPARAMETERS_H__ #define __MARKOVPARAMETERS_H__ #include "HaplotypeSet.h" #include "InputFile.h" #include #include #include #include #include "MathVector.h" #include "StringArray.h" using namespace std; class MarkovParameters { public: int noMarker; vector Recom,Error; // vector countError,countRecom; vector GWASRecom,GWASError; vector empError,empRecom; int empiricalCount; void CopyParameters(MarkovParameters * rhs); MarkovParameters & operator += (const MarkovParameters & rhs); void CopyParameters (MarkovParameters & rhs); void CopyParametersNew (MarkovParameters * rhs); void WriteParameters (vector &markerNames,String prefix, bool gz); void WriteErrorRates (vector & markerNames, const char * filename); void WriteCrossoverRates (vector & markerNames, const char * filename); void ReadErrorRates (String &filename); void ReadCrossoverRates (String &filename); void UpdateModel (); void ScaffoldParameters(HaplotypeSet &rHap, HaplotypeSet &tHap,MarkovParameters FromParameters); MarkovParameters() { empiricalCount=0; noMarker = 0; Recom.resize(0); Error.resize(0); empError.resize(0); empRecom.resize(0); }; MarkovParameters(int Markers) { empiricalCount=0; noMarker = Markers; Recom.resize(Markers-1,0.001); Error.resize(Markers,0.01); empError.resize(Markers,0.0); empRecom.resize(Markers-1,0.0); }; ~MarkovParameters() { }; }; #endif Minimac4-1.0.2/src/MyVariables.h000066400000000000000000000427631353222426400163500ustar00rootroot00000000000000#ifndef MY_VARIABLES_INCLUDED #define MY_VARIABLES_INCLUDED #include #include #include "StringBasics.h" #include #if defined(_OPENMP) #include #endif #include #include "assert.h" using namespace std; class OutputFormatVariable { public: int vcfBuffer; bool unphasedOutput; bool GT,DS,GP,HDS,SD; String OutPrefix; string CommandLine; char* MyCommandLine; string BinaryLocation; bool onlyrefmarkers; bool gzip,RsId,nobgzip,meta; // vector format; String formatString; String formatStringForVCF; bool verbose; int PrintBuffer; bool longZero; bool memUsage; bool vcfOutput,doseOutput,hapOutput,TypedOnly; bool CheckValidity() { string formatPiece,formatTemp=formatString.c_str(); char *end_str1; for(char * pch = strtok_r ((char*)formatTemp.c_str(),",", &end_str1); pch!=NULL; pch = strtok_r (NULL, ",", &end_str1)) { formatPiece=(string)pch; if(formatPiece.compare("GT")==0) { GT=true; } else if(formatPiece.compare("DS")==0) { DS=true; } else if(formatPiece.compare("GP")==0) { GP=true; } else if(formatPiece.compare("HDS")==0) { HDS=true; } else if(formatPiece.compare("SD")==0) { SD=true; } else { cout << " ERROR !!! \n Cannot identify handle for \"--format\" parameter : "<0.0) referenceEstimates=true; if(constantParam>=0.5) { cout << " ERROR !!! \n Invalid input for \"--constantParam\" = "<=1.0) { cout << " ERROR !!! \n Invalid input for \"--probThreshold\" = "<=1.0) { cout << " ERROR !!! \n Invalid input for \"--diffThreshold\" = "<=1.0) { cout << " ERROR !!! \n Invalid input for \"--topThreshold\" = "<300) { cout << " ERROR !!! \n Invalid input for \"--ChunkLengthMb\" = "<300) { cout << " ERROR !!! \n Invalid input for \"--ChunkOverlapMb\" = "<(ChunkLengthMb/3.0)) { ChunkOverlapMb=(ChunkLengthMb/3.0); cout<<" NOTE: By Default \"--ChunkLengthMb\" must be at least 3 times the \"--ChunkOverlapMb\" \n"; cout<<" Value of \"--ChunkOverlapMb\" reduced to = "<< ChunkOverlapMb <<"\n"; } if(minRatio<=0.0 || minRatio >= 1.0) { cout << " ERROR !!! \n Invalid input for \"--minRatio\" = "<0 && end> 0 && start>=end) { cout << " ERROR !!! \n Invalid Input !!!\n Value of \"--start\" must be less than value of \"--end\"."<0) { if(chr=="") { cout << "\n ERROR !!! \n Missing \"--chr\", a required parameter if using \"--start\" parameter.\n"; cout<<" Program Exiting ..."<0) { if(chr=="") { cout << "\n ERROR !!! \n Missing \"--chr\", a required parameter if using \"--end\" parameter.\n"; cout<<" Program Exiting ..."<0) { if(chr=="") { cout << "\n ERROR !!! \n Missing \"--chr\", a required parameter if using \"--end\" parameter.\n"; cout<<" Program Exiting ..."<0 || end>0) { cout<<" NOTE: No \"--window\" parameter provided !!! \n"; cout<<" No buffer region will be used on either side of the chunk"< 0) { if (START-WINDOW < 0) START = 0; else START -= WINDOW; END += WINDOW; } return true; }; void GetMapFileLocation(int argc, char ** argv) { int len = strlen(argv[0]); string tempString(argv[0]),tempMap; tempMap=tempString.substr(0,len-8)+"../docs/geneticMapFile.b38.map.txt.gz"; mapFile=tempMap.c_str(); int k=0; // char MyCommandLine; // strcpy(MyCommandLine,argv[0]); } }; class AllVariable { public: OutputFormatVariable myOutFormat; ModelVariable myModelVariables; HaplotypeDataVariables myHapDataVariables; }; #endif // MY_VARIABLES_INCLUDED Minimac4-1.0.2/src/Unique.cpp000066400000000000000000000214051353222426400157210ustar00rootroot00000000000000 #include "Unique.h" void findUnique::UpdateDeltaMatrix(CompressedHaplotype &haplotypes, vector & index, vector & firstDifference, int length, int blockSize, vector & oldIndex, vector & previousPredecessor, vector & previousDifference) { int haps = index.size(); previousPredecessor[oldIndex[0]] = -1; for (int i = 1; i < haps; i++) { previousPredecessor[oldIndex[i]] = oldIndex[i-1]; previousDifference[oldIndex[i]] = firstDifference[i-1]; } for (int i = 1; i < haps; i++) { if (index[i-1] == previousPredecessor[index[i]]) { firstDifference[i-1] = haplotypes.GetVal(index[i],length - 1) == haplotypes.GetVal(index[i-1],length - 1) ? previousDifference[index[i]] + 1 : 0; continue; } int diff = 0; while (diff < length && diff < blockSize && haplotypes.GetVal(index[i],length - diff - 1) == haplotypes.GetVal(index[i-1],length - diff - 1) ) diff++; firstDifference[i - 1] = diff; } } void findUnique::UpdateDeltaMatrix(vector & haplotypes, vector & index, vector & firstDifference, int length, int blockSize, vector & oldIndex, vector & previousPredecessor, vector & previousDifference) { int haps = index.size(); previousPredecessor[oldIndex[0]] = -1; for (int i = 1; i < haps; i++) { previousPredecessor[oldIndex[i]] = oldIndex[i-1]; previousDifference[oldIndex[i]] = firstDifference[i-1]; } for (int i = 1; i < haps; i++) { if (index[i-1] == previousPredecessor[index[i]]) { firstDifference[i-1] = haplotypes[index[i]][length - 1] == haplotypes[index[i-1]][length - 1] ? previousDifference[index[i]] + 1 : 0; continue; } int diff = 0; while (diff < length && diff < blockSize && haplotypes[index[i]][length - diff - 1] == haplotypes[index[i-1]][length - diff - 1]) diff++; firstDifference[i - 1] = diff; } } void findUnique::AnalyzeBlocks(vector & index, vector & firstDifference, int length, int blockSize, vector & cost, vector & bestSlice, vector & bestComplexity, vector > &bestIndex) { int haps = index.size(); // Try to figure out optimal block split for (int i = 1; i <= blockSize && i <= length; i++) { int distinctHaplos = 1; for (int j = 0; j < haps - 1; j++) if (i > firstDifference[j]) distinctHaplos++; int currentCost=1; if(i>1) currentCost= transFactor * haps + (i) * distinctHaplos * cisFactor + cost[length - i+1]; if (i==2) { cost[length] = currentCost; bestSlice[length] = 2; bestComplexity[length] = distinctHaplos; } else if (cost[length] > currentCost) { cost[length] = currentCost; bestSlice[length] = i; bestComplexity[length] = distinctHaplos; } else if (cost[length] + transFactor * haps < currentCost) break; } bestIndex[length-1] = index; } double findUnique::FlushBlocks(vector &HapInfo, int LastflushPos, CompressedHaplotype & haplotypes, vector & cost, vector & bestComplexity, vector & bestSlice, vector > &bestIndex) { ReducedHaplotypeInfo tempInfo; int where = haplotypes.Length; where--; int newCost = cost[where+1]; int totalBlocks=0; double totalComplexity = 0; vector examplars, labels; vector blockBoundaries; blockBoundaries.clear(); // Work out optimal set of block boundaries while (where != 0) { blockBoundaries.push_back(where); totalBlocks++; totalComplexity += bestComplexity[where+1]; where = where - bestSlice[where+1]+1; }; int blockStart = 0; // while (blockStart != (haplotypes.Length - 1)) { int blockEnd = blockBoundaries.back(); blockBoundaries.pop_back(); examplars.clear(); examplars.push_back(bestIndex[blockEnd][0]); labels.resize(bestIndex[blockEnd].size()); labels[bestIndex[blockEnd][0]] = 0; int countCard=0; for (int i = 1; i < (int) bestIndex[blockEnd].size(); i++) { int previous = bestIndex[blockEnd][i-1]; int current = bestIndex[blockEnd][i]; countCard++; for (int j = blockStart; j <= blockEnd; j++) if (haplotypes.GetVal(previous,j) != haplotypes.GetVal(current,j)) { examplars.push_back(current); break; } labels[current] = examplars.size() - 1; } tempInfo.uniqueIndexMap=labels; tempInfo.RepSize=examplars.size(); tempInfo.BlockSize=blockEnd-blockStart+1; tempInfo.startIndex=blockStart+LastflushPos; tempInfo.endIndex=LastflushPos+blockEnd; tempInfo.uniqueCardinality.clear(); tempInfo.uniqueCardinality.resize(tempInfo.RepSize,0); tempInfo.InvuniqueCardinality.resize(tempInfo.RepSize); for (int i = 0; i < (int)labels.size(); i++) { tempInfo.uniqueCardinality[labels[i]]++; } tempInfo.TransposedUniqueHaps.resize(tempInfo.BlockSize); for (int i = 0; i < tempInfo.BlockSize; i++) { tempInfo.TransposedUniqueHaps[i].resize(tempInfo.RepSize); } for (int i = 0; i < tempInfo.RepSize; i++) { tempInfo.InvuniqueCardinality[i]=1.0/(float)tempInfo.uniqueCardinality[i]; } for (int i = blockStart; i <= blockEnd; i++) { vector &TempHap = tempInfo.TransposedUniqueHaps[i-blockStart]; haplotypes.RetrieveVariant(i); for (int j = 0; j < tempInfo.RepSize; j++) { TempHap[j]=haplotypes.GetVal(examplars[j]) ; } } HapInfo.push_back(tempInfo); blockStart = blockEnd; } return newCost; } double findUnique::FlushBlocks(vector &HapInfo, int LastflushPos,vector & haplotypes, vector & cost, vector & bestComplexity, vector & bestSlice, vector > &bestIndex) { ReducedHaplotypeInfo tempInfo; int where = haplotypes[0].Length(); where--; int newCost = cost[where+1]; int totalBlocks=0; double totalComplexity = 0; vector examplars, labels; vector blockBoundaries; blockBoundaries.clear(); // Work out optimal set of block boundaries while (where != 0) { blockBoundaries.push_back(where); totalBlocks++; totalComplexity += bestComplexity[where+1]; where = where - bestSlice[where+1]+1; }; int blockStart = 0; // while (blockStart != (haplotypes[0].Length()-1)) { int blockEnd = blockBoundaries.back(); blockBoundaries.pop_back(); examplars.clear(); examplars.push_back(bestIndex[blockEnd][0]); labels.resize(bestIndex[blockEnd].size()); labels[bestIndex[blockEnd][0]] = 0; int countCard=0; for (int i = 1; i < (int) bestIndex[blockEnd].size(); i++) { int previous = bestIndex[blockEnd][i-1]; int current = bestIndex[blockEnd][i]; countCard++; for (int j = blockStart; j <= blockEnd; j++) if (haplotypes[previous][j] != haplotypes[current][j]) { examplars.push_back(current); break; } labels[current] = examplars.size() - 1; } tempInfo.uniqueIndexMap=labels; tempInfo.startIndex=blockStart+LastflushPos; tempInfo.endIndex=LastflushPos+blockEnd; tempInfo.uniqueCardinality.clear(); tempInfo.uniqueCardinality.resize(examplars.size(),0); for (int i = 0; i < (int)labels.size(); i++) { tempInfo.uniqueCardinality[labels[i]]++; } tempInfo.TransposedUniqueHaps.resize(blockEnd-blockStart+1); for (int i = 0; i < (blockEnd-blockStart+1); i++) tempInfo.TransposedUniqueHaps[i].resize(examplars.size()); for (int j = 0; j < (int)examplars.size(); j++) { for (int i = blockStart; i <= blockEnd; i++) { tempInfo.TransposedUniqueHaps[i-blockStart][j]=haplotypes[examplars[j]][i]; } } HapInfo.push_back(tempInfo); blockStart = blockEnd; } return newCost; } Minimac4-1.0.2/src/Unique.h000066400000000000000000000166471353222426400154020ustar00rootroot00000000000000#ifndef UNIQUE_H_INCLUDED #define UNIQUE_H_INCLUDED #include #include #include "StringBasics.h" #include #include #include "assert.h" using namespace std; typedef char AlleleType; typedef int SmallInt; class variant { public: string name; int bp; string chr; string rsid; string refAlleleString,altAlleleString; variant(){}; variant(string &id,string &CHR,int &BP) { name=id; bp=BP; chr=CHR; }; void assignValues(string &id,string &Rsid,string &CHR,int BP) { name=id; rsid=Rsid; bp=BP; chr=CHR; }; void assignRefAlt(string &refe,string &alt) { refAlleleString=refe; altAlleleString=alt; }; ~variant(){}; double size() { double S=0; S+=name.size(); S+=chr.size(); S+=rsid.size(); S+=refAlleleString.size(); S+=altAlleleString.size(); return (S+2); }; variant(const variant &obj) { name=obj.name; rsid=obj.rsid; bp=obj.bp; chr=obj.chr; refAlleleString=obj.refAlleleString; altAlleleString=obj.altAlleleString; } }; class ReducedHaplotypeInfo { public: // Basic Compulsory Parameters int startIndex,endIndex; vector uniqueCardinality; // has number of representatives for each unique representative vector InvuniqueCardinality; // has number of representatives for each unique representative vector uniqueIndexMap; // maps to corresponding item in the uniqueRep... required to map Constants and unfold fold probs vector > TransposedUniqueHaps; int BlockSize, RepSize; // Special members for RefAtGWAS Panel vector< vector > uniqueIndexReverseMaps; int size() { int S=0; S+=uniqueCardinality.size() * sizeof(int); S+=InvuniqueCardinality.size() * sizeof(float); S+=uniqueIndexMap.size() * sizeof(int); for(int i=0;i<(int)TransposedUniqueHaps.size();i++) { S+=TransposedUniqueHaps[i].size() * sizeof(AlleleType); } for(int i=0;i<(int)uniqueIndexReverseMaps.size();i++) { S+=uniqueIndexReverseMaps[i].size() * sizeof(int); } return (S+8); }; ReducedHaplotypeInfo() { startIndex=0; endIndex=0; BlockSize=0; RepSize=0; uniqueCardinality.clear(); InvuniqueCardinality.clear(); uniqueIndexMap.clear(); TransposedUniqueHaps.clear(); } ~ReducedHaplotypeInfo() { } ReducedHaplotypeInfo(const ReducedHaplotypeInfo &obj) { startIndex=obj.startIndex; endIndex=obj.endIndex; BlockSize=obj.BlockSize; RepSize=obj.RepSize; uniqueCardinality=obj.uniqueCardinality; InvuniqueCardinality=obj.InvuniqueCardinality; uniqueIndexMap=obj.uniqueIndexMap; TransposedUniqueHaps=obj.TransposedUniqueHaps; } }; class ReducedHaplotypeInfoSummary { public: // Basic Summary Parameters int startIndex,endIndex; int BlockSize, RepSize; ReducedHaplotypeInfoSummary() { startIndex=0; endIndex=0; BlockSize=0; RepSize=0; } int size() { return 16; }; ~ReducedHaplotypeInfoSummary() { } }; class CompressedHaplotype { public: // Basic Compulsory Parameters int Length; vector ReducedInfoMapper; vector ReducedInfoVariantMapper; vector *RhapInfo; ReducedHaplotypeInfo *CurrentVariantInfo; vector *CurrentVariantHaps; CompressedHaplotype() { ReducedInfoMapper.clear(); ReducedInfoVariantMapper.clear(); Length=0; } ~CompressedHaplotype() { RhapInfo=NULL; } void Size(vector &rhapInfo, int &bufferSize) { RhapInfo=&rhapInfo; ReducedInfoMapper.resize(bufferSize); ReducedInfoVariantMapper.resize(bufferSize); } void Clear() { Length=0; } void RetrieveVariant(int position) { CurrentVariantInfo = & (*RhapInfo)[ReducedInfoMapper[position]]; CurrentVariantHaps = &(CurrentVariantInfo->TransposedUniqueHaps[ReducedInfoVariantMapper[position]]); } AlleleType GetVal(int &HapId) { int &Index = CurrentVariantInfo->uniqueIndexMap[HapId]; return ( (*CurrentVariantHaps)[Index]); } AlleleType GetVal(int &HapId, int position) { ReducedHaplotypeInfo &tempInfo=(*RhapInfo)[ReducedInfoMapper[position]]; int &Index = tempInfo.uniqueIndexMap[HapId]; return (tempInfo.TransposedUniqueHaps[ReducedInfoVariantMapper[position]][Index]); } void Push(int &Val1,int &Val2) { ReducedInfoMapper[Length]=Val1; ReducedInfoVariantMapper[Length++]=Val2; } }; class findUnique { public: int N; // No. of Samples int max_block; // Maximum Block Length to consider int M; // No. of Markers vector > uniqueCount; // matrix to store unique number of haplotypes between positions vector minCost; vector minAllocation; vector optimalAllocation; int transFactor, cisFactor; findUnique() { } findUnique(vector > &hap) { N=hap.size(); M=hap[0].size(); } void UpdateDeltaMatrix(CompressedHaplotype &haplotypes, vector & index, vector & firstDifference, int length, int blockSize, vector & oldIndex, vector & previousPredecessor, vector & previousDifference); void UpdateDeltaMatrix(vector & haplotypes, vector & index, vector & firstDifference, int length, int blockSize, vector & oldIndex, vector & previousPredecessor, vector & previousDifference); void AnalyzeBlocks(vector & index, vector & firstDifference, int length, int blockSize, vector & cost, vector & bestSlice, vector & bestComplexity, vector > &bestIndex); double FlushBlocks(vector &HapInfo, int LastflushPos, CompressedHaplotype & haplotypes, vector & cost, vector & bestComplexity, vector & bestSlice, vector > &bestIndex); double FlushBlocks(vector &HapInfo, int LastflushPos,vector & haplotypes, vector & cost, vector & bestComplexity, vector & bestSlice, vector > &bestIndex); void updateCoeffs(int trans,int cis) { transFactor = trans; cisFactor = cis; } }; #endif // UNIQUE_H_INCLUDED