pax_global_header00006660000000000000000000000064145331464350014522gustar00rootroot0000000000000052 comment=0c4a8d894338809eb257be2a9f4bf37ced0e2a6c Minimac4-4.1.6/000077500000000000000000000000001453314643500131735ustar00rootroot00000000000000Minimac4-4.1.6/.clang-format000066400000000000000000000006521453314643500155510ustar00rootroot00000000000000BasedOnStyle: Mozilla BreakBeforeBraces: Allman AlwaysBreakAfterReturnType: None AlwaysBreakAfterDefinitionReturnType: None ColumnLimit: 0 NamespaceIndentation: All IndentCaseLabels: false IndentCaseBlocks: true BreakConstructorInitializers: AfterColon AllowShortCaseLabelsOnASingleLine: true AllowShortFunctionsOnASingleLine: All AllowShortLoopsOnASingleLine: true Cpp11BracedListStyle: true AlignAfterOpenBracket: DontAlign Minimac4-4.1.6/.github/000077500000000000000000000000001453314643500145335ustar00rootroot00000000000000Minimac4-4.1.6/.github/workflows/000077500000000000000000000000001453314643500165705ustar00rootroot00000000000000Minimac4-4.1.6/.github/workflows/build_and_test.yml000066400000000000000000000013771453314643500223030ustar00rootroot00000000000000name: build and run tests on: push: branches: [ master ] pull_request: branches: [ master ] jobs: build: runs-on: ubuntu-20.04 steps: - uses: actions/checkout@v2 - name: build and test shell: bash run: | set -euo pipefail sudo apt update sudo apt install -y build-essential bcftools cmake git gzip python3-dev python3-pip python3-setuptools pip3 --version pip3 install wheel pip3 install cget cget ignore xz cget install -f ./requirements.txt cmake --version mkdir build && cd build cmake -DBUILD_TESTS=1 -DCMAKE_TOOLCHAIN_FILE=../cget/cget/cget.cmake -DCMAKE_BUILD_TYPE=Debug .. make make CTEST_OUTPUT_ON_FAILURE=1 test Minimac4-4.1.6/.gitignore000066400000000000000000000001061453314643500151600ustar00rootroot00000000000000.idea/ *.so *.dylib *.dll *.lai *.la *.a *.lib *.slo *.lo *.o *.objMinimac4-4.1.6/CMakeGet.cmake000066400000000000000000000417651453314643500156320ustar00rootroot00000000000000 set(BUILD_DEPS On CACHE BOOL "Build dependencies") include(ProcessorCount) if(CMAKE_VERSION VERSION_LESS "3.4") function(cget_parse_arguments prefix _optionNames _singleArgNames _multiArgNames) # first set all result variables to empty/FALSE foreach(arg_name ${_singleArgNames} ${_multiArgNames}) set(${prefix}_${arg_name}) endforeach() foreach(option ${_optionNames}) set(${prefix}_${option} FALSE) endforeach() set(${prefix}_UNPARSED_ARGUMENTS) set(insideValues FALSE) set(currentArgName) # now iterate over all arguments and fill the result variables foreach(currentArg ${ARGN}) list(FIND _optionNames "${currentArg}" optionIndex) # ... then this marks the end of the arguments belonging to this keyword list(FIND _singleArgNames "${currentArg}" singleArgIndex) # ... then this marks the end of the arguments belonging to this keyword list(FIND _multiArgNames "${currentArg}" multiArgIndex) # ... then this marks the end of the arguments belonging to this keyword if(${optionIndex} EQUAL -1 AND ${singleArgIndex} EQUAL -1 AND ${multiArgIndex} EQUAL -1) if(insideValues) if("${insideValues}" STREQUAL "SINGLE") set(${prefix}_${currentArgName} ${currentArg}) set(insideValues FALSE) elseif("${insideValues}" STREQUAL "MULTI") list(APPEND ${prefix}_${currentArgName} ${currentArg}) endif() else() list(APPEND ${prefix}_UNPARSED_ARGUMENTS ${currentArg}) endif() else() if(NOT ${optionIndex} EQUAL -1) set(${prefix}_${currentArg} TRUE) set(insideValues FALSE) elseif(NOT ${singleArgIndex} EQUAL -1) set(currentArgName ${currentArg}) set(${prefix}_${currentArgName}) set(insideValues "SINGLE") elseif(NOT ${multiArgIndex} EQUAL -1) set(currentArgName ${currentArg}) set(insideValues "MULTI") endif() endif() endforeach() # propagate the result variables to the caller: foreach(arg_name ${_singleArgNames} ${_multiArgNames} ${_optionNames}) set(${prefix}_${arg_name} ${${prefix}_${arg_name}} PARENT_SCOPE) endforeach() set(${prefix}_UNPARSED_ARGUMENTS ${${prefix}_UNPARSED_ARGUMENTS} PARENT_SCOPE) endfunction() else() macro(cget_parse_arguments prefix _optionNames _singleArgNames _multiArgNames) cmake_parse_arguments(${prefix} "${_optionNames}" "${_singleArgNames}" "${_multiArgNames}" ${ARGN}) endmacro() endif() set(_cget_tmp_dir "${CMAKE_CURRENT_LIST_DIR}/tmp") if(CMAKE_HOST_UNIX) foreach(dir "$ENV{TMP}" "$ENV{TMPDIR}" "/tmp") if(EXISTS "${dir}" AND NOT "${dir}" STREQUAL "") file(TO_CMAKE_PATH "${dir}" _cget_tmp_dir) break() endif() endforeach() endif() set(_tmp_dir_count 0) macro(cget_mktemp_dir OUT) string(TIMESTAMP cget_mktemp_dir_STAMP "%H-%M-%S") string(RANDOM cget_mktemp_dir_RAND) set(cget_mktemp_dir_PREFIX "${_cget_tmp_dir}/cget-${cget_mktemp_dir_STAMP}-${cget_mktemp_dir_RAND}") math(EXPR _tmp_dir_count "${_tmp_dir_count} + 1") set(${OUT} "${cget_mktemp_dir_PREFIX}-${_tmp_dir_count}") file(MAKE_DIRECTORY ${${OUT}}) endmacro() macro(cget_set_parse_flag VAR OPT) unset(${VAR}_${OPT}) foreach(FLAG ${ARGN}) if(${VAR}_private_${FLAG}) set(${VAR}_${OPT} ${${VAR}_private_${FLAG}}) endif() unset(${VAR}_private_${FLAG}) endforeach() endmacro() macro(cget_parse_requirement VAR) unset(${VAR}_PKG) set(${VAR}_private_options --build -b --test -t) set(${VAR}_private_oneValueArgs -H --hash -X --cmake --file -f) set(${VAR}_private_multiValueArgs -D --define) set(cget_parse_requirement_args) foreach(ARG ${ARGN}) if(ARG MATCHES "^-([^-])(.+)") list(APPEND cget_parse_requirement_args -${CMAKE_MATCH_1}) list(APPEND cget_parse_requirement_args ${CMAKE_MATCH_2}) else() list(APPEND cget_parse_requirement_args ${ARG}) endif() endforeach() cget_parse_arguments(${VAR}_private "${${VAR}_private_options}" "${${VAR}_private_oneValueArgs}" "${${VAR}_private_multiValueArgs}" ${cget_parse_requirement_args}) if(${VAR}_private_UNPARSED_ARGUMENTS) list(GET ${VAR}_private_UNPARSED_ARGUMENTS 0 ${VAR}_PKG) list(LENGTH ${VAR}_private_UNPARSED_ARGUMENTS ${VAR}_private_UNPARSED_ARGUMENTS_SIZE) if(${VAR}_private_UNPARSED_ARGUMENTS_SIZE GREATER 1) list(REMOVE_AT ${VAR}_private_UNPARSED_ARGUMENTS 0) message(WARNING "Unknown keywords given in requirements file: \"${${VAR}_private_UNPARSED_ARGUMENTS}\"") endif() endif() cget_set_parse_flag(${VAR} BUILD --build -b) cget_set_parse_flag(${VAR} TEST --test -t) cget_set_parse_flag(${VAR} CMAKE --cmake -X) cget_set_parse_flag(${VAR} HASH --hash -H) cget_set_parse_flag(${VAR} DEFINE --define -D) cget_set_parse_flag(${VAR} FILE --file -f) set(${VAR}_CMAKE_ARGS) foreach(DEFINE ${${VAR}_DEFINE}) list(APPEND ${VAR}_CMAKE_ARGS "-D${DEFINE}") endforeach() endmacro() function(cget_exec) execute_process(${ARGN} RESULT_VARIABLE RESULT) if(NOT RESULT EQUAL 0) string(REPLACE ";" " " CMD "${ARGN}") string(REPLACE "COMMAND " "" CMD "${CMD}") message(FATAL_ERROR "Process failed: ${CMD}") endif() endfunction() function(cget_download) file(DOWNLOAD ${ARGN} STATUS RESULT_LIST) list(GET RESULT_LIST 0 RESULT) list(GET RESULT_LIST 1 RESULT_MESSAGE) if(NOT RESULT EQUAL 0) message(FATAL_ERROR "Download failed: ${RESULT_MESSAGE}: ${ARGN}") endif() endfunction() set(_cget_install_dir_count 0) set_property(GLOBAL PROPERTY _cget_install_dir_count 0) function(cget_install_dir DIR) set(options) set(oneValueArgs PREFIX BUILD_DIR) set(multiValueArgs CMAKE_ARGS) cget_parse_arguments(PARSE "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) if(PARSE_UNPARSED_ARGUMENTS) message(FATAL_ERROR "Unknown keywords given to cget_install_dir(): \"${PARSE_UNPARSED_ARGUMENTS}\"") endif() if(NOT EXISTS ${DIR}/CMakeLists.txt) message(FATAL_ERROR "cget_install_dir(): ${DIR} is not a cmake package") endif() set(PREFIX ${PARSE_PREFIX}) set(BUILD_DIR ${PARSE_BUILD_DIR}) if(NOT EXISTS ${BUILD_DIR}) file(MAKE_DIRECTORY ${BUILD_DIR}) endif() cget_exec(COMMAND ${CMAKE_COMMAND} -DCMAKE_PREFIX_PATH=${PREFIX} -DCMAKE_INSTALL_PREFIX=${PREFIX} ${PARSE_CMAKE_ARGS} ${DIR} WORKING_DIRECTORY ${BUILD_DIR} ) set(CONFIG "Release") foreach(ARG ${PARSE_CMAKE_ARGS}) string(TOUPPER ${ARG} ARG_UPPER) if(ARG_UPPER MATCHES "-DCMAKE_BUILD_TYPE") string(SUBSTRING ${ARG_UPPER} 19 -1 BUILD_TYPE) if(BUILD_TYPE STREQUAL "DEBUG") set(CONFIG "Debug") endif() endif() endforeach() set(BUILD_ARGS) if(EXISTS ${BUILD_DIR}/Makefile) ProcessorCount(N) set(BUILD_ARGS -- -j ${N}) endif() cget_exec(COMMAND ${CMAKE_COMMAND} --build ${BUILD_DIR} --config ${CONFIG} ${BUILD_ARGS}) cget_exec(COMMAND ${CMAKE_COMMAND} --build ${BUILD_DIR} --target install --config ${CONFIG} ${BUILD_ARGS}) get_property(_tmp_count GLOBAL PROPERTY _cget_install_dir_count) math(EXPR _tmp_count "${_tmp_count} + 1") set_property(GLOBAL PROPERTY _cget_install_dir_count ${_tmp_count}) file(REMOVE_RECURSE ${BUILD_DIR}) endfunction() function(cget_parse_src_name URL VARIANT SRC) if(SRC MATCHES "@") string(REPLACE "@" ";" SRC_LIST ${SRC}) list(GET SRC_LIST 0 _URL) list(GET SRC_LIST 1 _VARIANT) set(${URL} ${_URL} PARENT_SCOPE) set(${VARIANT} ${_VARIANT} PARENT_SCOPE) else() set(${URL} ${SRC} PARENT_SCOPE) set(${VARIANT} ${ARGN} PARENT_SCOPE) endif() endfunction() function(cget_find_recipe RECIPE_DIR SRC) cget_parse_src_name(NAME VARIANT ${SRC}) foreach(RECIPE ${ARGN}) if(EXISTS ${RECIPE}/${NAME}/package.txt OR EXISTS ${RECIPE}/${NAME}/requirements.txt) # TODO: Check variant set(${RECIPE_DIR} ${RECIPE}/${NAME} PARENT_SCOPE) break() endif() endforeach() endfunction() function(cget_validate_gh_src NAME) if(NAME MATCHES "[^A-Za-z0-9_./@-]") message(FATAL_ERROR "Not a valid name: ${NAME}") endif() endfunction() function(cget_parse_pkg NAME URL PKG) string(REPLACE "," ";" PKG_NAMES ${PKG}) list(GET PKG_NAMES -1 PKG_SRC) list(GET PKG_NAMES 0 PKG_NAME) set(${NAME} ${PKG_NAME} PARENT_SCOPE) if(PKG_SRC MATCHES "://") set(${URL} ${PKG_SRC} PARENT_SCOPE) else() get_filename_component(PKG_SRC_FULL ${PKG_SRC} ABSOLUTE) if(EXISTS ${PKG_SRC_FULL}) set(${URL} file://${PKG_SRC_FULL} PARENT_SCOPE) else() # Parse recipe dir cget_find_recipe(RECIPE_DIR ${PKG_SRC} ${ARGN}) if(EXISTS ${RECIPE_DIR}) set(${URL} recipe://${RECIPE_DIR} PARENT_SCOPE) set(${NAME} ${PKG_SRC} ${PKG_NAME} PARENT_SCOPE) else() cget_validate_gh_src(${PKG_SRC}) # Parse github url cget_parse_src_name(GH_NAME GH_BRANCH ${PKG_SRC} HEAD) cget_validate_gh_src(${GH_NAME}) cget_validate_gh_src(${GH_BRANCH}) set(${NAME} ${GH_NAME} ${PKG_NAME} PARENT_SCOPE) if(GH_NAME MATCHES "/") set(${URL} "https://github.com/${GH_NAME}/archive/${GH_BRANCH}.tar.gz" PARENT_SCOPE) else() set(${URL} "https://github.com/${GH_NAME}/${GH_NAME}/archive/${GH_BRANCH}.tar.gz" PARENT_SCOPE) endif() endif() endif() endif() endfunction() function(cget_unpack FILENAME DIR) file(MAKE_DIRECTORY ${DIR}) cget_exec(COMMAND ${CMAKE_COMMAND} -E tar xzf ${FILENAME} WORKING_DIRECTORY ${DIR} ) endfunction() function(cget_fetch DIR DOWNLOAD_DIR URL) if("${URL}" MATCHES "file://") string(REPLACE "file://" "" LOCAL_PATH ${URL}) if(IS_DIRECTORY ${LOCAL_PATH}) file(COPY ${LOCAL_PATH} DESTINATION ${DOWNLOAD_DIR}/) else() cget_unpack(${LOCAL_PATH} ${DOWNLOAD_DIR}) endif() else() string(REPLACE "/" ";" PATH_LIST ${URL}) list(GET PATH_LIST -1 FILENAME) message("Downloading ${URL}") cget_download(${URL} ${DOWNLOAD_DIR}/${FILENAME} ${ARGN}) cget_unpack("${DOWNLOAD_DIR}/${FILENAME}" "${DOWNLOAD_DIR}") file(REMOVE ${DOWNLOAD_DIR}/${FILENAME}) endif() set(${DIR} ${DOWNLOAD_DIR} PARENT_SCOPE) file(GLOB FILES LIST_DIRECTORIES true RELATIVE ${DOWNLOAD_DIR} ${DOWNLOAD_DIR}/*) list(LENGTH FILES NFILES) if(NFILES EQUAL 0) # No files found, so this is an error message(FATAL_ERROR "Failed to fetch: ${URL}") elseif(NFILES EQUAL 1) list(GET FILES 0 _DIR) if(IS_DIRECTORY ${DOWNLOAD_DIR}/${_DIR}) # If there is just one directory, then adjust the path set(${DIR} ${DOWNLOAD_DIR}/${_DIR} PARENT_SCOPE) endif() endif() endfunction() set(_cget_cmake_original_file "__cget_original_cmake_file__.cmake") function(cget_find_cmake FILE DIR) if(EXISTS ${DIR}/CMakeLists.txt) file(RENAME ${DIR}/CMakeLists.txt ${DIR}/${_cget_cmake_original_file}) endif() get_filename_component(BASENAME ${FILE} NAME) if(EXISTS ${FILE}) file(COPY ${FILE} DESTINATION ${DIR}/) file(RENAME ${DIR}/${BASENAME} ${DIR}/CMakeLists.txt) else() string(REPLACE ".cmake" "" REMOTE_CMAKE ${BASENAME}) cget_download(https://raw.githubusercontent.com/pfultz2/cget/master/cget/cmake/${REMOTE_CMAKE}.cmake ${DIR}/CMakeLists.txt) endif() endfunction() function(cget_check_pkg_install FOUND) get_property(INSTALLED_PKGS GLOBAL PROPERTY CGET_INSTALLED_PACKAGES) set(FOUND 0 PARENT_SCOPE) foreach(NAME ${ARGN}) list(FIND INSTALLED_PKGS ${NAME} IDX) if(NOT IDX EQUAL "-1") set(FOUND 1 PARENT_SCOPE) endif() endforeach() endfunction() function(cget_add_pkg_install) get_property(INSTALLED_PKGS GLOBAL PROPERTY CGET_INSTALLED_PACKAGES) foreach(NAME ${ARGN}) list(FIND INSTALLED_PKGS ${NAME} IDX) if(IDX EQUAL "-1") set_property(GLOBAL APPEND PROPERTY CGET_INSTALLED_PACKAGES ${NAME}) endif() endforeach() endfunction() function(cget_get_absolute_path VAR PATH FILENAME) get_filename_component(FILE_DIR ${FILENAME} DIRECTORY) if(NOT IS_ABSOLUTE "${PATH}") set(${VAR} "${FILE_DIR}/${PATH}" PARENT_SCOPE) else() set(${VAR} "${PATH}" PARENT_SCOPE) endif() endfunction() function(cmake_get PKG) if(BUILD_DEPS) set(options NO_RECIPE) set(oneValueArgs PREFIX HASH CMAKE_FILE) set(multiValueArgs CMAKE_ARGS) cget_parse_arguments(PARSE "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) if(PARSE_UNPARSED_ARGUMENTS) message(FATAL_ERROR "Unknown keywords given to cmake_get(): \"${PARSE_UNPARSED_ARGUMENTS}\"") endif() if(PARSE_NO_RECIPE) cget_parse_pkg(NAMES URL ${PKG}) else() cget_parse_pkg(NAMES URL ${PKG} ${PARSE_PREFIX}/etc/cget/recipes) endif() cget_check_pkg_install(FOUND ${NAMES}) if(NOT FOUND) if(URL MATCHES "recipe://") string(REPLACE "recipe://" "" RECIPE ${URL}) if(EXISTS ${RECIPE}/requirements.txt) cmake_get_from(${RECIPE}/requirements.txt PREFIX ${PARSE_PREFIX} CMAKE_ARGS ${PARSE_CMAKE_ARGS}) endif() if(EXISTS ${RECIPE}/package.txt) cmake_get_from(${RECIPE}/package.txt PREFIX ${PARSE_PREFIX} CMAKE_ARGS ${PARSE_CMAKE_ARGS} NO_RECIPE) endif() else() cget_mktemp_dir(TMP_DIR) if(PREFIX_HASH) string(TOUPPER ${PREFIX_HASH} _HASH) string(REPLACE ":" "=" _HASH ${_HASH}) set(HASH EXPECTED_HASH ${_HASH}) endif() cget_fetch(DIR ${TMP_DIR}/download ${URL} ${HASH} SHOW_PROGRESS) if(EXISTS ${DIR}/requirements.txt) cmake_get_from(${DIR}/requirements.txt ${BASE_DIR_ARG} PREFIX ${PARSE_PREFIX} CMAKE_ARGS ${PARSE_CMAKE_ARGS}) endif() if(PARSE_CMAKE_FILE) cget_find_cmake(${PARSE_CMAKE_FILE} ${DIR}) endif() cget_install_dir(${DIR} BUILD_DIR ${TMP_DIR}/build PREFIX ${PARSE_PREFIX} CMAKE_ARGS -DCGET_CMAKE_ORIGINAL_SOURCE_FILE=${DIR}/${_cget_cmake_original_file} ${PARSE_CMAKE_ARGS}) file(REMOVE_RECURSE ${TMP_DIR}) endif() cget_add_pkg_install(${NAMES}) endif() endif() endfunction() set(_cmake_get_configure_reqs 0) function(cmake_get_from FILENAME) if(BUILD_DEPS) set(options NO_RECIPE) set(oneValueArgs PREFIX) set(multiValueArgs CMAKE_ARGS) cget_parse_arguments(PARSE "${options}" "${oneValueArgs}" "${multiValueArgs}" ${ARGN}) if(NOT EXISTS ${FILENAME}) message(FATAL_ERROR "File ${FILENAME} does not exists") endif() if(PARSE_UNPARSED_ARGUMENTS) message(FATAL_ERROR "Unknown keywords given to cmake_get_from(): \"${PARSE_UNPARSED_ARGUMENTS}\"") endif() file(STRINGS ${FILENAME} LINES) foreach(LINE ${LINES}) separate_arguments(WORDS UNIX_COMMAND "${LINE}") set(REQ) foreach(WORD ${WORDS}) if(WORD MATCHES "^#") break() endif() list(APPEND REQ ${WORD}) endforeach() list(LENGTH REQ REQ_LEN) if(REQ_LEN GREATER 0) cget_parse_requirement(PARSE_REQ ${REQ}) if(_cmake_get_configure_reqs) string(CONFIGURE ${PARSE_REQ_PKG} PARSE_REQ_PKG @ONLY) endif() if(PARSE_NO_RECIPE) set(NO_RECIPE "NO_RECIPE") endif() set(REQ_CMAKE) if(PARSE_REQ_CMAKE) cget_get_absolute_path(REQ_CMAKE ${PARSE_REQ_CMAKE} ${FILENAME}) endif() if(PARSE_REQ_FILE) cget_get_absolute_path(REQ_FILE ${PARSE_REQ_FILE} ${FILENAME}) cmake_get_from(${REQ_FILE} ${NO_RECIPE} PREFIX ${PARSE_PREFIX} CMAKE_ARGS ${PARSE_CMAKE_ARGS} ${PARSE_REQ_CMAKE_ARGS} ) else() cget_get_absolute_path(REQ_PKG ${PARSE_REQ_PKG} ${FILENAME}) if(NOT EXISTS ${REQ_PKG}) set(REQ_PKG ${PARSE_REQ_PKG}) endif() cmake_get(${REQ_PKG} ${NO_RECIPE} PREFIX ${PARSE_PREFIX} HASH ${PARSE_REQ_HASH} CMAKE_FILE ${REQ_CMAKE} CMAKE_ARGS ${PARSE_CMAKE_ARGS} ${PARSE_REQ_CMAKE_ARGS} ) endif() endif() endforeach() endif() endfunction() Minimac4-4.1.6/CMakeLists.txt000066400000000000000000000040251453314643500157340ustar00rootroot00000000000000cmake_minimum_required(VERSION 3.2) project(minimac4 VERSION 4.1.6) if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE "Release" CACHE STRING "Choose build type (Debug|Release|RelWithDebInfo|MinSizeRel)" FORCE) endif() set(CMAKE_CXX_STANDARD 11) add_definitions(-DVERSION="${PROJECT_VERSION}") 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(Threads) find_library(OMPP_LIBRARY omp) find_package(savvy REQUIRED) add_executable(minimac4 src/dosage_writer.cpp src/dosage_writer.hpp src/hidden_markov_model.cpp src/hidden_markov_model.hpp src/input_prep.cpp src/input_prep.hpp src/recombination.cpp src/recombination.hpp src/unique_haplotype.cpp src/unique_haplotype.hpp src/main.cpp) target_link_libraries(minimac4 savvy ${OMPP_LIBRARY} Threads::Threads) add_custom_target(manuals COMMAND help2man --output "${CMAKE_BINARY_DIR}/minimac4.1" "${CMAKE_BINARY_DIR}/minimac4") if(BUILD_TESTS) enable_testing() add_test(simple_test ${CMAKE_SOURCE_DIR}/test/simple-test.sh ${CMAKE_BINARY_DIR}/minimac4 m4_simple_test_output ${CMAKE_SOURCE_DIR}/test/input/ref_panel.vcf ${CMAKE_SOURCE_DIR}/test/input/tar_panel.vcf) add_test(haploid_and_diploid_test ${CMAKE_SOURCE_DIR}/test/simple-test.sh ${CMAKE_BINARY_DIR}/minimac4 m4_haploid_and_diploid_test_output ${CMAKE_SOURCE_DIR}/test/input/ref_panel_with_haploid_sample.vcf ${CMAKE_SOURCE_DIR}/test/input/tar_panel_with_haploid_sample.vcf) endif() install(TARGETS minimac4 RUNTIME DESTINATION bin) install(FILES ${CMAKE_CURRENT_BINARY_DIR}/minimac4.1 DESTINATION share/man/man1 OPTIONAL) 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-4.1.6/LICENSE000066400000000000000000001045131453314643500142040ustar00rootroot00000000000000 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-4.1.6/README.md000066400000000000000000000062461453314643500144620ustar00rootroot00000000000000# Minimac4 Minimac4 is a lower memory and more computationally efficient implementation of the genotype imputation algorithms in minimac/mininac2/minimac3. ## Installation A prebuilt Linux x86 executable is available at https://github.com/statgen/Minimac4/releases/latest by downloading and running minimac4-{version}-Linux-x86_64.sh. Alternativbely, you can build from source. ## Prerequisites for building from source Minimac4 requires GCC >= v5 or a compiler with full C++11 support. Automatic installation of Minimac4 requires [cget](http://cget.readthedocs.io/en/latest/src/intro.html#installing-cget) and CMake >= v3.2. ## Building from source The simplest way to build the latest Minimac4 and its dependencies is to use cget: ```bash cget install --prefix statgen/Minimac4 ``` Alternatively, you can build manually: ```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. make install # Install ``` To build and run tests from build directory: ```bash # bcftools is required to run tests cmake -DCMAKE_TOOLCHAIN_FILE=../cget/cget/cget.cmake -DBUILD_TESTS=ON .. make make CTEST_OUTPUT_ON_FAILURE=1 test ``` Since some users have reported issues with installing cget with pip, a cmake-only alternative for installing dependencies is available: ```shell cmake -P dependencies.cmake deps/ mkdir build; cd build cmake -DCMAKE_PREFIX_PATH=$(pwd)/../deps/ -DCMAKE_CXX_FLAGS="-I$(pwd)/../deps/include" .. make make install ``` ## Usage See `minimac4 --help` for detailed usage. A typical Minimac4 command line for imputation is as follows ```bash minimac4 reference.msav target.vcf.gz > imputed.sav ``` Here reference.msav is a reference panel (e.g. [1000 Genomes download](ftp://share.sph.umich.edu/minimac4/panels/g1k_p3_msav_files_with_estimates.tar.gz)) compressed with MVCF encoding, target.vcf.gz is an indexed VCF containing phased genotype array data, and imputed.sav is the imputed output. The file formats VCF, [BCF](https://github.com/samtools/bcftools), and [SAV](https://github.com/statgen/savvy) are supported for both input and output: ```bash minimac4 reference.msav target.bcf -o imputed.bcf minimac4 reference.msav target.vcf.gz -o imputed.vcf.gz ``` A sites-only file can be generated with: ```bash minimac4 reference.msav target.bcf -o imputed.sav -s imputed.sites.vcf.gz ``` Meta-imputation with MetaMinimac2 requires `--empirical-output` (or `-e`) to be specified: ```bash minimac4 reference.msav target.bcf -o imputed.dose.sav -e imputed.empirical_dose.sav ``` ## Reference Panel Creation If an M3VCF file is already available, it can be converted to the new MVCF format with: ``` minimac4 --update-m3vcf reference.m3vcf.gz > reference.msav ``` Otherwise, phased VCFs containing the reference haplotypes can be compressed into an MVCF with: ``` minimac4 --compress-reference reference.{sav,bcf,vcf.gz} > reference.msav ``` Minimac4-4.1.6/dependencies.cmake000077500000000000000000000010211453314643500166200ustar00rootroot00000000000000#!/usr/bin/env cmake -P set(ARGS) foreach(i RANGE 4 ${CMAKE_ARGC}) list(APPEND ARGS ${CMAKE_ARGV${i}}) endforeach() set(_PREFIX ${CMAKE_ARGV3}) # Make sure this is in the module path list(APPEND CMAKE_MODULE_PATH ${CMAKEGET_MODULE_PATH}) include(${CMAKE_CURRENT_LIST_DIR}/CMakeGet.cmake) get_filename_component(PREFIX ${_PREFIX} ABSOLUTE) # Install recipes #cmake_get(pfultz2/cget-recipes PREFIX ${PREFIX} CMAKE_ARGS ${ARGS}) cmake_get_from(${CMAKE_CURRENT_LIST_DIR}/requirements.txt PREFIX ${PREFIX} CMAKE_ARGS ${ARGS}) Minimac4-4.1.6/package-linux.sh000077500000000000000000000020501453314643500162570ustar00rootroot00000000000000#!/bin/bash # Usage: docker build -t packaging-alpine3.17 -f packaging-dockerfile-alpine3.17 . # docker run -v `pwd`:/app -w /app packaging-alpine3.17 ./package-linux.sh set -euo pipefail src_dir=`pwd` build_dir=${src_dir}/pkg-build-alpine rm -rf ${build_dir} mkdir ${build_dir} cd ${build_dir} export CFLAGS="-fPIC" export CXXFLAGS="-fPIC" cmake -P ../dependencies.cmake deps/ -DSHRINKWRAP_PREFER_STATIC=ON rm deps/lib/libz.so unset CFLAGS unset CXXFLAGS arc=`uname -m` cmake \ -DCMAKE_BUILD_TYPE=Release \ -DCMAKE_PREFIX_PATH=$(pwd)/deps \ -DCMAKE_CXX_FLAGS="-I$(pwd)/deps/include" \ -DCMAKE_BUILD_WITH_INSTALL_RPATH=ON \ -DCMAKE_EXE_LINKER_FLAGS="-static" \ -DCPACK_GENERATOR="STGZ" \ -DCPACK_SYSTEM_NAME="Linux-${arc}" \ -DCPACK_RESOURCE_FILE_LICENSE=${src_dir}/LICENSE \ -DCPACK_PACKAGE_CONTACT="csg-devel@umich.edu" \ ${src_dir} #-DCMAKE_EXE_LINKER_FLAGS="-static -static-libgcc -static-libstdc++" make make manuals make package mkdir -p ${src_dir}/pkg/ cp minimac4-*.sh ${src_dir}/pkg/ cd ${src_dir} rm -r ${build_dir} Minimac4-4.1.6/packaging-dockerfile-alpine3.17000066400000000000000000000003531453314643500207270ustar00rootroot00000000000000FROM alpine:3.17 ENV TZ=Etc/UTC RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone RUN apk update && apk add --no-cache binutils bash cmake make libgcc musl-dev gcc g++ \ curl \ git \ help2man Minimac4-4.1.6/requirements.txt000066400000000000000000000000521453314643500164540ustar00rootroot00000000000000statgen/savvy@v2.1.0 jonathonl/omp@v1.0.0 Minimac4-4.1.6/src/000077500000000000000000000000001453314643500137625ustar00rootroot00000000000000Minimac4-4.1.6/src/dosage_writer.cpp000066400000000000000000000711741453314643500173360ustar00rootroot00000000000000#include "dosage_writer.hpp" #include dosage_writer::dosage_writer(const std::string& file_path, const std::string& emp_file_path, const std::string& sites_file_path, savvy::file::format file_format, std::uint8_t out_compression, const std::vector& sample_ids, const std::vector& fmt_fields, const std::string& chromosome, float min_r2, bool is_temp) : out_file_(file_path, format_from_filename(file_path, file_format), gen_headers(fmt_fields, chromosome, is_temp), sample_ids, clevel_from_filename(file_path, out_compression)), emp_out_file_(emp_file_path.empty() ? nullptr : new savvy::writer(emp_file_path, format_from_filename(emp_file_path, file_format), gen_emp_headers(chromosome), sample_ids, clevel_from_filename(emp_file_path, out_compression))), sites_out_file_(sites_file_path.empty() ? nullptr : new savvy::writer(sites_file_path, format_from_filename(sites_file_path, file_format), gen_headers({}, chromosome, false), {}, clevel_from_filename(sites_file_path, out_compression))), fmt_field_set_(fmt_fields.begin(), fmt_fields.end()), n_samples_(sample_ids.size()), min_r2_(min_r2), is_temp_file_(is_temp) { } std::vector> dosage_writer::gen_headers(const std::vector& fmt_fields, const std::string& chromosome, bool is_temp) { std::time_t t = std::time(nullptr); char datestr[11]; std::string filedate(datestr, std::strftime(datestr, sizeof(datestr), "%Y%m%d", std::localtime(&t))); assert(filedate.size()); std::vector> headers; if (is_temp) { headers = { {"fileformat","VCFv4.2"}, {"filedate", filedate}, {"source","Minimac v" + std::string(VERSION)}, {"phasing","full"}, {"contig",""}, {"INFO", ""}, {"INFO",""}, {"INFO",""}, {"INFO",""}, {"INFO",""}, {"INFO",""}, {"INFO",""}, {"INFO",""}, {"INFO",""}, {"INFO",""}, {"INFO",""}}; } else { headers = { {"fileformat", "VCFv4.2"}, {"filedate", filedate}, {"source", "Minimac v" + std::string(VERSION)}, {"phasing", "full"}, {"contig", ""}, {"INFO", ""}, {"INFO", ""}, {"INFO", ""}, {"INFO", ""}, {"INFO", ""}, {"INFO", ""}, {"INFO", ""}}; } headers.reserve(headers.size() + 5); for (const auto& f : fmt_fields) { if (f == "GT") headers.emplace_back("FORMAT", ""); else if (f == "DS") headers.emplace_back("FORMAT", ""); else if (f == "HDS") headers.emplace_back("FORMAT", ""); else if (f == "GP") headers.emplace_back("FORMAT", ""); else if (f == "SD") headers.emplace_back("FORMAT", ""); } // TODO: command string return headers; } std::vector> dosage_writer::gen_emp_headers(const std::string& chromosome) { std::time_t t = std::time(nullptr); char datestr[11]; std::string filedate(datestr, std::strftime(datestr, sizeof(datestr), "%Y%m%d", std::localtime(&t))); assert(filedate.size()); std::vector> headers = { {"fileformat", "VCFv4.2"}, {"filedate", filedate}, {"source", "Minimac v" + std::string(VERSION)}, {"phasing", "full"}, {"contig", ""}, {"INFO", ""}, {"INFO", ""}, {"FORMAT",""}, {"FORMAT",""}}; // TODO: command string return headers; } savvy::file::format dosage_writer::format_from_filename(const std::string& filename, savvy::file::format default_format) { if (filename.size() >= 4) { const std::string ext = filename.substr(filename.size() - 4); if (ext == ".sav") return savvy::file::format::sav; else if (ext == ".bcf") return savvy::file::format::bcf; else if (ext == ".vcf") return savvy::file::format::vcf; } if (filename.size() >= 5) { const std::string ext = filename.substr(filename.size() - 5); if (ext == ".usav") return savvy::file::format::sav; else if (ext == ".ubcf") return savvy::file::format::bcf; } if (filename.size() >= 7) { const std::string ext = filename.substr(filename.size() - 7); if (ext == ".vcf.gz") return savvy::file::format::vcf; } return default_format; } int dosage_writer::clevel_from_filename(const std::string& filename, int default_clevel) { if (filename.size() >= 4) { const std::string ext = filename.substr(filename.size() - 4); if (ext == ".sav") return 6; else if (ext == ".bcf") return 6; else if (ext == ".vcf") return 0; } if (filename.size() >= 5) { const std::string ext = filename.substr(filename.size() - 5); if (ext == ".usav") return 0; else if (ext == ".ubcf") return 0; } if (filename.size() >= 7) { const std::string ext = filename.substr(filename.size() - 7); if (ext == ".vcf.gz") return 6; } return default_clevel; } bool dosage_writer::sites_match(const target_variant& t, const reference_site_info& r) { return t.pos == r.pos && t.alt == r.alt && t.ref == r.ref; } //bool dosage_writer::merge_temp_files(std::list& temp_file_paths, std::list& temp_emp_file_paths) //{ // std::list temp_files(temp_file_paths.begin(), temp_file_paths.end()); // std::list temp_emp_files(temp_emp_file_paths.begin(), temp_emp_file_paths.end()); // std::for_each(temp_file_paths.begin(), temp_file_paths.end(), [](std::string&s) { std::remove(s.c_str()); }); // std::for_each(temp_emp_file_paths.begin(), temp_emp_file_paths.end(), [](std::string&s) { std::remove(s.c_str()); }); // return merge_temp_files(temp_files, temp_emp_files); //} bool dosage_writer::merge_temp_files(std::list& temp_files, std::list& temp_emp_files) { if (temp_files.empty()) return false; for (auto it = temp_files.begin(); it != temp_files.end(); ++it) it->reset_bounds(savvy::slice_bounds(0)); for (auto it = temp_emp_files.begin(); it != temp_emp_files.end(); ++it) it->reset_bounds(savvy::slice_bounds(0)); savvy::variant out_var; savvy::variant out_var_emp; savvy::compressed_vector pasted_hds; savvy::compressed_vector partial_hds; std::vector pasted_lds; std::vector partial_lds; std::vector pasted_gt; std::vector partial_gt; std::size_t max_ploidy = 0; int good_count = temp_files.size(); while (good_count == temp_files.size()) { float s_cs{}, s_x{}, s_xx{}, loo_s_x{}, loo_s_xx{}, loo_s_y{}, loo_s_yy{}, loo_s_xy{}; std::size_t n{}; bool is_typed = false; pasted_hds.clear(); good_count = 0; for (auto it = temp_files.begin(); it != temp_files.end(); ++it) { bool read_succeeded = it->read(out_var).good(); good_count += (int)read_succeeded; out_var.get_format("HDS", partial_hds); // verify max ploidy is consistent across all temp files if (max_ploidy == 0) max_ploidy = partial_hds.size() / it->samples().size(); if (read_succeeded && max_ploidy != (partial_hds.size() / it->samples().size())) return std::cerr << "Error: max ploidy is not consistent across temp files. This should never happen. Please report." << std::endl, false; std::size_t old_size = pasted_hds.size(); pasted_hds.resize(old_size + partial_hds.size()); for (auto jt = partial_hds.begin(); jt != partial_hds.end(); ++jt) pasted_hds[old_size + jt.offset()] = *jt; float tmp; if (out_var.get_info("S_X", tmp)) s_x += tmp; if (out_var.get_info("S_XX", tmp)) s_xx += tmp; if (out_var.get_info("S_CS", tmp)) s_cs += tmp; if (out_var.get_info("LOO_S_X", tmp)) { loo_s_x += tmp; if (out_var.get_info("LOO_S_XX", tmp)) loo_s_xx += tmp; if (out_var.get_info("LOO_S_Y", tmp)) loo_s_y += tmp; // if (out_var.get_info("LOO_S_YY", tmp)) loo_s_yy += tmp; if (out_var.get_info("LOO_S_XY", tmp)) loo_s_xy += tmp; is_typed = true; } std::int64_t tmp_int; if (out_var.get_info("AN", tmp_int)) n += tmp_int; } loo_s_yy = loo_s_y; if (good_count) { if (good_count < temp_files.size()) return std::cerr << "Error: record mismatch in temp files" << std::endl, false; out_var.remove_info("S_X"); out_var.remove_info("S_XX"); out_var.remove_info("S_CS"); out_var.remove_info("AN"); //std::size_t n = pasted_hds.size() - std::count_if(pasted_hds.begin(), pasted_hds.end(), [](const float& v) { return std::isnan(v); }); // float s_x = std::accumulate(pasted_hds.begin(), pasted_hds.end(), 0.f); // float s_xx = std::inner_product(pasted_hds.begin(), pasted_hds.end(), pasted_hds.begin(), 0.f); float af = s_x / n; out_var.set_info("AF", af); out_var.set_info("MAF", af > 0.5f ? 1.f - af : af); out_var.set_info("AVG_CS", s_cs / n); out_var.set_info("R2", calc_r2(s_x, s_xx, n)); if (has_good_r2(out_var)) { if (is_typed) { assert(std::find_if(out_var.info_fields().begin(), out_var.info_fields().end(), [](const std::pair& v) { return v.first == "TYPED"; }) != out_var.info_fields().end()); out_var.remove_info("LOO_S_X"); out_var.remove_info("LOO_S_XX"); out_var.remove_info("LOO_S_Y"); out_var.remove_info("LOO_S_YY"); out_var.remove_info("LOO_S_XY"); float er2 = calc_er2(loo_s_x, loo_s_xx, loo_s_y, loo_s_yy, loo_s_xy, n); out_var.set_info("ER2", er2); float gt_af = loo_s_y / n; if (gt_af > 0.f && gt_af < 1.f) { int bin = std::max(0, static_cast(-std::log10(gt_af > 0.5f ? 1.f - gt_af : gt_af))); if (accuracy_stats_.size() <= bin) accuracy_stats_.resize(bin + 1); accuracy_stats_[bin].er2_sum += er2; ++(accuracy_stats_[bin].n_var); } if (emp_out_file_) { pasted_lds.clear(); pasted_gt.clear(); pasted_lds.reserve(n); pasted_gt.reserve(n); int good_count_emp = 0; for (auto it = temp_emp_files.begin(); it != temp_emp_files.end(); ++it) { good_count_emp += (int)it->read(out_var_emp).good(); out_var_emp.get_format("LDS", partial_lds); for (auto jt = partial_lds.begin(); jt != partial_lds.end(); ++jt) pasted_lds.push_back(*jt); out_var_emp.get_format("GT", partial_gt); for (auto jt = partial_gt.begin(); jt != partial_gt.end(); ++jt) pasted_gt.push_back(*jt); } if (good_count_emp < temp_emp_files.size()) return std::cerr << "Error: record mismatch in empirical temp files" << std::endl, false; if (pasted_hds.size() != pasted_gt.size() || pasted_lds.size() != pasted_gt.size()) return std::cerr << "Error: Merged HDS, LDS, and GT are not consistent. This should never happen. Please report." << std::endl, false; out_var_emp.set_format("GT", pasted_gt); out_var_emp.set_format("LDS", pasted_lds); emp_out_file_->write(out_var_emp); } } if (sites_out_file_) { savvy::variant site_var; dynamic_cast(site_var) = out_var; sites_out_file_->write(site_var); } set_format_fields(out_var, pasted_hds); out_file_ << out_var; } } } int bad_count = 0; for (auto it = temp_files.begin(); it != temp_files.end(); ++it) bad_count += (int)it->bad(); if (bad_count || !out_file_.good()) return std::cerr << "Error: I/O failed while merging" << std::endl, false; if (emp_out_file_) { bad_count = 0; for (auto it = temp_emp_files.begin(); it != temp_emp_files.end(); ++it) bad_count += (int)it->bad(); if (bad_count || !emp_out_file_->good()) return std::cerr << "Error: I/O failed while merging empirical" << std::endl, false; } return true; } bool dosage_writer::has_good_r2(savvy::site_info& site) { if (min_r2_ >= 0.f) { float r2 = -1.f; site.get_info("R2", r2); if (r2 >= min_r2_) return true; return false; } return true; } bool dosage_writer::mean_impute(savvy::compressed_vector& sparse_dosages) { std::int64_t n = sparse_dosages.size(); float s = 0.f; for (auto it = sparse_dosages.begin(); it != sparse_dosages.end(); ++it) { if (savvy::typed_value::is_special_value(*it)) --n; else s += *it; } if (n > 0) { float mean = s / n; for (auto it = sparse_dosages.begin(); it != sparse_dosages.end(); ++it) { if (savvy::typed_value::is_missing(*it)) *it = mean; } return true; } return false; } bool dosage_writer::write_dosages(const full_dosages_results& hmm_results, const std::vector& tar_variants, const std::vector& tar_only_variants, std::pair observed_range, const reduced_haplotypes& full_reference_data, const savvy::region& impute_region) { assert(hmm_results.dimensions()[0] == full_reference_data.variant_size()); variant_update_ctx update_context; savvy::variant out_var; savvy::variant out_var_emp; assert(!tar_variants.empty()); // std::vector dosages(tar_variants[0].gt.size()); // std::vector loo_dosages(tar_variants[0].gt.size()); savvy::compressed_vector sparse_dosages; const std::vector empty_gt_vec; const std::vector empty_loo_vec; assert(!is_temp_file_ || observed_range.first != 0 || observed_range.second != tar_variants[0].gt.size()); auto tar_it = tar_variants.begin(); auto tar_only_it = tar_only_variants.begin(); std::size_t i = 0; while (tar_it != tar_variants.end() && tar_it->pos < impute_region.from()) ++tar_it; while (tar_only_it != tar_only_variants.end() && tar_only_it->pos < impute_region.from()) ++tar_only_it; for (auto ref_it = full_reference_data.begin(); ref_it != full_reference_data.end(); ++ref_it,++i) { assert(i == ref_it.global_idx()); while(tar_only_it != tar_only_variants.end() && tar_only_it->pos <= ref_it->pos) { out_var = savvy::site_info(tar_only_it->chrom, tar_only_it->pos, tar_only_it->ref, {tar_only_it->alt}, tar_only_it->id); std::vector observed(tar_only_it->gt.begin() + observed_range.first, tar_only_it->gt.begin() + observed_range.second); sparse_dosages.assign(observed.begin(), observed.end(), savvy::typed_value::reserved_transformation_functor()); if (mean_impute(sparse_dosages)) { set_info_fields(out_var, sparse_dosages, {}, observed); if (has_good_r2(out_var)) { if (sites_out_file_) { savvy::variant site_var; dynamic_cast(site_var) = out_var; sites_out_file_->write(site_var); } set_format_fields(out_var, sparse_dosages); out_file_ << out_var; } } ++tar_only_it; } bool ref_matches_tar = tar_it != tar_variants.end() && sites_match(*tar_it, *ref_it); // for (std::size_t j = 0; j < dosages.size(); ++j) // dosages[j] = float(std::int16_t(hmm_results.dosage(i, j) * bin_scalar_ + 0.5f)) / bin_scalar_; // // if (ref_matches_tar) // { // for (std::size_t j = 0; j < loo_dosages.size(); ++j) // loo_dosages[j] = float(std::int16_t(hmm_results.loo_dosage(tar_idx, j) * bin_scalar_ + 0.5f)) / bin_scalar_; // } out_var = savvy::site_info(ref_it->chrom, ref_it->pos, ref_it->ref, {ref_it->alt}, ref_it->id); assert(!std::isnan(hmm_results.dosages_[i][0])); sparse_dosages.assign(hmm_results.dosages_[i].begin(), hmm_results.dosages_[i].end()); if (ref_matches_tar) { assert(!std::isnan(hmm_results.loo_dosages_[tar_it - tar_variants.begin()][0])); std::vector observed(tar_it->gt.begin() + observed_range.first, tar_it->gt.begin() + observed_range.second); set_info_fields(out_var, sparse_dosages, hmm_results.loo_dosages_[tar_it - tar_variants.begin()], observed); // TODO: do not store loo_dosages outside impute region. if (emp_out_file_ && has_good_r2(out_var)) { out_var_emp = savvy::site_info(ref_it->chrom, ref_it->pos, ref_it->ref, {ref_it->alt}, ref_it->id); out_var_emp.set_info("TYPED", std::vector()); out_var_emp.set_info("IMPUTED", std::vector()); out_var_emp.set_format("GT", observed); out_var_emp.set_format("LDS", hmm_results.loo_dosages_[tar_it - tar_variants.begin()]); emp_out_file_->write(out_var_emp); } ++tar_it; } else { set_info_fields(out_var, sparse_dosages, {}, {}); out_var_emp.set_info("IMPUTED", std::vector()); } if (has_good_r2(out_var)) { if (sites_out_file_) { savvy::variant site_var; dynamic_cast(site_var) = out_var; sites_out_file_->write(site_var); } set_format_fields(out_var, sparse_dosages); out_file_ << out_var; } } assert(tar_it == tar_variants.end() || tar_it->pos > impute_region.to()); while(tar_only_it != tar_only_variants.end() && tar_only_it->pos <= impute_region.to()) { out_var = savvy::site_info(tar_only_it->chrom, tar_only_it->pos, tar_only_it->ref, {tar_only_it->alt}, tar_only_it->id); std::vector observed(tar_only_it->gt.begin() + observed_range.first, tar_only_it->gt.begin() + observed_range.second); sparse_dosages.assign(observed.begin(), observed.end(), savvy::typed_value::reserved_transformation_functor()); if (mean_impute(sparse_dosages)) { set_info_fields(out_var, sparse_dosages, {}, observed); if (has_good_r2(out_var)) { if (sites_out_file_) { savvy::variant site_var; dynamic_cast(site_var) = out_var; sites_out_file_->write(site_var); } set_format_fields(out_var, sparse_dosages); out_file_ << out_var; } } ++tar_only_it; } return out_file_.good(); } float dosage_writer::calc_r2(double s_x, double s_xx, std::size_t n) { double af = s_x / n; double denom = af * (1. - af); float r2 = 0.f; //savvy::typed_value::missing_value(); if (denom > 0.) r2 = float((std::max(0., s_xx - s_x * s_x / n) / n) / denom); return r2; } float dosage_writer::calc_er2(double s_x, double s_xx, double s_y, double s_yy, double s_xy, std::size_t n) { // (n * Sum xy - Sum x * Sum y)^2 // r^2 = ------------------------------------------------------------------- // (n * Sum xx - Sum x * Sum x) * (n * Sum yy - Sum y * Sum y) float emp_r2 = 0.f; //savvy::typed_value::missing_value(); double denom = std::max(0., n * s_xx - s_x * s_x) * std::max(0., n * s_yy - s_y * s_y); if (denom > 0.) { double num = (n * s_xy - s_x * s_y); emp_r2 = float(num * num / denom); } return emp_r2; } void dosage_writer::print_mean_er2(std::ostream& os) const { os << "Mean ER2: "; for (auto it = accuracy_stats_.begin(); it != accuracy_stats_.end(); ++it) { os << " "; if (it->n_var) os << (it->er2_sum / it->n_var); else os << "."; } os << std::endl; } void dosage_writer::set_info_fields(savvy::variant& out_var, const savvy::compressed_vector& sparse_dosages, const std::vector& loo_dosages, const std::vector& observed) { std::size_t n = sparse_dosages.size(); assert(n); float s_x = std::accumulate(sparse_dosages.begin(), sparse_dosages.end(), 0.f, plus_ignore_missing()); float s_xx = std::inner_product(sparse_dosages.begin(), sparse_dosages.end(), sparse_dosages.begin(), 0.f, plus_ignore_missing(), std::multiplies()); float s_cs(sparse_dosages.size() - sparse_dosages.non_zero_size()); for (auto it = sparse_dosages.begin(); it != sparse_dosages.end(); ++it) { if (savvy::typed_value::is_end_of_vector(*it)) --n; else s_cs += *it > 0.5f ? *it : 1.f - *it; } float af = s_x / n; if (is_temp_file_) { out_var.set_info("AN", std::int64_t(n)); out_var.set_info("S_X", s_x); out_var.set_info("S_XX", s_xx); out_var.set_info("S_CS", s_cs); } else { out_var.set_info("AF", af); out_var.set_info("MAF", af > 0.5f ? 1.f - af : af); out_var.set_info("AVG_CS", s_cs / n); out_var.set_info("R2", calc_r2(s_x, s_xx, n)); } if (loo_dosages.size()) { assert(observed.size() == loo_dosages.size()); // sparse_loo_dosages.assign(loo_dosages.begin(), loo_dosages.end()); s_x = std::accumulate(loo_dosages.begin(), loo_dosages.end(), 0.f, plus_ignore_missing()); s_xx = std::inner_product(loo_dosages.begin(), loo_dosages.end(), loo_dosages.begin(), 0.f, plus_ignore_missing(), std::multiplies()); float s_y = (float)std::accumulate(observed.begin(), observed.end(), std::int32_t(0), plus_ignore_missing()); // since observed can only be 0 or 1, s_yy is the same as s_y float s_yy = s_y; // std::inner_product(sparse_gt.begin(), sparse_gt.end(), sparse_gt.begin(), 0.f); // TODO: allow for missing oberserved genotypes. float s_xy = std::inner_product(loo_dosages.begin(), loo_dosages.end(), observed.begin(), 0.f, plus_ignore_missing(), std::multiplies()); // float s_xy = 0.f; // for (auto it = ctx.sparse_gt.begin(); it != ctx.sparse_gt.end(); ++it) // s_xy += *it * loo_dosages[it.offset()]; if (is_temp_file_) { out_var.set_info("LOO_S_X", s_x); out_var.set_info("LOO_S_XX", s_xx); out_var.set_info("LOO_S_Y", s_y); out_var.set_info("LOO_S_YY", s_yy); out_var.set_info("LOO_S_XY", s_xy); } else { float er2 = calc_er2(s_x, s_xx, s_y, s_yy, s_xy, n); out_var.set_info("ER2", er2); float gt_af = s_y / n; if (gt_af > 0.f && gt_af < 1.f) { int bin = std::max(0, static_cast(-std::log10(gt_af > 0.5f ? 1.f - gt_af : gt_af))); if (accuracy_stats_.size() <= bin) accuracy_stats_.resize(bin + 1); accuracy_stats_[bin].er2_sum += er2; ++(accuracy_stats_[bin].n_var); } } } if (observed.size()) out_var.set_info("TYPED", std::vector()); if (loo_dosages.size() || observed.empty()) out_var.set_info("IMPUTED", std::vector()); } void dosage_writer::set_format_fields(savvy::variant& out_var, savvy::compressed_vector& sparse_dosages) { std::size_t stride = sparse_dosages.size() / n_samples_; if (fmt_field_set_.find("GT") != fmt_field_set_.end()) { out_var.set_format("HDS", {}); sparse_gt_.assign(sparse_dosages.value_data(), sparse_dosages.value_data() + sparse_dosages.non_zero_size(), sparse_dosages.index_data(), sparse_dosages.size(), [](float v) { if (savvy::typed_value::is_end_of_vector(v)) return savvy::typed_value::end_of_vector_value(); // else if (savvy::typed_value::is_missing(v)) // TODO: This would be necessary without mean-imputation of target only variants // return savvy::typed_value::missing_value(); return std::int8_t(v < 0.5f ? 0 : 1); }); out_var.set_format("GT", sparse_gt_); } if (fmt_field_set_.find("HDS") != fmt_field_set_.end()) { out_var.set_format("HDS", sparse_dosages); } else { out_var.set_format("HDS", {}); } if (fmt_field_set_.find("GP") != fmt_field_set_.end() || fmt_field_set_.find("SD") != fmt_field_set_.end()) { // set dense dosage vector dense_zero_vec_.resize(sparse_dosages.size()); for (auto it = sparse_dosages.begin(); it != sparse_dosages.end(); ++it) dense_zero_vec_[it.offset()] = *it; std::vector& dense_hds = dense_zero_vec_; if (fmt_field_set_.find("GP") != fmt_field_set_.end()) { if (stride == 1) { // All samples are haploid dense_float_vec_.resize(n_samples_ * 2); for (std::size_t i = 0; i < n_samples_; ++i) { std::size_t dest_idx = i * 2; dense_float_vec_[dest_idx] = 1.f - dense_hds[i]; dense_float_vec_[dest_idx + 1] = dense_hds[i]; } } else if (stride == 2) { dense_float_vec_.resize(n_samples_ * 3); for (std::size_t i = 0; i < n_samples_; ++i) { std::size_t src_idx = i * 2; std::size_t dest_idx = i * 3; float x = dense_hds[src_idx]; float y = dense_hds[src_idx + 1]; if (savvy::typed_value::is_end_of_vector(y)) { // haploid dense_float_vec_[dest_idx] = 1.f - x; dense_float_vec_[dest_idx + 1] = x; dense_float_vec_[dest_idx + 2] = y; } else { // diploid dense_float_vec_[dest_idx] = (1.f - x) * (1.f - y); dense_float_vec_[dest_idx + 1] = x * (1.f - y) + y * (1.f - x); dense_float_vec_[dest_idx + 2] = x * y; } } } out_var.set_format("GP", dense_float_vec_); } if (fmt_field_set_.find("SD") != fmt_field_set_.end()) { dense_float_vec_.resize(n_samples_); if (stride == 1) { // All samples are haploid for (std::size_t i = 0; i < n_samples_; ++i) { dense_float_vec_[i] = dense_hds[i] * (1.f - dense_hds[i]); } out_var.set_format("SD", dense_float_vec_); } else if (stride == 2) { for (std::size_t i = 0; i < dense_hds.size(); i += 2) { float x = dense_hds[i]; float y = dense_hds[i + 1]; if (savvy::typed_value::is_end_of_vector(y)) // haploid dense_float_vec_[i / 2] = x * (1.f - x); else // diploid dense_float_vec_[i / 2] = x * (1.f - x) + y * (1.f - y); } out_var.set_format("SD", dense_float_vec_); } else { // TODO: suppress error excessive error messages std::cerr << "Error: only haploid and diploid samples are supported when generating SD\n"; } } // unset dense dosage vector for (auto it = sparse_dosages.begin(); it != sparse_dosages.end(); ++it) dense_zero_vec_[it.offset()] = 0.f; } if (fmt_field_set_.find("DS") != fmt_field_set_.end()) { savvy::stride_reduce(sparse_dosages, sparse_dosages.size() / n_samples_, savvy::plus_eov()); out_var.set_format("DS", sparse_dosages); } } Minimac4-4.1.6/src/dosage_writer.hpp000066400000000000000000000066561453314643500173460ustar00rootroot00000000000000#ifndef MINIMAC4_DOSAGE_WRITER_HPP #define MINIMAC4_DOSAGE_WRITER_HPP #include "variant.hpp" #include "unique_haplotype.hpp" #include "hidden_markov_model.hpp" // TODO: change imputed data class #include #include #include class dosage_writer { private: struct accuracy_statistics { double er2_sum = 0.; std::size_t n_var = 0; }; savvy::writer out_file_; std::unique_ptr emp_out_file_; std::unique_ptr sites_out_file_; std::unordered_set fmt_field_set_; std::vector accuracy_stats_; std::size_t n_samples_ = 0; float min_r2_ = -1.f; bool is_temp_file_; // buffers savvy::compressed_vector sparse_gt_; std::vector dense_float_vec_; std::vector dense_zero_vec_; struct variant_update_ctx { savvy::compressed_vector sparse_gt; savvy::compressed_vector sparse_dosages; std::vector gp_vec; }; public: dosage_writer(const std::string& file_path, const std::string& emp_file_path, const std::string& sites_file_path, savvy::file::format file_format, std::uint8_t out_compression, const std::vector& sample_ids, const std::vector& fmt_fields, const std::string& chromosome, float min_r2, bool is_temp); bool merge_temp_files(std::list& temp_files, std::list& temp_emp_files); bool merge_temp_files(std::list& temp_file_paths, std::list& temp_emp_file_paths); bool write_dosages(const full_dosages_results& hmm_results, const std::vector& tar_variants, const std::vector& tar_only_variants, std::pair observed_range, const reduced_haplotypes& full_reference_data, const savvy::region& impute_region); void print_mean_er2(std::ostream& os) const; private: static bool mean_impute(savvy::compressed_vector& sparse_dosages); static std::vector> gen_headers(const std::vector& fmt_fields, const std::string& chromosome, bool is_temp); static std::vector> gen_emp_headers(const std::string& chromosome); static savvy::file::format format_from_filename(const std::string& filename, savvy::file::format default_format); static int clevel_from_filename(const std::string& filename, int default_clevel); static bool sites_match(const target_variant& t, const reference_site_info& r); bool has_good_r2(savvy::site_info& site); static float calc_er2(double s_x, double s_xx, double s_y, double s_yy, double s_xy, std::size_t n); static float calc_r2(double s_x, double s_xx, std::size_t n); void set_info_fields(savvy::variant& out_var, const savvy::compressed_vector& sparse_dosages, const std::vector& loo_dosages, const std::vector& observed); void set_format_fields(savvy::variant& out_var, savvy::compressed_vector& sparse_dosages); struct plus_ignore_missing { float operator()(const float& l, const float& r) { if (std::isnan(r)) return l; if (std::isnan(l)) return r; return l + r; } std::int32_t operator()(const std::int32_t& l, const std::int32_t& r) { if (r < 0) return l; if (l < 0) return r; return l + r; } }; }; #endif // MINIMAC4_DOSAGE_WRITER_HPP Minimac4-4.1.6/src/getopt_wrapper.hpp000066400000000000000000000040511453314643500175350ustar00rootroot00000000000000#ifndef GETOPT_WRAPPER_HPP #define GETOPT_WRAPPER_HPP #include #include #include #include #include #include class getopt_wrapper { public: struct option_with_desc : public ::option { const char* description; option_with_desc(const char* _name, int _has_arg, int* _flag, int _val, const char* _description) { name = _name; has_arg = _has_arg; flag = _flag; val = _val; description = _description; } }; protected: std::vector