diff --git a/.clang-format b/.clang-format deleted file mode 100644 index a08740ca0..000000000 --- a/.clang-format +++ /dev/null @@ -1,142 +0,0 @@ ---- -AccessModifierOffset: -4 -AlignAfterOpenBracket: Align -AlignArrayOfStructures: Right -AlignConsecutiveAssignments: AcrossComments -AlignConsecutiveBitFields: AcrossComments -AlignConsecutiveMacros: AcrossComments -AlignConsecutiveDeclarations: AcrossComments -AlignEscapedNewlines: Right -AlignOperands: true -AlignTrailingComments: true -AllowAllArgumentsOnNextLine: false -AllowAllConstructorInitializersOnNextLine: true -AllowAllParametersOfDeclarationOnNextLine: false -AllowShortBlocksOnASingleLine: Never -AllowShortCaseLabelsOnASingleLine: false -AllowShortEnumsOnASingleLine: false -AllowShortFunctionsOnASingleLine: Inline -AllowShortIfStatementsOnASingleLine: Never -AllowShortLambdasOnASingleLine: All -AllowShortLoopsOnASingleLine: false -AlwaysBreakAfterReturnType: None -AlwaysBreakBeforeMultilineStrings: true -AlwaysBreakTemplateDeclarations: Yes -BinPackArguments: false -BinPackParameters: false -BitFieldColonSpacing: Both -BreakBeforeBraces: Custom -BreakBeforeConceptDeclarations: true -BraceWrapping: - AfterCaseLabel: true - AfterClass: true - AfterControlStatement: Always - AfterEnum: true - AfterFunction: true - AfterNamespace: true - AfterObjCDeclaration: true - AfterStruct: true - AfterUnion: true - AfterExternBlock: true - BeforeCatch: true - BeforeElse: true - BeforeLambdaBody: true - BeforeWhile: true - IndentBraces: false - SplitEmptyFunction: false - SplitEmptyRecord: false - SplitEmptyNamespace: false -BreakBeforeBinaryOperators: None -BreakBeforeConceptDeclarations: true -BreakBeforeInheritanceComma: true -BreakBeforeTernaryOperators: true -BreakConstructorInitializers: AfterColon -BreakInheritanceList: AfterColon -BreakStringLiterals: true -ColumnLimit: 120 -#CommentPragmas: 'REQUIRES' -CommentPragmas: \/\/! -CompactNamespaces: false -ConstructorInitializerAllOnOneLineOrOnePerLine: true -ConstructorInitializerIndentWidth: 2 -ContinuationIndentWidth: 2 -Cpp11BracedListStyle: true -DeriveLineEnding: false -DerivePointerAlignment: false -DisableFormat: false -EmptyLineAfterAccessModifier: Never -EmptyLineBeforeAccessModifier: LogicalBlock -ExperimentalAutoDetectBinPacking: false -FixNamespaceComments: true -ForEachMacros: - - foreach - - Q_FOREACH - - BOOST_FOREACH -IncludeBlocks: Regroup -IncludeCategories: - - Regex: '^ /dev/null - sudo add-apt-repository --no-update --yes ppa:ubuntu-toolchain-r/ppa - sudo add-apt-repository --no-update --yes ppa:ubuntu-toolchain-r/test - sudo apt-get update - - - name: Install CMake - run: sudo apt-get install --yes cmake - - - name: Install ccache - run: sudo apt-get install --yes ccache - - - name: Install compiler ${{ matrix.install }} - run: sudo apt-get install --yes ${{ matrix.install }} - - - name: Load ccache - if: matrix.name != 'clang_format' - uses: actions/cache@v2 - with: - path: .ccache - key: ${{ runner.os }}-${{ matrix.name }}-ccache-${{ github.ref }}-${{ github.run_number }} - # Restoring: From current branch, otherwise from base branch, otherwise from any branch. - restore-keys: | - ${{ runner.os }}-${{ matrix.name }}-ccache-${{ github.ref }} - ${{ runner.os }}-${{ matrix.name }}-ccache-${{ github.base_ref }} - ${{ runner.os }}-${{ matrix.name }}-ccache- - - - name: Tool versions - run: | - env cmake --version - env ${{ matrix.cxx }} --version - - - name: Configure tests - env: - CXX: ${{ matrix.cxx }} - CC: ${{ matrix.cc }} - run: | - mkdir build - cd build - cmake ../lambda -DLAMBDA_COMPILE_THREADS=2 -DLAMBDA_NATIVE_BUILD=OFF ${{ matrix.cmake_flags }} -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_C_COMPILER_LAUNCHER=ccache - - - name: Build tests - if: matrix.name != 'clang_format' - env: - CCACHE_BASEDIR: ${{ github.workspace }} - CCACHE_DIR: ${{ github.workspace }}/.ccache - CCACHE_COMPRESS: true - CCACHE_COMPRESSLEVEL: 6 - CCACHE_MAXSIZE: 500M - run: | - ccache -p || true - cd build - make -k -j2 cli_test - ccache -s || true - - - name: Run tests - if: matrix.name != 'clang_format' - run: | - cd build - ctest . -j2 --output-on-failure - - name: Run Format Check - if: matrix.name == 'clang_format' - run: | - cd build - make check_format diff --git a/.github/workflows/ci_macos.yml b/.github/workflows/ci_macos.yml deleted file mode 100644 index 78a70b013..000000000 --- a/.github/workflows/ci_macos.yml +++ /dev/null @@ -1,99 +0,0 @@ -name: Lambda CI on macOS - -on: - push: - pull_request: - -env: - CMAKE_VERSION: 3.10.0 - SHARG_NO_VERSION_CHECK: 1 - TZ: Europe/Berlin - -defaults: - run: - shell: bash -ex {0} - -jobs: - build: - name: ${{ matrix.name }} - runs-on: macos-13 - timeout-minutes: 120 - strategy: - fail-fast: false - matrix: - include: - - name: "gcc12" - cxx: "g++-12" - cc: "gcc-12" - build_type: Release - - - name: "gcc11" - cxx: "g++-11" - cc: "gcc-11" - build_type: Release - - steps: - - name: Checkout - uses: actions/checkout@v2 - with: - path: lambda - fetch-depth: 2 - submodules: recursive - - - name: Configure Homebrew - uses: Homebrew/actions/setup-homebrew@master - - - name: Install ccache - run: brew install --overwrite ccache - - - name: Install compiler ${{ matrix.cxx }} - run: brew install --overwrite gcc@$(echo "${{ matrix.cxx }}" | sed "s/g++-//g") - - - name: Load ccache - uses: actions/cache@v2 - with: - path: .ccache - key: ${{ runner.os }}-${{ matrix.name }}-ccache-${{ github.ref }}-${{ github.run_number }} - # Restoring: From current branch, otherwise from base branch, otherwise from any branch. - restore-keys: | - ${{ runner.os }}-${{ matrix.name }}-ccache-${{ github.ref }} - ${{ runner.os }}-${{ matrix.name }}-ccache-${{ github.base_ref }} - ${{ runner.os }}-${{ matrix.name }}-ccache- - - - name: Tool versions - run: | - env cmake --version - env ${{ matrix.cxx }} --version - - - name: Configure tests - env: - CXX: ${{ matrix.cxx }} - CC: ${{ matrix.cc }} - run: | - mkdir build - cd build - cmake ../lambda -DLAMBDA_COMPILE_THREADS=3 -DLAMBDA_NATIVE_BUILD=OFF -DCMAKE_CXX_FLAGS="${{ matrix.cxx_flags }}" -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_C_COMPILER_LAUNCHER=ccache - - - name: Build tests - env: - CCACHE_BASEDIR: ${{ github.workspace }} - CCACHE_DIR: ${{ github.workspace }}/.ccache - CCACHE_COMPRESS: true - CCACHE_COMPRESSLEVEL: 6 - CCACHE_MAXSIZE: 500M - run: | - ccache -p || true - cd build - make -k -j3 cli_test - ccache -s || true - - - name: Run tests - env: - CCACHE_BASEDIR: ${{ github.workspace }} - CCACHE_DIR: ${{ github.workspace }}/.ccache - CCACHE_COMPRESS: true - CCACHE_COMPRESSLEVEL: 6 - CCACHE_MAXSIZE: 500M - run: | - cd build - ctest . -j3 --output-on-failure diff --git a/.gitmodules b/.gitmodules deleted file mode 100644 index d15f69c3e..000000000 --- a/.gitmodules +++ /dev/null @@ -1,18 +0,0 @@ -[submodule "seqan"] - path = submodules/seqan - url = ../../seqan/seqan.git -[submodule "submodules/fmindex-collection"] - path = submodules/fmindex-collection - url = ../../SGSSGene/fmindex-collection.git -[submodule "submodules/sharg-parser"] - path = submodules/sharg-parser - url = ../../seqan/sharg-parser -[submodule "submodules/biocpp-core"] - path = submodules/biocpp-core - url = ../../biocpp/biocpp-core -[submodule "submodules/biocpp-io"] - path = submodules/biocpp-io - url = ../../biocpp/biocpp-io -[submodule "submodules/cereal"] - path = submodules/cereal - url = ../../USCiLab/cereal diff --git a/CMakeLists.txt b/CMakeLists.txt deleted file mode 100644 index 49fa024cb..000000000 --- a/CMakeLists.txt +++ /dev/null @@ -1,87 +0,0 @@ -# =========================================================================== -# Lambda -# =========================================================================== - -cmake_minimum_required (VERSION 3.4.0) -string(ASCII 27 Esc) -set(ColourBold "${Esc}[1m") -set(ColourReset "${Esc}[m") -set(ColourRed "${Esc}[31m") - -message ("${ColourBold}Compiler Detection${ColourReset}") - -project (lambda3 CXX) - -# ---------------------------------------------------------------------------- -# Make "Release" the default cmake build type -# ---------------------------------------------------------------------------- - -if (NOT CMAKE_BUILD_TYPE) - set (CMAKE_BUILD_TYPE Release CACHE STRING - "Choose the type of build, options are: Debug Release RelWithDebInfo" - FORCE) -endif () - -# ---------------------------------------------------------------------------- -# Options -# ---------------------------------------------------------------------------- - -option (LAMBDA_WITH_BIFM "Include codepaths for bidirectional indexes." OFF) - -if (LAMBDA_WITH_BIFM) - add_definitions (-DLAMBDA_WITH_BIFM=1) -endif () - -# ---------------------------------------------------------------------------- -# Begin of dependency detection -# ---------------------------------------------------------------------------- - -message ("\n${ColourBold}Dependency detection${ColourReset}") - -if (EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/submodules/seqan/include/seqan/version.h") - set (CMAKE_INCLUDE_PATH - ${CMAKE_CURRENT_SOURCE_DIR}/submodules/seqan/include - ${CMAKE_INCLUDE_PATH}) - set (CMAKE_PREFIX_PATH - ${CMAKE_CURRENT_SOURCE_DIR}/submodules/seqan/util/cmake - ${CMAKE_PREFIX_PATH}) - set (CMAKE_MODULE_PATH - ${CMAKE_CURRENT_SOURCE_DIR}/submodules/seqan/util/cmake - ${CMAKE_MODULE_PATH}) - message (STATUS "Found a local SeqAn library provided with the Lambda source code.") - message ( " This will be preferred over system global headers.") -endif () - -# CEREAL -if (EXISTS ${CMAKE_SOURCE_DIR}/submodules/cereal) - set(BUILD_SANDBOX OFF) - set(BUILD_DOC OFF) - set(BUILD_TESTS OFF) - set(SKIP_PERFORMANCE_COMPARISON ON) - set(CEREAL_INSTALL OFF) - add_subdirectory(submodules/cereal) -endif () - -# ---------------------------------------------------------------------------- -# Add Lambda targets -# ---------------------------------------------------------------------------- - -add_subdirectory(src) - -# ---------------------------------------------------------------------------- -# Warn if cmake build type is not "Release" -# ---------------------------------------------------------------------------- - -if (NOT CMAKE_BUILD_TYPE STREQUAL Release) - message (STATUS "${ColourRed}CMAKE_BUILD_TYPE is not \"Release\", your binaries will be slow.${ColourReset}") -endif () - -# ---------------------------------------------------------------------------- -# Add Tests -# ---------------------------------------------------------------------------- - -message ("\n${ColourBold}Setting up unit tests${ColourReset}") - -enable_testing () -add_subdirectory (test EXCLUDE_FROM_ALL) - diff --git a/INFO b/INFO deleted file mode 100644 index 22c8ad7fd..000000000 --- a/INFO +++ /dev/null @@ -1,12 +0,0 @@ -Name: lambda -Author: Hannes Hauswedell -Maintainer: Hannes Hauswedell -License: AGPL v3 -Copyright: 2013-2023, Hannes Hauswedell; 2016-2023 Knut Reinert, FU-Berlin -Status: under development -Description: Lambda is a biological sequence aligner for searches -in protein, nucleotide or bisulfite-treated databases. It is highly -compatible to BLAST (bitscore and e-value statistics, tab separated and -verbose output formats), much faster than BLAST and many other comparable -tools and supports many other input and output formats, including -standards-conforming .sam and .bam and many compression types. diff --git a/LICENSE-AGPL3.rst b/LICENSE-AGPL3.rst deleted file mode 100644 index 980af45b4..000000000 --- a/LICENSE-AGPL3.rst +++ /dev/null @@ -1,671 +0,0 @@ -GNU Affero General Public License -================================= - -*Version 3, 19 November 2007* -*Copyright © 2007 Free Software Foundation, In* - -Everyone is permitted to copy and distribute verbatim copies -of this license document, but changing it is not allowed. - -Preamble --------- - -The GNU Affero General Public License is a free, copyleft license for -software and other kinds of works, specifically designed to ensure -cooperation with the community in the case of network server software. - -The licenses for most software and other practical works are designed -to take away your freedom to share and change the works. By contrast, -our General Public Licenses are 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. - -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. - -Developers that use our General Public Licenses protect your rights -with two steps: **(1)** assert copyright on the software, and **(2)** offer -you this License which gives you legal permission to copy, distribute -and/or modify the software. - -A secondary benefit of defending all users' freedom is that -improvements made in alternate versions of the program, if they -receive widespread use, become available for other developers to -incorporate. Many developers of free software are heartened and -encouraged by the resulting cooperation. However, in the case of -software used on network servers, this result may fail to come about. -The GNU General Public License permits making a modified version and -letting the public access it on a server without ever releasing its -source code to the public. - -The GNU Affero General Public License is designed specifically to -ensure that, in such cases, the modified source code becomes available -to the community. It requires the operator of a network server to -provide the source code of the modified version running there to the -users of that server. Therefore, public use of a modified version, on -a publicly accessible server, gives the public access to the source -code of the modified version. - -An older license, called the Affero General Public License and -published by Affero, was designed to accomplish similar goals. This is -a different license, not a version of the Affero GPL, but Affero has -released a new version of the Affero GPL which permits relicensing under -this license. - -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 Affero 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. Remote Network Interaction; Use with the GNU General Public License -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -Notwithstanding any other provision of this License, if you modify the -Program, your modified version must prominently offer all users -interacting with it remotely through a computer network (if your version -supports such interaction) an opportunity to receive the Corresponding -Source of your version by providing access to the Corresponding Source -from a network server at no charge, through some standard or customary -means of facilitating copying of software. This Corresponding Source -shall include the Corresponding Source for any work covered by version 3 -of the GNU General Public License that is incorporated pursuant to the -following paragraph. - -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 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 work with which it is combined will remain governed by version -3 of the GNU General Public License. - -14. Revised Versions of this License -~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - -The Free Software Foundation may publish revised and/or new versions of -the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details. -| -| You should have received a copy of the GNU Affero General Public License -| along with this program. If not, see . - -Also add information on how to contact you by electronic and paper mail. - -If your software can interact with users remotely through a computer -network, you should also make sure that it provides a way for users to -get its source. For example, if your program is a web application, its -interface could display a "Source" link that leads users to an archive -of the code. There are many ways you could offer source, and different -solutions will be better for different programs; see section 13 for the -specific requirements. - -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 AGPL, see -. diff --git a/LICENSE-BSD.rst b/LICENSE-BSD.rst deleted file mode 100644 index ab3650d7d..000000000 --- a/LICENSE-BSD.rst +++ /dev/null @@ -1,29 +0,0 @@ -BSD-License (3-clause) -====================== - - | Copyright (c) 2016-2019, Knut Reinert, Freie Universität Berlin - | All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - -* Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. -* Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. -* Neither the name of Knut Reinert or the FU Berlin nor the names of - its contributors may be used to endorse or promote products derived - from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE -FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -DAMAGE. diff --git a/LICENSE.rst b/LICENSE.rst deleted file mode 100644 index 1e139d243..000000000 --- a/LICENSE.rst +++ /dev/null @@ -1,44 +0,0 @@ -lambda copyright -================ -:: - - Copyright (c) 2013-2023, Hannes Hauswedell - Copyright (c) 2019-2023, Sara Hetzel - All rights reserved. - -Lambda is *free software*: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as -published by the Free Software Foundation, either version 3 of the -License, or (at your option) any later version. - -Lambda 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 file `LICENSE-AGPL3.rst <./LICENSE-AGPL3.rst>`__ or -http://www.gnu.org/licenses/ for a full text of the license and the -rights and obligations implied. - -Some of the contributions to Lambda are alternatively or additionally -:: - - Copyright (c) 2016-2020, Knut Reinert & Freie Universität Berlin - Copyright (c) 2019-2020, Knut Reinert & MPI für molekulare Genetik - -These are covered by the three clause BSD license as can be found in -the file `LICENSE-BSD.rst <./LICENSE-BSD.rst>`__. In cases of doubt -the terms of both licenses apply. - -submodules -========== - -When Lambda is distributed in binary form or when Lambda is distributed -in source form including its submodules, additional license terms apply. -See the respective files in the submodules folder: - -* submodules/biocpp-core/LICENSE.md -* submodules/biocpp-io/LICENSE -* submodules/cereal/LICENSE -* submodules/fmindex-collection/TODO -* submodules/seqan/LICENSE -* submodules/sharg-parser/LICENSE.md diff --git a/README.rst b/README.rst deleted file mode 100644 index e954445e5..000000000 --- a/README.rst +++ /dev/null @@ -1,102 +0,0 @@ -Lambda: the Local Aligner for Massive Biological DatA ------------------------------------------------------ - -Lambda is a versatile local aligner that can perform protein, nucleotide and bisulfite searches. It... - -* is highly compatible to BLAST (bit-score and e-value statistics, tab separated and verbose output formats) -* is much faster than BLAST and many other comparable tools -* supports many other input and output formats, including standards-conforming ``.sam`` and ``.bam`` and many compression types -* has special features for species annotation and taxonomic analysis -* is well-documented and easy to use (e.g. provides progress-bars and memory usage estimates) - -downloads and installation --------------------------- - -+------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------+ -| **Executables** | -+------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------+ -| .. image:: https://raw.githubusercontent.com/seqan/lambda/gh-pages/images_readme/appbar.disk.download.png | Pre-built executables for GNU/Linux, Mac and FreeBSD are available from the | -| :alt: Download Executables | `releases page `__. | -| :target: https://github.com/seqan/lambda/releases | | -| :width: 76px | | -+------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------+ -| **Source code** | -+------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------+ -| .. image:: https://raw.githubusercontent.com/seqan/lambda/gh-pages/images_readme/appbar.column.three.png | You can also build lambda from source which will result in binaries optimized for your | -| :alt: Build from source | specific system (and thus faster). For instructions, please see the | -| :target: https://github.com/seqan/lambda/wiki | `wiki `__. | -| :width: 76px | | -+------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------+ - -usage instructions ------------------- - - -Before you can search, you need to have an index. You can - -1. download and unzip a pre-built index from the `wiki `__; or -2. index one yourself (this can take some time but only has to be done once): - -:: - - % bin/lambda3 mkindexp -d db.fasta - -*(in case you want to create a nucleotide index, instead use* ``mkindexn`` *)* - -After that running Lambda is as simple as - -:: - - % bin/lambda3 searchp -q query.fasta -i db.fasta.lba - -*(in case you want to perform a nucleotide search, instead use* ``searchn`` *)* - -For a list of options, see the help pages: - -:: - - % bin/lambda3 --help - % bin/lambda3 COMMAND --help - -Advanced options are available via ``--full-help`` or the man pages, and more documentation is available -in the `wiki `__. - -authorship and copyright ------------------------- - -Lambda is developed by `Hannes Hauswedell `__ and `Sara Hetzel `__ . - -+------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------+ -| **Please always cite the publication, also if using Lambda in comparisons and pipelines** | -+------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------+ -| .. image:: https://raw.githubusercontent.com/seqan/lambda/gh-pages/images_readme/appbar.book.hardcover.open.png | *Lambda3: homology search for protein, nucleotide, and bisulfite-converted sequences*; | -| :alt: Please cite | Hannes Hauswedell, Sara Hetzel et al.; | -| :target: https://academic.oup.com/bioinformatics/article/40/3/btae097/7629128 | `Bioinformatics 2024 40 (3) `__; | -| :width: 76px | doi: 10.1093/bioinformatics/btae097 | -+------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------+ -| **The original Lambda publication (versions before 3)** | -+------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------+ -| .. image:: https://raw.githubusercontent.com/seqan/lambda/gh-pages/images_readme/appbar.book.hardcover.open.png | *Lambda: the local aligner for massive biological data*; | -| :alt: Please cite | Hannes Hauswedell, Jochen Singer, Knut Reinert; | -| :target: http://bioinformatics.oxfordjournals.org/content/30/17/i349.abstract | `Bioinformatics 2014 30 (17): i349-i355 `__; | -| :width: 76px | doi: 10.1093/bioinformatics/btu439 | -+------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------+ -| **Please respect the license of the software** | -+------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------+ -| .. image:: https://raw.githubusercontent.com/seqan/lambda/gh-pages/images_readme/copyleft.png | Lambda is Free and open source software, so you can use it for any purpose, free of charge. | -| :alt: Respect the license | However certain conditions apply when you (re-)distribute and/or modify Lambda, please respect the | -| :target: https://github.com/seqan/lambda/blob/master/LICENSE.rst | `license `__. | -| :width: 76px | | -+------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------+ - -feedback & updates ------------------- - -+-------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------+ -| .. image:: https://raw.githubusercontent.com/seqan/lambda/gh-pages/images_readme/appbar.social.github.octocat.png | You can ask questions and report bugs on the `github tracker `__ . | -| :alt: GitHub | Please also `subscribe `__ and/or star us! | -| :target: https://github.com/seqan/lambda/issues | | -| :width: 76px | | -+-------------------------------------------------------------------------------------------------------------------+--------------------------------------------------------------------------------------------------------------------+ - -*icons on this page by Austin Andrews / https://github.com/Templarian/WindowsIcons* diff --git a/images/arrow-down.png b/images/arrow-down.png new file mode 100644 index 000000000..5c55c6a8c Binary files /dev/null and b/images/arrow-down.png differ diff --git a/images/logo_fub.png b/images/logo_fub.png new file mode 100644 index 000000000..0043575e7 Binary files /dev/null and b/images/logo_fub.png differ diff --git a/images/logo_mpimg.png b/images/logo_mpimg.png new file mode 100644 index 000000000..7d8a0ed18 Binary files /dev/null and b/images/logo_mpimg.png differ diff --git a/images/logo_seqan.png b/images/logo_seqan.png new file mode 100644 index 000000000..a28a7f924 Binary files /dev/null and b/images/logo_seqan.png differ diff --git a/images/octocat-small.png b/images/octocat-small.png new file mode 100644 index 000000000..57c1e44f9 Binary files /dev/null and b/images/octocat-small.png differ diff --git a/images_readme/appbar.book.hardcover.open.png b/images_readme/appbar.book.hardcover.open.png new file mode 100644 index 000000000..4cb53c8b6 Binary files /dev/null and b/images_readme/appbar.book.hardcover.open.png differ diff --git a/images_readme/appbar.column.three.png b/images_readme/appbar.column.three.png new file mode 100644 index 000000000..d956ec61b Binary files /dev/null and b/images_readme/appbar.column.three.png differ diff --git a/images_readme/appbar.disk.download.png b/images_readme/appbar.disk.download.png new file mode 100644 index 000000000..22c0fb9f9 Binary files /dev/null and b/images_readme/appbar.disk.download.png differ diff --git a/images_readme/appbar.email.png b/images_readme/appbar.email.png new file mode 100644 index 000000000..3ad94af46 Binary files /dev/null and b/images_readme/appbar.email.png differ diff --git a/images_readme/appbar.social.github.octocat.png b/images_readme/appbar.social.github.octocat.png new file mode 100644 index 000000000..4d26610b6 Binary files /dev/null and b/images_readme/appbar.social.github.octocat.png differ diff --git a/images_readme/appbar.social.twitter.png b/images_readme/appbar.social.twitter.png new file mode 100644 index 000000000..969fa82bc Binary files /dev/null and b/images_readme/appbar.social.twitter.png differ diff --git a/images_readme/copyleft.png b/images_readme/copyleft.png new file mode 100644 index 000000000..668dde49f Binary files /dev/null and b/images_readme/copyleft.png differ diff --git a/index.html b/index.html new file mode 100644 index 000000000..93efc4cb6 --- /dev/null +++ b/index.html @@ -0,0 +1,215 @@ + + + + + + Lambda by seqan + + + + + + + + +
+
+

Lambda

+

Download

+ + + +

Resources

+ +
+
+

+Lambda: the Local Aligner for Massive Biological DatA

+ +

Lambda is a local aligner optimized for many query sequences and searches in protein space. It is compatible to + BLAST, but much faster than BLAST and many other comparable tools.

+ +

Downloads are available from the sidebar on the left. Lambda is Free and open source software, so you can use it for any purpose, free of charge. However certain conditions apply when you (re-)distribute or modify Lambda, please respect the license. Also, please cite the publication if you use Lambda anywhere in your academic work. Thank you!

+ +

The manual, build instructions and much more are available in the: ━━━┥ WIKI ┝━━━

+ +

+Publication

+ +

Lambda: the local aligner for massive biological data; Hannes Hauswedell, Jochen Singer, Knut Reinert; Bioinformatics 2014 30 (17): i349-i355; doi: 10.1093/bioinformatics/btu439

+ +

+News

+ +

+2018-02-05: Release of 1.9.4

+ +

Version 1.9.4 has just been released. It is a pre-release of the development branch and +has significant changes in the interface over 1.9.3 bringing it much closer to the final +interface of 2.0.0. There is now only a single lambda2-executable that offers sub-commands +for index creation and search. Many parameters are now auto-detected to improve usability +and manual-pages are automatically created and included in the package. +Furthermore our pre-built packages now include binaries with different optimisation levels +and automatically pick the fastest usable by your system. Since the interfaces are stabilising now, +the development branch has become the master branch on GitHub (the 1.0.* branch is available as the +stable branch). +Beyond those structural changes, numerous bugs were fixed and the speed of index creation was improved +significantly. +

+ +

+2017-06-29: Release of 1.9.3

+ +

Version 1.9.3 has just been released. It is a pre-release of the development branch and +offers numerous bug-fixes, additions for taxonomic analysis, speed improvements for short +sequences and a reduction of the required memory. Beyond that there are multiple usability +improvements including stricter argument parsing, better exception handling and +a check of the available memory against the estimated amount required so that users +are warned early on if they might run out during a long run. Lambda now informs you +when new versions become available so that you don't miss future updates. The index +format has changed and is not compatible to previous versions. +

+ +

+2017-01-10: Release of 1.9.2

+ +

Version 1.9.2 has just been released. It is a pre-release of the development branch and +offers new features for taxonomic analysis, including taxonomic ID retrieval and annotation, +as well as taxonomic binning via computation of the lowest common ancestor (LCA) of all matches of +each query sequence. More information on these features is available in the Wiki. The release also +includes a lot of changes to core algorithms to improve performance, however, these are not +yet active by default. Please provide feedback on the new release, especially the new features! +But also bear in mind that the 1.9.* series might be less stable than 1.0.* and that you need +to re-create the index files. +

+ +

+2017-01-09: Release of 1.0.1

+ +

Version 1.0.1 has just been released. It contains minor fixes and performance improvements. +It is fully compatible to the 0.9.* and 1.0.* series. +

+ + +

+2016-08-18: Release of 1.9.0

+ +

Version 1.9.0 has just been released. It is a pre-release of the development branch and comes with +very significant performance improvements. We are not publishing any numbers, +yet, because it is still in development, but you should see very big +differences immediately. Of course we are interested in your feedback so +please try out the new release! But also bear in mind that it might be less +stable than 1.0.0 and that you need to re-create the index files. +

+ +

+2016-08-18: Release of 1.0.0

+ +

Version 1.0.0 has just been released. It contains minor fixes and performance improvements. +It is fully compatible to the 0.9.* series. +

+ +

+2016-08-18: Git-History invalidated

+ +

There were some significant changes to the git repository, SeqAn is now only included as a git submodule. This means that +previous clones of the git repository are no longer valid and must be force-updated or cleanly re-cloned. Clone with the +--recursive parameter if you don't have SeqAn installed system-wide.

+ + +

+2016-04-08: Release of 0.9.4

+ +

Version 0.9.4 has just been released. It contains minor SAM/BAM fixes and additions, and it now runs on OpenBSD. Lambda can now also be built with Clang (as of version 3.8) +and the Intel Compiler (as of version 16.0.2). If there are no serious bugs, this version will soon become 1.0 and development of the new feature branch will begin.

+ +

+2015-12-11: Release of 0.9.3

+ +

Version 0.9.3 has just been released. This is mostly a bug-fix release. We have also added app tests and continuous integration builds to improve the +quality of Lambda and spot issues more quickly. Happy holiday season to all users who are affected :-)

+ +

+2015-11-27: Release of 0.9.2

+ +

Version 0.9.2 has just been released. We have implemented (long-awaited) support for the SAM and BAM formats! +And documentation on the different formats and their options has been added to the wiki. +The indexer now truncates sequence IDs by default which results in smaller indexes. If you use the pairwise format (.m0) +you might want to change this since your output files will only contain the shortened IDs otherwise; all other formats are not +effected (they truncate the IDs anyway). Head over to the releases +for a full list of changes and the downloads. Updated index files will be created next week (but old indexes are compatible).

+ + +

+2015-10-23: Release of 0.9.1

+ +

Version 0.9.1 has just been released. There is now support for memory-mapped file access to the database which enables sharing the memory between multiple instances of LAMBDA running on the same server. Also the construction of the index now uses a different algorithm which is faster and more memory efficient. See the Changelog for details. Users who built 0.9.0 from Source, please be aware that optimizations where not turned on by default, so please update to 0.9.1 and rebuild. Users of our binaries are not affected.

+ + +

+2015-09-15: Indexes prebuilt for 0.9.*

+ +

There are now pre-built indexes for NR, the Uniref databases and the Uniprot databases available in the wiki.

+ +

+2015-09-14: Release of 0.9.0

+ +

I am pleased to announce the availability of lambda-0.9.0. This is the first release based off SeqAn 2.0 with many bug-fixes and new features. See the Changelog for details. Please note that the indexes created with older versions are not compatible.

+ +
+ +
+ +
+ + + +

Hosted on GitHub Pages using the Dinky theme

+
+
+
+ + + + diff --git a/javascripts/scale.fix.js b/javascripts/scale.fix.js new file mode 100644 index 000000000..08716c006 --- /dev/null +++ b/javascripts/scale.fix.js @@ -0,0 +1,20 @@ +fixScale = function(doc) { + + var addEvent = 'addEventListener', + type = 'gesturestart', + qsa = 'querySelectorAll', + scales = [1, 1], + meta = qsa in doc ? doc[qsa]('meta[name=viewport]') : []; + + function fix() { + meta.content = 'width=device-width,minimum-scale=' + scales[0] + ',maximum-scale=' + scales[1]; + doc.removeEventListener(type, fix, true); + } + + if ((meta = meta[meta.length - 1]) && addEvent in doc) { + fix(); + scales = [.25, 1.6]; + doc[addEvent](type, fix, true); + } + +}; \ No newline at end of file diff --git a/params.json b/params.json new file mode 100644 index 000000000..55fe0ad5a --- /dev/null +++ b/params.json @@ -0,0 +1 @@ +{"name":"Lambda","tagline":"the Local Aligner for Massive Biological DatA ","body":"Lambda: the Local Aligner for Massive Biological DatA\r\n-----------------------------------------------------\r\n\r\nLambda is a local aligner optimized for many query sequences and searches in protein space. It is compatible to\r\n BLAST, but much faster than BLAST and many other comparable tools.\r\n\r\nThe latest stable version is available in the [releases] (https://github.com/seqan/lambda/releases). Lambda is Free and open source software, so you can use it for any purpose, free of charge. However certain conditions apply when you (re-)distribute or modify Lambda, please respect the license. Also, **please cite the publication** if you use Lambda anywhere in your academic work. Thank you!\r\n\r\nThe manual, build instructions and much more are available in the:\r\n\r\n**--------> [WIKI](https://github.com/seqan/lambda/wiki) <--------**\r\n\r\nReferences\r\n----------\r\n*Lambda: the local aligner for massive biological data*; Hannes Hauswedell, Jochen Singer, Knut Reinert; [Bioinformatics 2014 30 (17): i349-i355](http://bioinformatics.oxfordjournals.org/content/30/17/i349.abstract); doi: 10.1093/bioinformatics/btu439\r\n\r\n\r\nNews\r\n----\r\n\r\n#### 2015-09-14: Release of 0.9.0\r\n\r\nI am pleased to announce the availability of `lambda-0.9.0`. This is the first release based off SeqAn 2.0 with many bug-fixes and new features. See the [Changelog](https://github.com/seqan/lambda/wiki/changelog) for details. *Please note that the indexes created with older versions are not compatible.*\r\n","google":"","note":"Don't delete this file! It's used internally to help with page regeneration."} \ No newline at end of file diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt deleted file mode 100644 index 45ddb9fa4..000000000 --- a/src/CMakeLists.txt +++ /dev/null @@ -1,273 +0,0 @@ -# =========================================================================== -# SeqAn - The Library for Sequence Analysis -# =========================================================================== -# File: /sandbox/h4nn3s/apps/lambda/CMakeLists.txt -# -# CMakeLists.txt file for lambda. -# =========================================================================== - -# ---------------------------------------------------------------------------- -# App version -# ---------------------------------------------------------------------------- - -# change this after every release -set (SEQAN_APP_VERSION_MAJOR "3") -set (SEQAN_APP_VERSION_MINOR "1") -set (SEQAN_APP_VERSION_PATCH "0") - -# don't change the following -set (SEQAN_APP_VERSION "${SEQAN_APP_VERSION_MAJOR}.${SEQAN_APP_VERSION_MINOR}.${SEQAN_APP_VERSION_PATCH}") - -# adapt when necessary -set (MINIMUM_SEQAN_VERSION "2.3.1") - -# ---------------------------------------------------------------------------- -# App-Level Configuration -# ---------------------------------------------------------------------------- - -message ("\n${ColourBold}Build configuration${ColourReset}") - -message (STATUS "LAMBDA version is: ${SEQAN_APP_VERSION}") - -option (LAMBDA_STATIC_BUILD "Include all libraries in the binaries." OFF) -option (LAMBDA_WITH_BIFM "Include codepaths for bidirectional indexes." OFF) - -if (LAMBDA_STATIC_BUILD) - add_definitions (-DLAMBDA_STATIC_BUILD=1) - # apple does not support fully static builds, but at least libgcc and libstdc++ - if (APPLE) - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static-libgcc -static-libstdc++") - message (WARNING "WARNING: Builds on Mac are never fully static.") - else (APPLE) - set(CMAKE_FIND_LIBRARY_SUFFIXES ".a") - set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static") - endif (APPLE) - # on linux cmake adds -rdynamic automatically which clang can't handle in static builds - if (CMAKE_SYSTEM_NAME MATCHES "Linux") - SET(CMAKE_SHARED_LIBRARY_LINK_CXX_FLAGS "") - endif (CMAKE_SYSTEM_NAME MATCHES "Linux") -endif (LAMBDA_STATIC_BUILD) - -if (LAMBDA_WITH_BIFM) - add_definitions (-DLAMBDA_WITH_BIFM=1) -endif () - -message(STATUS "The following options are selected for the build:") -message( " LAMBDA_STATIC_BUILD ${LAMBDA_STATIC_BUILD}") -message( " LAMBDA_WITH_BIFM ${LAMBDA_WITH_BIFM}") -message(STATUS "Run 'cmake -LH' to get a comment on each option.") -message(STATUS "Remove CMakeCache.txt and re-run cmake with -DOPTIONNAME=ON|OFF to change an option.") - -# ---------------------------------------------------------------------------- -# Dependencies (continued) -# ---------------------------------------------------------------------------- - -# Search SeqAn and select dependencies. -find_package(OpenMP QUIET) -find_package(ZLIB QUIET) -find_package(SeqAn QUIET REQUIRED CONFIG) - -# BIO -find_package (biocpp COMPONENTS core io QUIET REQUIRED HINTS "${CMAKE_SOURCE_DIR}/submodules/biocpp-core/build_system") - -# SHARG -find_package (sharg QUIET REQUIRED HINTS "${CMAKE_SOURCE_DIR}/submodules/sharg-parser/build_system") - -# CEREAL -if (NOT EXISTS ${CMAKE_SOURCE_DIR}/submodules/cereal) - find_package(cereal QUIET REQUIRED) -endif () - -# SGS FMindex -add_subdirectory(../submodules/fmindex-collection fmindex-collection) - -message(STATUS "These dependencies were found:") -message( " BIOCPP-CORE ${BIOCPP_CORE_FOUND} ${BIOCPP_CORE_VERSION}") -message( " BIOCPP-IO ${BIOCPP_IO_FOUND} ${BIOCPP_IO_VERSION}") -message( " CEREAL ${CEREAL_FOUND} ${CEREAL_VERSION}") -message( " OPENMP ${OPENMP_FOUND} ${OpenMP_CXX_FLAGS}") -message( " SEQAN ${SEQAN_FOUND} ${SEQAN_VERSION_STRING}") -message( " SHARG ${SHARG_FOUND} ${SHARG_VERSION}") -message( " ZLIB ${ZLIB_FOUND} ${ZLIB_VERSION_STRING}") - -# Warn if Zlib was not found. -if (NOT ZLIB_FOUND) - message (WARNING "WARNING: Zlib not found. Building lambda without support for gzipped input and output (this includes support for .bam).") -endif (NOT ZLIB_FOUND) - -if (SEQAN_VERSION_STRING VERSION_LESS "${MINIMUM_SEQAN_VERSION}") - message (FATAL_ERROR "The minimum SeqAn version required is ${MINIMUM_SEQAN_VERSION}!") - return () -endif () - -message(STATUS "The requirements were met.") - -# ---------------------------------------------------------------------------- -# Compiler specifics -# ---------------------------------------------------------------------------- - -if (CMAKE_CXX_COMPILER_ID MATCHES "Clang") - set (SEQAN_CXX_FLAGS "${SEQAN_CXX_FLAGS} -ftemplate-depth-1024") - - # do not warn for variable length arrays - set (SEQAN_CXX_FLAGS "${SEQAN_CXX_FLAGS} -Wno-vla-extension") -endif () - -if (CMAKE_CXX_COMPILER_ID MATCHES "GNU") - # do not warn for variable length arrays - set (SEQAN_CXX_FLAGS "${SEQAN_CXX_FLAGS} -Wno-vla") - - # parallelize parts of build even for one translation unit - if (NOT DEFINED LAMBDA_COMPILE_THREADS) - include(ProcessorCount) - ProcessorCount(LAMBDA_COMPILE_THREADS) - endif () - - # TODO: this should be fixed; currently triggers an ICE for some reason - # if (LAMBDA_COMPILE_THREADS GREATER 1) - # set (CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -flto=${LAMBDA_COMPILE_THREADS}") - # endif() - - # strip binaries to make them smaller - set (CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_RELEASE} -s") -endif () - -# ---------------------------------------------------------------------------- -# Build Setup -# ---------------------------------------------------------------------------- - -# Add include directories. -include_directories (${SEQAN_INCLUDE_DIRS}) - -# Add definitions set by find_package (SeqAn). -add_definitions (${SEQAN_DEFINITIONS}) - -# Add definitions set by the build system. -add_definitions (-DSEQAN_APP_VERSION="${SEQAN_APP_VERSION}") -add_definitions (-DCMAKE_BUILD_TYPE="${CMAKE_BUILD_TYPE}") - -# Set the right output directory -set (CMAKE_RUNTIME_OUTPUT_DIRECTORY ${PROJECT_BINARY_DIR}/bin) - -# Add CXX flags found by find_package (SeqAn). -set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${SEQAN_CXX_FLAGS} -Wall -pedantic") - -# Update the list of file names below if you add source files to your application. -set (LAMBDA_SOURCE_FILES lambda.cpp search.cpp mkindex.cpp) - -add_executable (lambda3 ${LAMBDA_SOURCE_FILES}) -target_link_libraries (lambda3 ${SEQAN_LIBRARIES} fmindex-collection sharg::sharg biocpp::core biocpp::io cereal::cereal) -set_target_properties (lambda3 PROPERTIES COMPILE_FLAGS "-mmmx -msse -msse2 -msse3 -mssse3 -msse4 -mpopcnt") - -# ---------------------------------------------------------------------------- -# Man-pages -# ---------------------------------------------------------------------------- - -# Umbrella man-page -add_custom_command (OUTPUT lambda3.1 - COMMAND lambda3 --export-help man > lambda3.1 - DEPENDS lambda3) -# searchn subcommand -add_custom_command (OUTPUT lambda3-searchn.1 - COMMAND lambda3 searchn --export-help man > lambda3-searchn.1 - DEPENDS lambda3) -# searchp subcommand -add_custom_command (OUTPUT lambda3-searchp.1 - COMMAND lambda3 searchp --export-help man > lambda3-searchp.1 - DEPENDS lambda3) - -# searchbs subcommand -add_custom_command (OUTPUT lambda3-searchbs.1 - COMMAND lambda3 searchbs --export-help man > lambda3-searchbs.1 - DEPENDS lambda3) - -# mkindexn subcommand -add_custom_command (OUTPUT lambda3-mkindexn.1 - COMMAND lambda3 mkindexn --export-help man > lambda3-mkindexn.1 - DEPENDS lambda3) -# mkindexp subcommand -add_custom_command (OUTPUT lambda3-mkindexp.1 - COMMAND lambda3 mkindexp --export-help man > lambda3-mkindexp.1 - DEPENDS lambda3) - -# mkindexbs subcommand -add_custom_command (OUTPUT lambda3-mkindexbs.1 - COMMAND lambda3 mkindexbs --export-help man > lambda3-mkindexbs.1 - DEPENDS lambda3) - -add_custom_target (manual ALL DEPENDS lambda3.1 - lambda3-searchn.1 lambda3-searchp.1 lambda3-searchbs.1 - lambda3-mkindexn.1 lambda3-mkindexp.1 lambda3-mkindexbs.1) - -# ---------------------------------------------------------------------------- -# Installation -# ---------------------------------------------------------------------------- - -# Adapt to system paths -include (GNUInstallDirs) - -# Install lambda binaries into LIBEXECDIR -install (TARGETS lambda3 - DESTINATION ${CMAKE_INSTALL_BINDIR}) - -# Install non-binary files for the package to DOCDIR, usually ${PREFIX}/share/doc/lambda3 -install (FILES ../LICENSE.rst - ../LICENSE-BSD.rst - ../LICENSE-AGPL3.rst - ../README.rst - DESTINATION ${CMAKE_INSTALL_DOCDIR}) - -# Man pages into MANDIR, usually ${PREFIX}/share/man/man1 (or without share) -install (FILES ${CMAKE_CURRENT_BINARY_DIR}/lambda3.1 - ${CMAKE_CURRENT_BINARY_DIR}/lambda3-searchn.1 - ${CMAKE_CURRENT_BINARY_DIR}/lambda3-searchp.1 - ${CMAKE_CURRENT_BINARY_DIR}/lambda3-searchbs.1 - ${CMAKE_CURRENT_BINARY_DIR}/lambda3-mkindexn.1 - ${CMAKE_CURRENT_BINARY_DIR}/lambda3-mkindexp.1 - ${CMAKE_CURRENT_BINARY_DIR}/lambda3-mkindexbs.1 - DESTINATION ${CMAKE_INSTALL_MANDIR}/man1) - -# ---------------------------------------------------------------------------- -# CPack Install -# ---------------------------------------------------------------------------- - -# Information -set (CPACK_PACKAGE_NAME "lambda3") -set (CPACK_PACKAGE_DESCRIPTION_SUMMARY "lambda -- the local aligner for massive bioligical data") -set (CPACK_PACKAGE_DESCRIPTION_FILE "${CMAKE_CURRENT_SOURCE_DIR}/../README.rst") -set (CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/../LICENSE.rst") -set (CPACK_PACKAGE_VENDOR "Hannes Hauswedell ") -set (CPACK_PACKAGE_CONTACT "${CPACK_PACKAGE_VENDOR}") -set (CPACK_PACKAGE_VERSION_MAJOR "${SEQAN_APP_VERSION_MAJOR}") -set (CPACK_PACKAGE_VERSION_MINOR "${SEQAN_APP_VERSION_MINOR}") -set (CPACK_PACKAGE_VERSION_PATCH "${SEQAN_APP_VERSION_PATCH}") -set (CPACK_PACKAGE_VERSION "${SEQAN_APP_VERSION}") -set (CPACK_PACKAGE_INSTALL_DIRECTORY "${CPACK_PACKAGE_NAME} ${CPACK_PACKAGE_VERSION}") - -# Package format(s) -if (CMAKE_SYSTEM_NAME MATCHES "Windows") - set(CPACK_GENERATOR "ZIP;NSIS") -elseif (CMAKE_SYSTEM_NAME MATCHES "Darwin") - set(CPACK_GENERATOR "ZIP;DragNDrop") -elseif (CMAKE_VERSION VERSION_LESS "3.1") # TXZ support since 3.1 - set(CPACK_GENERATOR "TBZ2") -else() - set(CPACK_GENERATOR "TXZ") -endif () - -if (CMAKE_SYSTEM_NAME MATCHES "Linux") - set(CPACK_GENERATOR "${CPACK_GENERATOR};DEB;RPM") -endif () - -# Package architecture -if (CMAKE_SYSTEM_PROCESSOR STREQUAL "amd64") - set(CMAKE_SYSTEM_PROCESSOR "x86_64") - set(CPACK_DEBIAN_PACKAGE_ARCHITECTURE "amd64") -endif () - -# Include architecture in package name -if (NOT DEFINED CPACK_SYSTEM_NAME) - set(CPACK_SYSTEM_NAME "${CMAKE_SYSTEM_NAME}-${CMAKE_SYSTEM_PROCESSOR}") -endif (NOT DEFINED CPACK_SYSTEM_NAME) - -include (CPack) diff --git a/src/bisulfite_scoring.hpp b/src/bisulfite_scoring.hpp deleted file mode 100644 index 743506291..000000000 --- a/src/bisulfite_scoring.hpp +++ /dev/null @@ -1,95 +0,0 @@ -// ========================================================================== -// lambda -// ========================================================================== -// Copyright (c) 2019-2024, Sara Hetzel -// Copyright (c) 2016-2019, Knut Reinert and Freie Universität Berlin -// All rights reserved. -// -// This file is part of Lambda. -// -// Lambda is Free Software: you can redistribute it and/or modify it -// under the terms found in the LICENSE[.md|.rst] file distributed -// together with this file. -// -// Lambda 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. -// -// ========================================================================== -// Scoring schemes for bisulfite converted data on dna5 alphabet -// ========================================================================== - -#pragma once - -#include -#include - -#include -#include - -enum class bsDirection -{ - fwd, - rev -}; - -namespace seqan -{ - -struct BisulfiteMatrix -{}; - -template <> -struct ScoringMatrixData_ -{ - enum - { - VALUE_SIZE = ValueSize::VALUE, - TAB_SIZE = VALUE_SIZE * VALUE_SIZE - }; - - static inline int const * getData() - { - // clang-format off - static int const _data[TAB_SIZE] = - { - 0, -1, -1, -1, -1, - -1, 0, -1, -1, -1, - -1, -1, 0, -1, -1, - -1, 0, -1, 0, -1, - -1, -1, -1, -1, -1 - }; - // clang-format on - return _data; - } -}; - -template -inline void setScoreBisulfiteMatrix(Score> & sc, - T matchScore, - T mismatchScore, - bsDirection const dir = bsDirection::fwd) -{ - for (size_t i = 0; i < ValueSize::VALUE; ++i) - { - for (size_t j = 0; j < ValueSize::VALUE; ++j) - { - if (dir == bsDirection::fwd) - { - if (((i == j) || (i == 3 && j == 1)) && i != 4) - setScore(sc, i, j, matchScore); - else - setScore(sc, i, j, mismatchScore); - } - else - { - if (((i == j) || (i == 0 && j == 2)) && i != 4) - setScore(sc, i, j, matchScore); - else - setScore(sc, i, j, mismatchScore); - } - } - } -} - -} // namespace seqan diff --git a/src/evaluate_bisulfite_alignment.hpp b/src/evaluate_bisulfite_alignment.hpp deleted file mode 100644 index b9a272545..000000000 --- a/src/evaluate_bisulfite_alignment.hpp +++ /dev/null @@ -1,119 +0,0 @@ -// ========================================================================== -// lambda -// ========================================================================== -// Copyright (c) 2019-2024, Sara Hetzel and MPI für Molekulare Genetik -// All rights reserved. -// -// This file is part of Lambda. -// -// Lambda is Free Software: you can redistribute it and/or modify it -// under the terms found in the LICENSE[.md|.rst] file distributed -// together with this file. -// -// Lambda 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. -// -// ========================================================================== -// Scoring schemes for bisulfite converted data on dna5 alphabet -// ========================================================================== - -#pragma once - -namespace seqan -{ - -template -TScoreVal computeAlignmentStats(AlignmentStats & stats, - Gaps const & row0, - Gaps const & row1, - Score> const & scoringScheme) -{ - clear(stats); - - typedef typename Iterator const, Standard>::Type TGapsIter0; - typedef typename Iterator const, Standard>::Type TGapsIter1; - typedef typename Value::Type TAlphabet; - - // Get iterators. - TGapsIter0 it0 = begin(row0); - TGapsIter0 itEnd0 = end(row0); - TGapsIter1 it1 = begin(row1); - TGapsIter1 itEnd1 = end(row1); - - // State whether we have already opened a gap. - bool isGapOpen0 = false, isGapOpen1 = false; - - for (; it0 != itEnd0 && it1 != itEnd1; ++it0, ++it1) - { - if (isGap(it0)) - { - if (!isGapOpen0) - { - stats.numGapOpens += 1; - stats.alignmentScore += scoreGapOpen(scoringScheme); - } - else - { - stats.numGapExtensions += 1; - stats.alignmentScore += scoreGapExtend(scoringScheme); - } - stats.numDeletions += 1; - isGapOpen0 = true; - } - else - { - isGapOpen0 = false; - } - - if (isGap(it1)) - { - if (!isGapOpen1) - { - stats.numGapOpens += 1; - stats.alignmentScore += scoreGapOpen(scoringScheme); - } - else - { - stats.numGapExtensions += 1; - stats.alignmentScore += scoreGapExtend(scoringScheme); - } - stats.numInsertions += 1; - isGapOpen1 = true; - } - else - { - isGapOpen1 = false; - } - - if (!isGap(it0) && !isGap(it1)) - { - // Compute the alignment score and register in stats. - TAlphabet c0 = convert(*it0); - TAlphabet c1 = convert(*it1); - TScoreVal scoreVal = score(scoringScheme, c0, c1); - stats.alignmentScore += scoreVal; - // Register other statistics. - bool isMatch = score(scoringScheme, c0, c1) == score(scoringScheme, c0, c0); - bool isPositive = (scoreVal > 0); - stats.numMatches += isMatch; - stats.numMismatches += !isMatch; - stats.numPositiveScores += isPositive; - stats.numNegativeScores += !isPositive; - } - } - SEQAN_ASSERT(it0 == itEnd0); - SEQAN_ASSERT(it1 == itEnd1); - - stats.numGaps = stats.numGapOpens + stats.numGapExtensions; - - // Finally, compute the alignment similarity from the various counts - stats.alignmentLength = length(row0); - stats.alignmentSimilarity = - 100.0 * static_cast(stats.numPositiveScores) / static_cast(stats.alignmentLength); - stats.alignmentIdentity = 100.0 * static_cast(stats.numMatches) / static_cast(stats.alignmentLength); - - return stats.alignmentScore; -} - -} // namespace seqan diff --git a/src/holder_tristate_overload.h b/src/holder_tristate_overload.h deleted file mode 100644 index 6cfea02b5..000000000 --- a/src/holder_tristate_overload.h +++ /dev/null @@ -1,224 +0,0 @@ -// ========================================================================== -// SeqAn - The Library for Sequence Analysis -// ========================================================================== -// Copyright (c) 2006-2018, Knut Reinert, FU Berlin -// All rights reserved. -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are met: -// -// * Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// * Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// * Neither the name of Knut Reinert or the FU Berlin nor the names of -// its contributors may be used to endorse or promote products derived -// from this software without specific prior written permission. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -// ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE -// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL -// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR -// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER -// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT -// LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY -// OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -// DAMAGE. -// -// ========================================================================== -// Author: Andreas Gogol-Döring -// ========================================================================== -// Tristate Holder Implementation. -// ========================================================================== - -#pragma once - -#include -#include -#include - -template -concept overload_c = !std::default_initializable>; - -namespace seqan -{ - -// ============================================================================ -// Tags, Classes, Enums -// ============================================================================ -template -struct Holder -{ - enum EHolderState - { - EMPTY = 0, - OWNER = 1, - DEPENDENT = 2 - }; - - typedef std::optional THostValue; - - // ------------------------------------------------------------------------ - // Members - // ------------------------------------------------------------------------ - - THostValue data_value; - EHolderState data_state; - - // ------------------------------------------------------------------------ - // Constructors; Destructor - // ------------------------------------------------------------------------ - - Holder() : data_value{}, data_state(EMPTY) - { - } - - Holder(Holder const & source_) : data_value{}, data_state(EMPTY) - { - data_value = source_; - } - - explicit - Holder(THostValue & value_) : data_value{}, data_state(EMPTY) - { - data_value = value_; - } - - explicit - Holder(THostValue const & value_) : data_value{}, data_state(EMPTY) - { - data_value = value_; - } - - ~Holder() - { - clear(*this); - } - - // ------------------------------------------------------------------------ - // Assignment Operators; Must be defined in class. - // ------------------------------------------------------------------------ - - Holder & operator=(Holder const &) = default; - - Holder & operator=(THostValue const & value_) - { - data_value = value_; - return *this; - } - - // ------------------------------------------------------------------------ - // Conversion Operators; Must be defined in class. - // ------------------------------------------------------------------------ - - inline operator THostValue() - { - return data_value; - } -}; - -// ============================================================================ -// Functions -// ============================================================================ - -/// ---------------------------------------------------------------------------- -// Function clear() -// ---------------------------------------------------------------------------- - -template -inline void -clear(Holder & me) -{ - me.data_value.reset(); - me.data_state = Holder::EMPTY; -} - -// ---------------------------------------------------------------------------- -// Function setValue() -// ---------------------------------------------------------------------------- - -template -inline void -setValue(Holder & me, - TValue const & value_) -{ - me.data_value = value_; - me.data_state = Holder::OWNER; -} - -template -inline void -setValue(Holder & me, - TValue const & value_) -{ - me.data_value = value_; - me.data_state = Holder::OWNER; -} - -// ---------------------------------------------------------------------------- -// Function value() -// ---------------------------------------------------------------------------- - -template -auto & value(Holder & me) -{ - SEQAN_ASSERT_NOT(empty(me)); // HERE BE DRAGONS!!! - return * me.data_value; -} - -template -auto & value(Holder const & me) -{ - SEQAN_ASSERT_NOT(empty(me)); - - return * me.data_value; -} - -// ---------------------------------------------------------------------------- -// Function assignValue() -// ---------------------------------------------------------------------------- - -template -inline void -assignValue(Holder & me, - TSource const & value_) -{ - setValue(me, value_); -} - -// ---------------------------------------------------------------------------- -// Function moveValue() -// ---------------------------------------------------------------------------- - -template -inline void -moveValue(Holder & me, - TSource const & value_) -{ - setValue(me, value_); -} - -// ---------------------------------------------------------------------------- -// Function assign() -// ---------------------------------------------------------------------------- - -template -inline void -assign(Holder & target_, - Holder const & source_) -{ - target_ = source_; -} - -template -inline void -assign(Holder & target_, - Holder const & source_) -{ - target_ = source_; -} - -} // namespace seqan diff --git a/src/lambda.cpp b/src/lambda.cpp deleted file mode 100644 index 77be0b4c3..000000000 --- a/src/lambda.cpp +++ /dev/null @@ -1,118 +0,0 @@ -// ========================================================================== -// lambda -// ========================================================================== -// Copyright (c) 2013-2024, Hannes Hauswedell

-// Copyright (c) 2016-2020, Knut Reinert and Freie Universität Berlin -// All rights reserved. -// -// This file is part of Lambda. -// -// Lambda is Free Software: you can redistribute it and/or modify it -// under the terms found in the LICENSE[.md|.rst] file distributed -// together with this file. -// -// Lambda 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. -// -// ========================================================================== -// lambda.cpp: Main File for Lambda -// ========================================================================== - -#include - -#include "mkindex.hpp" -#include "search.hpp" -#include "shared_options.hpp" - -void parseCommandLineMain(int argc, char const ** argv); - -int main(int argc, char const ** argv) -{ - if (std::string(CMAKE_BUILD_TYPE) != "Release") - std::cerr << "WARNING: This binary is not built in release mode and will be much slower than it should be!\n"; - - int until = argc; - bool skipNext = false; - for (int i = 1; i < argc; ++i) - { - // version check expects a parameter - if (std::string(argv[i]) == "--version-check") - skipNext = true; - - if (argv[i][0] != '-') - { - if (skipNext) - { - skipNext = false; - } - else - { - until = i + 1; - break; - } - } - } - - try - { - parseCommandLineMain(until, argv); - } - catch (std::exception const & ext) - { - std::cerr << ext.what() << "\n"; - return -1; - } - - --until; // undo the "+ 1" above - - std::string const subcommand_actual = argv[until]; - - if (subcommand_actual.starts_with("search")) - { - return searchMain(argc - until, argv + until); - } - else if (subcommand_actual.starts_with("mkindex")) - { - return mkindexMain(argc - until, argv + until); - } - else - { - // shouldn't be reached - std::cerr << "WRONG ARGUMENTS!\n"; - return -1; - } - return 0; -} - -void parseCommandLineMain(int argc, char const ** argv) -{ - sharg::parser parser("lambda3", argc, argv, sharg::update_notifications::off); - - parser.info.short_description = "Lambda, the Local Aligner for Massive Biological DatA."; - parser.info.synopsis.push_back("lambda3 [\\fIOPTIONS\\fP] COMMAND [\\fICOMMAND-OPTIONS\\fP]"); - - sharedSetup(parser); - - std::string command{}; - parser.add_positional_option( - command, - sharg::config{ - .description = "The sub-program to execute. See above.", - .validator = - sharg::value_list_validator{"searchp", "searchn", "searchbs", "mkindexp", "mkindexn", "mkindexbs"} - }); - - parser.info.description.push_back("Available commands"); - parser.info.description.push_back( - "\\fBsearchp \\fP– Perform a protein search (BLASTP, BLASTX, TBLASTN, TBLASTX)."); - parser.info.description.push_back("\\fBsearchn \\fP– Perform a nucleotide search (BLASTN, MEGABLAST)."); - parser.info.description.push_back("\\fBsearchbs \\fP– Perform a bisulfite search."); - parser.info.description.push_back("\\fBmkindexp \\fP– Create an index for protein searches."); - parser.info.description.push_back("\\fBmkindexn \\fP– Create an index for nucleotide searches."); - parser.info.description.push_back("\\fBmkindexbs\\fP– Create an index for bisulfite searches."); - parser.info.description.push_back( - "To view the help page for a specific command, simply run 'lambda command --help'."); - - parser.parse(); -} diff --git a/src/mkindex.cpp b/src/mkindex.cpp deleted file mode 100644 index 345ecbda3..000000000 --- a/src/mkindex.cpp +++ /dev/null @@ -1,262 +0,0 @@ -// ========================================================================== -// lambda -// ========================================================================== -// Copyright (c) 2013-2024, Hannes Hauswedell

-// Copyright (c) 2016-2020, Knut Reinert and Freie Universität Berlin -// All rights reserved. -// -// This file is part of Lambda. -// -// Lambda is Free Software: you can redistribute it and/or modify it -// under the terms found in the LICENSE[.md|.rst] file distributed -// together with this file. -// -// Lambda 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. -// -// ========================================================================== -// mkindex.cpp: Main File for building the index -// ========================================================================== - -#include -#include - -#include -#include -#include - -#include - -#include "shared_definitions.hpp" -#include "shared_misc.hpp" -#include "shared_options.hpp" - -#include "mkindex_misc.hpp" -#include "mkindex_options.hpp" -// #include "mkindex_saca.hpp" -#include "mkindex_algo.hpp" -#include "view_reduce_to_bisulfite.hpp" - -// ========================================================================== -// Forwards -// ========================================================================== - -void argConv0(LambdaIndexerOptions & options); - -template -void argConv1(LambdaIndexerOptions & options); - -template -void argConv2(LambdaIndexerOptions const & options); - -template -void argConv3a(LambdaIndexerOptions const & options); - -template -void argConv3b(LambdaIndexerOptions const & options); - -template -void realMain(LambdaIndexerOptions const & options); - -// -------------------------------------------------------------------------- -// Function main() -// -------------------------------------------------------------------------- - -// Program entry point. - -int mkindexMain(int const argc, char const ** argv) -{ - LambdaIndexerOptions options; - -#ifdef NDEBUG - try - { - parseCommandLine(options, argc, argv); - } - catch (sharg::parser_error const & ext) // catch user errors - { - std::cerr << "\n\nERROR: during command line parsing\n" - << " \"" << ext.what() << "\"\n"; - return -1; - } -#else - parseCommandLine(options, argc, argv); -#endif - -#ifdef NDEBUG - try - { - argConv0(options); - } - catch (std::bad_alloc const & e) - { - std::cerr << "ERROR: Lambda ran out of memory :(\n" - " You need to split your file into smaller segments.\n"; - return -1; - } - catch (std::exception const & e) - { - std::cerr << "\n\nERROR: The following unspecified exception was thrown:\n" - << " \"" << e.what() << "\"\n" - << " If the problem persists, report an issue at https://github.com/seqan/lambda/issues " - << "and include this output, as well as the output of `lambda3 --version`, thanks!\n"; - return -1; - } -#else - // In debug mode we don't catch the exceptions so that we get a backtrace from SeqAn's handler - argConv0(options); -#endif - return 0; -} - -void argConv0(LambdaIndexerOptions & options) -{ - switch (options.indexFileOptions.indexType) - { - case DbIndexType::FM_INDEX: - return argConv1(options); - case DbIndexType::BI_FM_INDEX: -#if LAMBDA_WITH_BIFM - return argConv1(options); -#else - throw std::runtime_error{ - "To create bidirectional indexes, you need to rebuild lambda with LAMBDA_WITH_BIFM=1 ."}; -#endif - default: - throw 42; - } -} - -template -void argConv1(LambdaIndexerOptions & options) -{ - if (options.indexFileOptions.origAlph == AlphabetEnum::UNDEFINED) - { - myPrint(options, 1, "Detecting database alphabet... "); - options.indexFileOptions.origAlph = detectSeqFileAlphabet(options.dbFile); - myPrint(options, 1, _alphabetEnumToName(options.indexFileOptions.origAlph), " detected.\n"); - myPrint(options, 2, "\n"); - } - - switch (options.indexFileOptions.origAlph) - { - case AlphabetEnum::DNA5: - return argConv2(options); - case AlphabetEnum::AMINO_ACID: - return argConv3a(options); - default: - throw 43; - } -} - -template -void argConv2(LambdaIndexerOptions const & options) -{ - switch (options.indexFileOptions.transAlph) - { - case AlphabetEnum::DNA5: - return argConv3b(options); - case AlphabetEnum::AMINO_ACID: - return argConv3a(options); - default: - throw 44; - } -} - -template -void argConv3a(LambdaIndexerOptions const & options) -{ - switch (options.indexFileOptions.redAlph) - { - case AlphabetEnum::AMINO_ACID: - return realMain(options); - case AlphabetEnum::MURPHY10: - return realMain(options); - case AlphabetEnum::LI10: - return realMain(options); - default: - throw 45; - } -} - -template -void argConv3b(LambdaIndexerOptions const & options) -{ - switch (options.indexFileOptions.redAlph) - { - case AlphabetEnum::DNA5: - return realMain(options); - case AlphabetEnum::DNA4: - return realMain(options); - case AlphabetEnum::DNA3BS: - return realMain(options); - default: - throw 364; - } -} - -template -void realMain(LambdaIndexerOptions const & options) -{ - index_file f; - f.options = options.indexFileOptions; - - { - TaccToIdRank accToIdRank; - - // ids get saved to disk again immediately and are not kept in memory - std::tie(f.ids, f.seqs, accToIdRank) = loadSubjSeqsAndIds<_alphabetEnumToType>(options); - - if (options.hasSTaxIds) - { - std::vector taxIdIsPresent; - - // read taxonomic IDs - std::tie(f.sTaxIds, taxIdIsPresent) = mapTaxIDs(accToIdRank, std::ranges::size(f.seqs), options); - - if (!options.taxDumpDir.empty()) - { - // read and create taxonomic tree - std::tie(f.taxonParentIDs, f.taxonHeights, f.taxonNames) = - parseAndStoreTaxTree(taxIdIsPresent, options); - } - } - } - - // see if final sequence set actually fits into index - // checkIndexSize(translatedSeqs, options, seqan::BlastProgramSelector

()); - - auto transSbjSeqs = f.seqs | sbjTransView; - auto redSbjSeqs = transSbjSeqs | redView; - - f.index = generateIndex(redSbjSeqs, options); - - myPrint(options, 1, "Writing Index to disk..."); - double s = sysTime(); - { - std::string filename(options.indexFilePath); - bio::io::transparent_ostream os{ - filename, - {.compression_level = 5, .threads = options.threads} - }; - - if (filename.ends_with(".lba") || filename.ends_with(".lba.gz")) - { - cereal::BinaryOutputArchive oarchive(os); - oarchive(cereal::make_nvp("lambda index", f)); - } - else if (filename.ends_with(".lta") || filename.ends_with(".lta.gz")) - { - cereal::JSONOutputArchive oarchive(os); - oarchive(cereal::make_nvp("lambda index", f)); - } - else - { - throw 59; - } - } - double e = sysTime() - s; - myPrint(options, 1, " done.\n"); - myPrint(options, 2, "Runtime: ", e, "s \n"); -} diff --git a/src/mkindex.hpp b/src/mkindex.hpp deleted file mode 100644 index 9005fce66..000000000 --- a/src/mkindex.hpp +++ /dev/null @@ -1,24 +0,0 @@ -// ========================================================================== -// lambda -// ========================================================================== -// Copyright (c) 2013-2024, Hannes Hauswedell

-// Copyright (c) 2016-2020, Knut Reinert and Freie Universität Berlin -// All rights reserved. -// -// This file is part of Lambda. -// -// Lambda is Free Software: you can redistribute it and/or modify it -// under the terms found in the LICENSE[.md|.rst] file distributed -// together with this file. -// -// Lambda 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. -// -// ========================================================================== -// lambda.hpp: Main File for the main application -// ========================================================================== - -#pragma once - -int mkindexMain(int const argc, char const ** argv); diff --git a/src/mkindex_algo.hpp b/src/mkindex_algo.hpp deleted file mode 100644 index 8bc7ca00c..000000000 --- a/src/mkindex_algo.hpp +++ /dev/null @@ -1,618 +0,0 @@ -// ========================================================================== -// lambda -// ========================================================================== -// Copyright (c) 2013-2024, Hannes Hauswedell

-// Copyright (c) 2016-2020, Knut Reinert and Freie Universität Berlin -// All rights reserved. -// -// This file is part of Lambda. -// -// Lambda is Free Software: you can redistribute it and/or modify it -// under the terms found in the LICENSE[.md|.rst] file distributed -// together with this file. -// -// Lambda 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. -// -// ========================================================================== -// mkindex_algo.hpp: Functions for the indexer application -// ========================================================================== - -#pragma once - -#include -#include - -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -#include "mkindex_misc.hpp" -#include "shared_definitions.hpp" -#include "shared_misc.hpp" -#include "shared_options.hpp" - -// -------------------------------------------------------------------------- -// Function loadSubj() -// -------------------------------------------------------------------------- - -template -auto loadSubjSeqsAndIds(LambdaIndexerOptions const & options) -{ - using TIDs = TCDStringSet; - using TOrigSeqs = TCDStringSet>; - - std::tuple ret; - - auto & ids = std::get<0>(ret); - auto & originalSeqs = std::get<1>(ret); - auto & accToIdRank = std::get<2>(ret); - - // Make sure we have enough RAM to load the file - auto ram = getTotalSystemMemory(); - auto fS = fileSize(options.dbFile.c_str()); - - if (fS >= ram) - std::cerr << "WARNING: Your sequence file is already larger than your physical memory!\n" - << " This means you will likely encounter a crash with \"bad_alloc\".\n" - << " Split you sequence file into many smaller ones or use a computer\n" - << " with more memory!\n"; - - // see http://www.uniprot.org/help/accession_numbers - // https://www.ncbi.nlm.nih.gov/Sequin/acc.html - // https://www.ncbi.nlm.nih.gov/refseq/about/ - // REMARK: these might trigger twice on one ID - std::regex const accRegEx{ - "[OPQ][0-9][A-Z0-9]{3}[0-9]|[A-NR-Z][0-9]([A-Z][A-Z0-9]{2}[0-9]){1,2}|" // UNIPROT - "[A-Z][0-9]{5}|[A-Z]{2}[0-9]{6}|" // NCBI nucl - "[A-Z]{3}[0-9]{5}|" // NCBI prot - "[A-Z]{4}[0-9]{8,10}|" // NCBI wgs - "[A-Z]{5}[0-9]{7}|" // NCBI mga - "(NC|AC|NG|NT|NW|NZ|NM|NR|XM|XR|NP|AP|XP|YP|ZP)_[0-9]+|" // RefSeq - "UPI[A-F0-9]{10}"}; // UniParc - - uint64_t noAcc = 0; - uint64_t multiAcc = 0; - - // lambda that extracts accession numbers and saves them in the map - auto extractAccIds = [&accToIdRank, &accRegEx, &noAcc, &multiAcc](std::string_view const id, uint64_t const rank) - { - uint64_t count = 0; - for (auto it = std::cregex_iterator(id.begin(), id.end(), accRegEx), itEnd = std::cregex_iterator(); - it != itEnd; - ++it, ++count) - { - assert(accToIdRank.count(it->str()) == 0); - // "An accession number appeared twice in the file, but they should be unique."); - - accToIdRank[it->str()] = rank; - } - - switch (count) - { - case 0: - ++noAcc; - break; - case 1: - break; - default: - ++multiAcc; - break; - } - }; - - double start = sysTime(); - myPrint(options, 1, "Loading Subject Sequences and Ids..."); - - using seq_t = std::conditional_t | - bio::views::char_to), - bio::ranges::views::char_conversion_view_t>; - - using rec_t = decltype(bio::io::seq::record{.id = std::string_view{}, .seq = seq_t{}, .qual = std::ignore}); - bio::io::seq::reader reader{ - options.dbFile, - bio::io::seq::reader_options{.record = rec_t{}, .truncate_ids = options.truncateIDs} - }; - - size_t count = 0; - for (auto & [id, seq, qual] : reader) - { - if (options.hasSTaxIds) - extractAccIds(id, count); - - ids.push_back(id); - - originalSeqs.push_back(seq); - ++count; - } - - myPrint(options, 1, " done.\n"); - double finish = sysTime() - start; - myPrint(options, 2, "Runtime: ", finish, "s \n"); - - if (std::ranges::empty(originalSeqs)) - { - throw std::runtime_error("ERROR: No sequences in file. Aborting.\n"); - } - - size_t maxLen = 0ul; - size_t lengthSum = 0ul; - for (auto const & s : originalSeqs) - { - lengthSum += s.size(); - if (s.size() > maxLen) - { - maxLen = s.size(); - } - else if (s.size() == 0ul) - { - throw std::runtime_error( - "ERROR: Unexpectedly encountered a sequence of length 0 in the file." - "Remove the entry and try again. Aborting.\n"); - } - } - myPrint(options, - 2, - "Number of sequences read: ", - std::ranges::size(originalSeqs), - "\nLongest sequence read: ", - maxLen, - "\nSum of all sequence lengths: ", - lengthSum, - "\n"); - - if (options.hasSTaxIds) - { - myPrint(options, - 2, - "Subjects without acc numbers: ", - noAcc, - '/', - std::ranges::size(ids), - "\n", - "Subjects with more than one acc number: ", - multiAcc, - '/', - std::ranges::size(ids), - "\n"); - } - - myPrint(options, 2, "\n"); - - return ret; -} - -// -------------------------------------------------------------------------- -// Function checkIndexSize() -// -------------------------------------------------------------------------- - -template -void checkIndexSize(TCDStringSet> const & seqs, LambdaIndexerOptions const & options) -{ -#if 0 // TODO: new index should handle arbitrary sizes, but we want the RAM check again - myPrint(options, 1, "Checking parameters of to-be-built index..."); - - // check number of sequences - using SAV = typename SAValue>>::Type; - uint64_t curNumSeq = std::ranges::size(seqs); - uint64_t maxNumSeq = std::numeric_limits::Type>::max(); - - if (curNumSeq >= maxNumSeq) - { - throw std::invalid_argument(std::string("ERROR: Too many sequences to be indexed:\n ") + - std::to_string(std::ranges::size(seqs)) + - std::string(" in file, but only ") + - std::to_string(maxNumSeq) + - std::string(" supported by index.\n")); - } - - // check length of sequences - uint64_t maxLenSeq = std::numeric_limits::Type>::max(); - uint64_t maxLen = 0ul; - for (auto const & s : seqs) - if (std::ranges::size(s) > maxLen) - maxLen = std::ranges::size(s); - - if (maxLen >= maxLenSeq) - { - std::string err; - err += "Sequences too long to be indexed:\n "; - err += "length"; - err += std::to_string(maxLen); - err += " present in file, but only "; - err += std::to_string(maxLenSeq); - err += " supported by index.\n"; -# ifndef LAMBDA_LONG_PROTEIN_SUBJ_SEQS - if (p != BlastProgram::BLASTN) - err += "You can recompile Lambda and add -DLAMBDA_LONG_PROTEIN_SUBJ_SEQS=1 to activate\n" - "support for longer protein sequences.\n"; -# endif - - throw std::invalid_argument(err); - } - - // check available RAM - auto ram = getTotalSystemMemory(); - auto lS = lengthSum(seqs); - unsigned long long factor = 0; - if (options.algo == "radixsort") - factor = sizeof(SizeTypeNum_) + sizeof(SizeTypePos_) + 4; // 4 is good heuristic - else if (options.algo == "skew7ext") - factor = 6; // TODO do some tests! - auto estimatedSize = lS * factor; - - myPrint(options, 1, "done.\n"); - if (estimatedSize >= ram) - { - std::cerr << "WARNING: Lambda estimates that it will need " << estimatedSize / 1024 / 1024 << "MB\n" - << " of memory to index this file, but you have only " << ram / 1024 / 1024 << "MB\n" - << " available on your system.\n" - << " This means you will likely encounter a crash with \"bad_alloc\".\n" - << " Split you sequence file into many smaller ones or use a computer\n" - << " with more memory!\n"; - } else - { - myPrint(options, 2, "Detected RAM: ", ram / 1024 / 1024, "MB, Estimated RAM usage: ", - estimatedSize / 1024 / 1024, "MB\n\n"); - } -#else - (void)seqs; - (void)options; -#endif -} - -// -------------------------------------------------------------------------- -// Function mapAndDumpTaxIDs() -// -------------------------------------------------------------------------- - -auto mapTaxIDs(TaccToIdRank const & accToIdRank, uint64_t const numSubjects, LambdaIndexerOptions const & options) -{ - using TTaxIds = std::vector>; // not concat because we resize inbetween - using TTaxIdsPresent = std::vector; - - std::tuple ret; - - auto & sTaxIds = std::get<0>(ret); - auto & taxIdIsPresent = std::get<1>(ret); - - taxIdIsPresent.reserve(2'000'000); - sTaxIds.resize(numSubjects); - - myPrint(options, 1, "Parsing acc-to-tax-map file... "); - - double start = sysTime(); - - if (std::regex_match(options.accToTaxMapFile, std::regex{R"raw(.*\.accession2taxid(\.(gz|bgzf|bz2))?)raw"})) - { - _readMappingFileNCBI(options.accToTaxMapFile, accToIdRank, sTaxIds, taxIdIsPresent); - } - else if (std::regex_match(options.accToTaxMapFile, std::regex{R"raw(.*\.dat(\.(gz|bgzf|bz2))?)raw"})) - { - _readMappingFileUniProt(options.accToTaxMapFile, accToIdRank, sTaxIds, taxIdIsPresent); - } - else - { - throw std::invalid_argument("ERROR: extension of acc-to-tax-map file not handled.\n"); - } - - // root node is always present - if (taxIdIsPresent.size() < 2) - taxIdIsPresent.resize(2); - taxIdIsPresent[1] = true; - - myPrint(options, 1, "done.\n"); - - myPrint(options, 2, "Runtime: ", sysTime() - start, "s \n"); - - uint64_t nomap = 0; - uint64_t multi = 0; - - for (auto && s : sTaxIds) - { - if (std::ranges::size(s) == 0) - ++nomap; - else if (std::ranges::size(s) > 1) - ++multi; - } - - myPrint(options, - 2, - "Subjects without tax IDs: ", - nomap, - '/', - numSubjects, - "\n", - "Subjects with more than one tax ID: ", - multi, - '/', - numSubjects, - "\n\n"); - if ((nomap > 0) && ((numSubjects / nomap) < 5)) - myPrint(options, - 1, - "WARNING: ", - double(nomap) * 100 / numSubjects, - "% of subjects have no taxID.\n" - " Maybe you specified the wrong map file?\n\n"); - - return ret; -} - -// -------------------------------------------------------------------------- -// Function mapAndDumpTaxIDs() -// -------------------------------------------------------------------------- - -auto parseAndStoreTaxTree(std::vector & taxIdIsPresent, LambdaIndexerOptions const & options) -{ - using TTaxonParentIDs = std::vector; // ever position has the index of its parent node - using TTaxonHeights = std::vector; - using TTaxonNames = std::vector; - - std::tuple ret; - - auto & taxonParentIDs = std::get<0>(ret); - auto & taxonHeights = std::get<1>(ret); - auto & taxonNames = std::get<2>(ret); - - taxonParentIDs.reserve(2'000'000); // reserve 2million to save reallocs - - myPrint(options, 1, "Parsing nodes.dmp... "); - - double start = sysTime(); - - bio::io::txt::reader reader{options.taxDumpDir + "/nodes.dmp", '\t'}; - for (auto & record : reader) - { - /* first column (own id) */ - uint32_t n = 0; - std::string_view col1 = record.fields[0]; - auto res1 = std::from_chars(col1.data(), col1.data() + col1.size(), n); - if (res1.ec != std::errc{}) - { - throw std::runtime_error{ - std::string{"Error: Expected taxonomical ID, but got something I couldn't read: "} + - static_cast(col1) + "\n"}; - } - - /* second column (parent id) */ - uint32_t parent = 0; - std::string_view col2 = record.fields[2]; // fields[1] is '|' - auto res2 = std::from_chars(col2.data(), col2.data() + col2.size(), parent); - if (res2.ec != std::errc{}) - { - throw std::runtime_error{ - std::string{"Error: Expected taxonomical ID, but got something I couldn't read: "} + - static_cast(col2) + "\n"}; - } - - if (std::ranges::size(taxonParentIDs) <= n) - taxonParentIDs.resize(n + 1, 0); - taxonParentIDs[n] = parent; - } - // also resize these, since we get new, possibly higher cardinality nodes - taxIdIsPresent.resize(std::ranges::size(taxonParentIDs), false); - - myPrint(options, 1, "done.\n"); - myPrint(options, 2, "Runtime: ", sysTime() - start, "s\n"); - - if (options.verbosity >= 2) - { - uint32_t heightMax = 0; - uint32_t numNodes = 0; - for (uint32_t i = 0; i < std::ranges::size(taxonParentIDs); ++i) - { - if (taxonParentIDs[i] > 0) - ++numNodes; - uint32_t height = 0; - uint32_t curPar = taxonParentIDs[i]; - while (curPar > 1) - { - curPar = taxonParentIDs[curPar]; - ++height; - } - - heightMax = std::max(heightMax, height); - } - myPrint(options, 2, "Number of nodes in tree: ", numNodes, "\n"); - myPrint(options, 2, "Maximum Tree Height: ", heightMax, "\n\n"); - } - - myPrint(options, 1, "Thinning and flattening Tree... "); - start = sysTime(); - - // taxIdIsPresent are all directly present taxIds - // taxIdIsPresentOrParent are also the (recursive) parents of the above - // we need to differentiate this later, because we will remove some intermediate nodes - // but we may not remove any that are directly present AND parents of directly present ones - std::vector taxIdIsPresentOrParent{taxIdIsPresent}; - // mark parents as present, too - for (uint32_t i = 0; i < std::ranges::size(taxonParentIDs); ++i) - { - if (taxIdIsPresent[i]) - { - // get ancestors: - uint32_t curPar = i; - do - { - curPar = taxonParentIDs[curPar]; - taxIdIsPresentOrParent[curPar] = true; - } - while (curPar > 1); - } - } - - // set unpresent nodes to 0 - // SEQAN_OMP_PRAGMA(parallel for) - for (uint32_t i = 0; i < std::ranges::size(taxonParentIDs); ++i) - if (!taxIdIsPresentOrParent[i]) - taxonParentIDs[i] = 0; - - // count inDegrees - std::vector inDegrees; - inDegrees.resize(std::ranges::size(taxonParentIDs), 0); - for (uint32_t i = 0; i < std::ranges::size(taxonParentIDs); ++i) - { - // increase inDegree of parent - uint32_t curPar = taxonParentIDs[i]; - ++inDegrees[curPar]; - } - - // skip parents with indegree 1 (flattening) - for (uint32_t i = 0; i < std::ranges::size(taxonParentIDs); ++i) - { - uint32_t curPar = taxonParentIDs[i]; - // those intermediate nodes that themselve represent sequences may not be skipped - while ((curPar > 1) && (inDegrees[curPar] == 1) && (!taxIdIsPresent[curPar])) - curPar = taxonParentIDs[curPar]; - - taxonParentIDs[i] = curPar; - } - - // remove nodes that are now disconnected - // SEQAN_OMP_PRAGMA(parallel for) - for (uint32_t i = 0; i < std::ranges::size(taxonParentIDs); ++i) - { - // those intermediate nodes that themselve represent sequences may not be skipped - if ((inDegrees[i] == 1) && (!taxIdIsPresent[i])) - { - taxonParentIDs[i] = 0; - taxIdIsPresentOrParent[i] = false; - } - } - - taxonHeights.resize(std::ranges::size(taxonParentIDs), 0); - - { - uint32_t heightMax = 0; - uint32_t numNodes = 0; - for (uint32_t i = 0; i < std::ranges::size(taxonParentIDs); ++i) - { - if (taxonParentIDs[i] > 0) - ++numNodes; - uint32_t height = 0; - uint32_t curPar = taxonParentIDs[i]; - while (curPar > 1) - { - curPar = taxonParentIDs[curPar]; - ++height; - } - taxonHeights[i] = height; - heightMax = std::max(heightMax, height); - } - - myPrint(options, 1, "done.\n"); - myPrint(options, 2, "Runtime: ", sysTime() - start, "s\n"); - - myPrint(options, 2, "Number of nodes in tree: ", numNodes, "\n"); - myPrint(options, 2, "Maximum Tree Height: ", heightMax, "\n\n"); - } - -// DEBUG -#ifndef NDEBUG - for (uint32_t i = 0; i < std::ranges::size(taxonParentIDs); ++i) - { - if (!taxIdIsPresentOrParent[i] && (taxonParentIDs[i] != 0)) - std::cerr << "WARNING: TaxID " << i << " has parent, but shouldn't.\n"; - - if (taxIdIsPresentOrParent[i] && (taxonParentIDs[i] == 0)) - std::cerr << "WARNING: TaxID " << i << " has no parent, but should.\n"; - if (taxIdIsPresent[i] && (taxonParentIDs[i] == 0)) - std::cerr << "WARNING: TaxID " << i << " has no parent, but should. 2\n"; - - if (taxIdIsPresent[i] && !taxIdIsPresentOrParent[i]) - std::cerr << "WARNING: TaxID " << i << " disappeared, but shouldn't have.\n"; - - if (!taxIdIsPresent[i] && taxIdIsPresentOrParent[i] && (inDegrees[i] == 1)) - std::cerr << "WARNING: TaxID " << i << " should have disappeared, but didn't.\n"; - } -#endif - - /** read the names **/ - taxonNames.resize(std::ranges::size(taxonParentIDs)); - - myPrint(options, 1, "Parsing names.dmp... "); - - start = sysTime(); - - bio::io::txt::reader reader2{options.taxDumpDir + "/names.dmp", '\t'}; - for (auto & record : reader2) - { - assert(record.fields.size() == 8); - - if (record.fields.size() < 6) - continue; - - if (record.fields[6] == "scientific name") - { - /* first column */ - uint32_t taxId = 0; - std::string_view col1 = record.fields[0]; - auto res1 = std::from_chars(col1.data(), col1.data() + col1.size(), taxId); - if (res1.ec != std::errc{}) - { - throw std::runtime_error{ - std::string{"Error: Expected taxonomical ID, but got something I couldn't read: "} + - static_cast(col1) + "\n"}; - } - - if (taxId >= std::ranges::size(taxonNames)) - { - throw std::runtime_error(std::string("Error: taxonomical ID is ") + std::to_string(taxId) + - ", but no such taxon in tree.\n"); - } - - /* second column (name) */ - if (taxIdIsPresentOrParent[taxId]) // check if we need the name - taxonNames[taxId].assign(record.fields[2].begin(), - record.fields[2].end()); // fields[1] is '|' separator - } - } - - myPrint(options, 1, "done.\n"); - myPrint(options, 2, "Runtime: ", sysTime() - start, "s\n"); - - taxonNames[0] = "invalid"; - size_t taxaWithoutNameCount = 0; - for (uint32_t i = 0; i < std::ranges::size(taxonNames); ++i) - { - if (taxIdIsPresentOrParent[i] && empty(taxonNames[i])) - { - std::cerr << "Warning: Taxon with ID " << i << " has no name associated, defaulting to \"n/a\".\n"; - taxonNames[i] = "n/a"; - ++taxaWithoutNameCount; - } - } - if (taxaWithoutNameCount * 10 > taxonNames.size()) - std::cerr << "Warning: More than 10% of taxa have no valid name entry.\n"; - - return ret; -} - -template -auto generateIndex(TStringSet & seqs, LambdaIndexerOptions const & options) -{ - using TRedAlph = bio::ranges::range_innermost_value_t; - using TIndexSpec = IndexSpec>; - using TIndex = std:: - conditional_t, fmindex_collection::ReverseFMIndex>; - - myPrint(options, 1, "Generating Index..."); - double s = sysTime(); - - TIndex index{seqs | bio::views::to_rank | fmindex_collection::add_sentinels, /*samplingRate*/ 5, options.threads}; - - double e = sysTime() - s; - myPrint(options, 1, " done.\n"); - myPrint(options, 2, "Runtime: ", e, "s \n\n"); - - return index; -} diff --git a/src/mkindex_misc.hpp b/src/mkindex_misc.hpp deleted file mode 100644 index 144574d40..000000000 --- a/src/mkindex_misc.hpp +++ /dev/null @@ -1,146 +0,0 @@ -// ========================================================================== -// lambda -// ========================================================================== -// Copyright (c) 2013-2024, Hannes Hauswedell

-// Copyright (c) 2016-2020, Knut Reinert and Freie Universität Berlin -// All rights reserved. -// -// This file is part of Lambda. -// -// Lambda is Free Software: you can redistribute it and/or modify it -// under the terms found in the LICENSE[.md|.rst] file distributed -// together with this file. -// -// Lambda 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. -// -// ========================================================================== -// mkindex_misc.hpp: misc stuff for indexer -// ========================================================================== - -#pragma once - -#include -#include -#include -#include -#include -#include - -#include -#include - -bool setEnv(std::string const & key, std::string const & value) -{ -#ifdef PLATFORM_WINDOWS - return !_putenv_s(key.c_str(), value.c_str()); -#else - return !setenv(key.c_str(), value.c_str(), true); -#endif -} - -// ---------------------------------------------------------------------------- -// hashmap type -// ---------------------------------------------------------------------------- - -struct hash_string -{ - using is_transparent = void; - - std::size_t operator()(std::string const & v) const { return std::hash{}(v); } - std::size_t operator()(char const * v) const { return std::hash{}(v); } - - std::size_t operator()(std::string_view const & v) const { return std::hash{}(v); } -}; - -using TaccToIdRank = std::unordered_map>; - -// ---------------------------------------------------------------------------- -// function _readMappingFileNCBI -// ---------------------------------------------------------------------------- - -#if defined(__GNUC__) && __GNUC__ < 11 -# define LAMBDA_TO_STR(x) static_cast(x) -#else -# define LAMBDA_TO_STR(x) x -#endif - -inline void _readMappingFileUniProt(std::filesystem::path const & fileName, - TaccToIdRank const & accToIdRank, - std::vector> & sTaxIds, - std::vector & taxIdIsPresent) -{ - bio::io::txt::reader reader{fileName, '\t'}; - - for (auto & r : reader) - { - assert(r.fields.size() == 3); - - std::string_view acc = r.fields[0]; - std::string_view category = r.fields[1]; - std::string_view tId = r.fields[2]; - - if (category == "NCBI_TaxID") - { - if (auto it = accToIdRank.find(LAMBDA_TO_STR(acc)); it != accToIdRank.end()) - { - std::vector & sTaxIdV = sTaxIds[it->second]; - - uint32_t idNum = 0; - auto [p, ec] = std::from_chars(tId.data(), tId.data() + tId.size(), idNum); - if (ec != std::errc{}) - { - std::string msg = "Error: Expected taxonomical ID, but got something I couldn't read: "; - msg += tId; - msg += '\n'; - throw std::runtime_error(msg); - } - sTaxIdV.push_back(idNum); - if (taxIdIsPresent.size() < idNum + 1) - taxIdIsPresent.resize(idNum + 1); - taxIdIsPresent[idNum] = true; - } - } - } -} - -inline void _readMappingFileNCBI(std::filesystem::path const & fileName, - TaccToIdRank const & accToIdRank, - std::vector> & sTaxIds, - std::vector & taxIdIsPresent) -{ - bio::io::txt::reader reader{fileName, '\t', bio::io::txt::header_kind::first_line}; - - if (reader.header() != "accession\taccession.version\ttaxid\tgi") - throw std::runtime_error{"Unexpected first line in NCBI taxid file."}; - - for (auto & r : reader) - { - assert(r.fields.size() == 4); - - std::string_view acc = r.fields[0]; - std::string_view tId = r.fields[2]; - - if (auto it = accToIdRank.find(LAMBDA_TO_STR(acc)); it != accToIdRank.end()) - { - std::vector & sTaxIdV = sTaxIds[it->second]; - - uint32_t idNum = 0; - auto [p, ec] = std::from_chars(tId.data(), tId.data() + tId.size(), idNum); - if (ec != std::errc{}) - { - std::string msg = "Error: Expected taxonomical ID, but got something I couldn't read: "; - msg += tId; - msg += '\n'; - throw std::runtime_error(msg); - } - sTaxIdV.push_back(idNum); - if (taxIdIsPresent.size() < idNum + 1) - taxIdIsPresent.resize(idNum + 1); - taxIdIsPresent[idNum] = true; - } - } -} - -#undef LAMBDA_TO_STR diff --git a/src/mkindex_options.hpp b/src/mkindex_options.hpp deleted file mode 100644 index 484d548a1..000000000 --- a/src/mkindex_options.hpp +++ /dev/null @@ -1,266 +0,0 @@ -// ========================================================================== -// lambda -// ========================================================================== -// Copyright (c) 2013-2024, Hannes Hauswedell

-// Copyright (c) 2016-2020, Knut Reinert and Freie Universität Berlin -// All rights reserved. -// -// This file is part of Lambda. -// -// Lambda is Free Software: you can redistribute it and/or modify it -// under the terms found in the LICENSE[.md|.rst] file distributed -// together with this file. -// -// Lambda 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. -// -// ========================================================================== -// mkindex_options.h: contains the options and argument parser for the indexer -// ========================================================================== - -#pragma once - -#include -#include -#include - -#include - -#include "shared_options.hpp" - -// -------------------------------------------------------------------------- -// Class LambdaIndexerOptions -// -------------------------------------------------------------------------- - -struct LambdaIndexerOptions : public SharedOptions -{ - std::string dbFile; - std::string algo = "default"; - std::string accToTaxMapFile; - std::string taxDumpDir; - - std::string tmpdir = std::filesystem::current_path(); - - bool truncateIDs = true; - - int alphReduction; - - LambdaIndexerOptions() : SharedOptions() {} -}; - -// ========================================================================== -// Functions -// ========================================================================== - -// INDEXER -void parseCommandLine(LambdaIndexerOptions & options, int argc, char const ** argv) -{ - std::string const subcommand = std::string(argv[0]); - std::string const programName = "lambda3-" + subcommand; - - // this is important for option handling: - if (subcommand == "mkindexp") - options.domain = domain_t::protein; - else if (subcommand == "mkindexn") - options.domain = domain_t::nucleotide; - else if (subcommand == "mkindexbs") - options.domain = domain_t::bisulfite; - else - throw std::runtime_error{"Unknown subcommand."}; - - sharg::parser parser(programName, argc, argv, sharg::update_notifications::off); - - parser.info.short_description = "the Local Aligner for Massive Biological DatA"; - - // Define usage line and long description. - parser.info.synopsis.push_back("lambda3 "s + subcommand + - " [\\fIOPTIONS\\fP] \\-d DATABASE.fasta [-i INDEX.lba]\\fP"); - - parser.info.description.push_back("This is the indexer command for creating lambda-compatible databases."); - - sharedSetup(parser); - - parser.add_option(options.verbosity, - sharg::config{ - .short_id = 'v', - .long_id = "verbosity", - .description = "Display more/less diagnostic output during operation: " - "0 [only errors]; 1 [default]; 2 [+run-time, options and statistics].", - .validator = sharg::arithmetic_range_validator{0, 2} - }); - - parser.add_section("Input Options"); - - std::vector extensions{"fa", "fq", "fasta", "fastq", "fna", "faa"}; -#ifdef SEQAN_HAS_ZLIB - for (auto const & ext : extensions) - extensions.push_back(ext + ".gz"); -#endif - parser.add_option(options.dbFile, - sharg::config{.short_id = 'd', - .long_id = "database", - .description = "Database sequences.", - .required = true, - .validator = sharg::input_file_validator{extensions}}); - - extensions = {"accession2taxid", "dat"}; -#ifdef SEQAN_HAS_ZLIB - for (auto const & ext : extensions) - extensions.push_back(ext + ".gz"); -#endif - - parser.add_option( - options.accToTaxMapFile, - sharg::config{.short_id = 'm', - .long_id = "acc-tax-map", - .description = - "An NCBI or UniProt accession-to-taxid mapping file. Download from " - "ftp://ftp.ncbi.nlm.nih.gov/pub/taxonomy/accession2taxid/ or " - "ftp://ftp.uniprot.org/pub/databases/uniprot/current_release/knowledgebase/idmapping/ .", - .validator = sharg::input_file_validator{extensions}}); - - parser.add_option(options.taxDumpDir, - sharg::config{.short_id = 'x', - .long_id = "tax-dump-dir", - .description = "A directory that contains nodes.dmp and names.dmp; unzipped from " - "ftp://ftp.ncbi.nlm.nih.gov/pub/taxonomy/taxdump.tar.gz", - .validator = sharg::input_directory_validator()}); - - parser.add_section("Output Options"); - - options.indexFilePath = "»INPUT«.lba"; - extensions = {"lba", "lta"}; -#ifdef SEQAN_HAS_ZLIB - for (auto const & ext : extensions) - extensions.push_back(ext + ".gz"); -#endif - parser.add_option( - options.indexFilePath, - sharg::config{ - .short_id = 'i', - .long_id = "index", - .description = "The output path for the index file.", - .validator = sharg::output_file_validator{sharg::output_file_open_options::create_new, {extensions}} - }); - - options.threads = std::max(2ul, std::min(std::thread::hardware_concurrency(), 4ul)); - parser.add_option(options.threads, - sharg::config{ - .short_id = 't', - .long_id = "threads", - .description = "Number of threads (only used for compression).", - .advanced = true, - .validator = sharg::arithmetic_range_validator{2, 1000} - }); - - std::string dbIndexTypeTmp = "fm"; - parser.add_option(dbIndexTypeTmp, - sharg::config{ - .short_id = '\0', - .long_id = "db-index-type", - .description = "FM-Index oder bidirectional FM-Index.", - .advanced = true, - .validator = sharg::value_list_validator{"fm", "bifm"} - }); - - parser.add_option( - options.truncateIDs, - sharg::config{.short_id = '\0', - .long_id = "truncate-ids", - .description = - "Truncate IDs at first whitespace. This saves a lot of space and is irrelevant for all " - "LAMBDA output formats other than BLAST Pairwise (.m0)."}); - - std::string inputAlphabetTmp = "auto"; - std::string alphabetReductionTmp; - int geneticCodeTmp = 1; - - switch (options.domain) - { - case domain_t::protein: - alphabetReductionTmp = "li10"; - options.indexFileOptions.origAlph = AlphabetEnum::UNDEFINED; - options.indexFileOptions.transAlph = AlphabetEnum::AMINO_ACID; - options.indexFileOptions.redAlph = AlphabetEnum::LI10; - - parser.add_section("Alphabet and Translation"); - - parser.add_option(inputAlphabetTmp, - sharg::config{ - .short_id = 'a', - .long_id = "input-alphabet", - .description = "Alphabet of the database sequences (specify to override " - "auto-detection); if input is Dna, it will be translated.", - .advanced = true, - .validator = sharg::value_list_validator{"auto", "dna5", "aminoacid"} - }); - - parser.add_option(alphabetReductionTmp, - sharg::config{ - .short_id = 'r', - .long_id = "alphabet-reduction", - .description = "Alphabet Reduction for seeding phase.", - .advanced = true, - .validator = sharg::value_list_validator{"none", "murphy10", "li10"} - }); - break; - case domain_t::nucleotide: - options.indexFileOptions.origAlph = AlphabetEnum::DNA5; - options.indexFileOptions.transAlph = AlphabetEnum::DNA5; - options.indexFileOptions.redAlph = AlphabetEnum::DNA4; - break; - case domain_t::bisulfite: - options.indexFileOptions.origAlph = AlphabetEnum::DNA5; - options.indexFileOptions.transAlph = AlphabetEnum::DNA5; - options.indexFileOptions.redAlph = AlphabetEnum::DNA3BS; - break; - } - - parser.add_section("Remarks"); - parser.add_line("Indexes are *NOT* compatible between different CPU endiannesses.", false); - - // parse command line. - parser.parse(); - - // set db index type - if (dbIndexTypeTmp == "bifm") - options.indexFileOptions.indexType = DbIndexType::BI_FM_INDEX; - else - options.indexFileOptions.indexType = DbIndexType::FM_INDEX; - - // set options for protein alphabet, genetic code and alphabet reduction - if (options.domain == domain_t::protein) - { - options.indexFileOptions.origAlph = _alphabetNameToEnum(inputAlphabetTmp); - if (alphabetReductionTmp == "none") - options.indexFileOptions.redAlph = AlphabetEnum::AMINO_ACID; - else - options.indexFileOptions.redAlph = _alphabetNameToEnum(alphabetReductionTmp); - options.indexFileOptions.geneticCode = static_cast(geneticCodeTmp); - } - - setEnv("TMPDIR", options.tmpdir); - - // set hasSTaxIds based on taxonomy file - options.hasSTaxIds = (options.accToTaxMapFile != ""); - - if (options.indexFilePath == "»INPUT«.lba") - options.indexFilePath = options.dbFile + ".lba"; - - if (std::filesystem::exists(options.indexFilePath)) - { - throw sharg::parser_error("ERROR: An output file already exists at " + options.indexFilePath.string() + - "\n Remove it, or choose a different location.\n"); - } - - if (!options.taxDumpDir.empty()) - { - if (!options.hasSTaxIds) - { - throw sharg::parser_error( - "ERROR: There is no point in including a taxonomic tree in the index, if\n" - " you don't also include taxonomic IDs for your sequences.\n"); - } - } -} diff --git a/src/search.cpp b/src/search.cpp deleted file mode 100644 index 38742cf74..000000000 --- a/src/search.cpp +++ /dev/null @@ -1,477 +0,0 @@ -// ========================================================================== -// lambda -// ========================================================================== -// Copyright (c) 2013-2024, Hannes Hauswedell

-// Copyright (c) 2016-2020, Knut Reinert and Freie Universität Berlin -// All rights reserved. -// -// This file is part of Lambda. -// -// Lambda is Free Software: you can redistribute it and/or modify it -// under the terms found in the LICENSE[.md|.rst] file distributed -// together with this file. -// -// Lambda 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. -// -// ========================================================================== -// search.cpp: Main File for the search -// ========================================================================== - -#include "seqan2_to_biocpp.hpp" // must come first - -#include - -#include -#include -#include -#include -#include -#include - -#include "view_async_input_buffer.hpp" - -#include "shared_definitions.hpp" -#include "shared_misc.hpp" -#include "shared_options.hpp" - -#include "search_algo.hpp" -#include "search_datastructures.hpp" -#include "search_misc.hpp" -#include "search_options.hpp" -#include "search_output.hpp" - -#ifndef SEQAN_SIMD_ENABLED -# error "Lambda must be built with at least SSE4 support. Add -march=native to your compiler flags." -#endif - -// forwards - -void argConv0(LambdaOptions & options); - -template -void argConv1(LambdaOptions const & options); - -template -void argConv2(LambdaOptions const & options); - -template -void argConv3(LambdaOptions const & options); - -template -void realMain(LambdaOptions const & options); - -// -------------------------------------------------------------------------- -// Function main() -// -------------------------------------------------------------------------- - -int searchMain(int const argc, char const ** argv) -{ - LambdaOptions options; - -#ifdef NDEBUG - try - { - parseCommandLine(options, argc, argv); - } - catch (sharg::parser_error const & ext) // catch user errors - { - std::cerr << "\n\nERROR: during command line parsing\n" - << " \"" << ext.what() << "\"\n"; - return -1; - } -#else - parseCommandLine(options, argc, argv); -#endif - -#ifdef _OPENMP - omp_set_num_threads(options.threads - options.lazyQryFile); // reserve one thread for I/O when lazy-loading -#else - options.threads = 1; -#endif - -#ifdef NDEBUG - try - { - argConv0(options); - } - catch (std::bad_alloc const & e) - { - std::cerr << "\n\nERROR: Lambda ran out of memory :(\n" - " You need to split your file into smaller segments or search against a smaller database.\n"; - return -1; - } - catch (IndexException const & e) - { - std::cerr << "\n\nERROR: The following exception was thrown while reading the index:\n" - << " \"" << e.what() << "\"\n" - << " Make sure the directory exists and is readable; recreate the index and try again.\n" - << " If the problem persists, report an issue at https://github.com/seqan/lambda/issues " - << "and include this output, as well as the output of `lambda3 --version`, thanks!\n"; - return -1; - } - catch (std::exception const & e) - { - std::cerr << "\n\nERROR: The following unspecified exception was thrown:\n" - << " \"" << e.what() << "\"\n" - << " If the problem persists, report an issue at https://github.com/seqan/lambda/issues " - << "and include this output, as well as the output of `lambda3 --version`, thanks!\n"; - return -1; - } -#else - // In debug mode we don't catch the exceptions so that we get a backtrace from SeqAn's handler - argConv0(options); -#endif - return 0; -} - -// CONVERT Run-time options to compile-time Format-Type -void argConv0(LambdaOptions & options) -{ - myPrint(options, - 1, - "LAMBDA - the Local Aligner for Massive Biological DatA" - "\n======================================================" - "\nVersion ", - SEQAN_APP_VERSION, - "\n\n"); - - // Index - myPrint(options, 1, "Reading index properties... "); - readIndexOptions(options); - myPrint(options, 1, "done.\n"); - - myPrint(options, - 2, - " type: ", - _indexEnumToName(options.indexFileOptions.indexType), - "\n", - " original alphabet: ", - _alphabetEnumToName(options.indexFileOptions.origAlph), - "\n"); - if (options.indexFileOptions.origAlph == options.indexFileOptions.transAlph) - { - myPrint(options, 2, " translated alphabet: not translated\n"); - if ((int)options.geneticCodeQry == 0) // use same geneticCode as Index, but index wasn't translated - options.geneticCodeQry = bio::alphabet::genetic_code::CANONICAL; - } - else - { - myPrint(options, 2, " translated alphabet: ", _alphabetEnumToName(options.indexFileOptions.transAlph), "\n"); - myPrint(options, 2, " ^- genetic code: ", (int)options.indexFileOptions.geneticCode, "\n"); - if ((int)options.geneticCodeQry == 0) // use same geneticCode as Index - { - options.geneticCodeQry = options.indexFileOptions.geneticCode; - } - else if (options.geneticCodeQry != options.indexFileOptions.geneticCode) - { - std::cerr << "WARNING: The genetic code used when creating the index: " - << (int)options.indexFileOptions.geneticCode - << "\n is not the same as now selected for the query sequences: " - << (int)options.geneticCodeQry << "\n Are you sure this is what you want?\n"; - } - } - - if (options.indexFileOptions.transAlph == options.indexFileOptions.redAlph) - { - myPrint(options, 2, " reduced alphabet: not reduced\n"); - } - else - { - myPrint(options, 2, " reduced alphabet: ", _alphabetEnumToName(options.indexFileOptions.redAlph), "\n\n"); - } - - switch (options.domain) - { - case domain_t::protein: - if (options.indexFileOptions.transAlph != AlphabetEnum::AMINO_ACID) - throw std::runtime_error{"Attempting to use nucleotide or bisulfite index for protein search."}; - break; - case domain_t::nucleotide: - if (options.indexFileOptions.transAlph != AlphabetEnum::DNA5) - throw std::runtime_error{"Attempting to use protein index for nucleotide search."}; - if (options.indexFileOptions.redAlph != AlphabetEnum::DNA4) - throw std::runtime_error{"Attempting to use bisulfite index for nucleotide search."}; - break; - case domain_t::bisulfite: - if (options.indexFileOptions.transAlph != AlphabetEnum::DNA5) - throw std::runtime_error{"Attempting to use protein index for bisulfite search."}; - if (options.indexFileOptions.redAlph != AlphabetEnum::DNA3BS) - throw std::runtime_error{"Attempting to use nucleotid index for bisulfite search."}; - break; - } - - // query file - if (options.qryOrigAlphabet == - AlphabetEnum::DNA4) // means "auto", as dna4 not valid as argument to --input-alphabet - { - myPrint(options, 1, "Detecting query alphabet... "); - options.qryOrigAlphabet = detectSeqFileAlphabet(options.queryFile); - myPrint(options, 1, _alphabetEnumToName(options.qryOrigAlphabet), " detected.\n"); - myPrint(options, 2, "\n"); - } - -#if 0 // blastProgram set in GlobalDataHolder later - // set blastProgram - if (options.blastProgram == seqan::BlastProgram::UNKNOWN) - { - if ((options.indexFileOptions.transAlph == AlphabetEnum::DNA5) && (options.qryOrigAlphabet == AlphabetEnum::AMINO_ACID)) - { - throw IndexException("Query file is protein, but index is nucleotide. " - "Recreate the index with 'lambda mkindexp'."); - } - else if ((options.indexFileOptions.transAlph == AlphabetEnum::DNA5) && (options.qryOrigAlphabet == AlphabetEnum::DNA5)) - { - options.blastProgram = seqan::BlastProgram::BLASTN; - } - else if (options.qryOrigAlphabet == AlphabetEnum::DNA5) // query will be translated - { - if (options.indexFileOptions.origAlph == options.indexFileOptions.transAlph) - options.blastProgram = seqan::BlastProgram::BLASTX; - else - options.blastProgram = seqan::BlastProgram::TBLASTX; - } - else // query is aminoacid already - { - if (options.indexFileOptions.origAlph == options.indexFileOptions.transAlph) - options.blastProgram = seqan::BlastProgram::BLASTP; - else - options.blastProgram = seqan::BlastProgram::TBLASTN; - } - } - -#endif - -#if 0 // this needs to be moved - // some blastProgram-specific "late option modifiers" - if (((options.blastProgram == seqan::BlastProgram::BLASTP) || - (options.blastProgram == seqan::BlastProgram::TBLASTN)) && - (!options.samBamTags[SamBamExtraTags<>::Q_AA_CIGAR])) - options.samBamSeq = 0; -#endif - // sizes - checkRAM(options); - - switch (options.indexFileOptions.indexType) - { - case DbIndexType::FM_INDEX: - return argConv1(options); - case DbIndexType::BI_FM_INDEX: -#if LAMBDA_WITH_BIFM - return argConv1(options); -#else - throw std::runtime_error{ - "To open bidirectional indexes, you need to rebuild lambda with LAMBDA_WITH_BIFM=1 ."}; -#endif - default: - throw 52; - } -} - -template -void argConv1(LambdaOptions const & options) -{ - switch (options.domain) - { - case domain_t::protein: - switch (options.indexFileOptions.origAlph) - { - case AlphabetEnum::DNA5: - return argConv2(options); - case AlphabetEnum::AMINO_ACID: - return argConv2(options); - default: - throw 53; - break; - } - break; - case domain_t::nucleotide: - return realMain(options); - case domain_t::bisulfite: - return realMain(options); - } -} - -template -void argConv2(LambdaOptions const & options) -{ - // transalph is always amino acid, unless in nucleotide_mode - switch (options.indexFileOptions.redAlph) - { - case AlphabetEnum::AMINO_ACID: - return argConv3(options); - case AlphabetEnum::MURPHY10: - return argConv3(options); - case AlphabetEnum::LI10: - return argConv3(options); - default: - throw 54; - } -} - -template -void argConv3(LambdaOptions const & options) -{ - // transalph is always amino acid, unless in nucleotide_mode - switch (options.qryOrigAlphabet) - { - case AlphabetEnum::DNA5: - return realMain(options); - case AlphabetEnum::AMINO_ACID: - return realMain(options); - default: - throw 55; - } -} - -template -void realMain(LambdaOptions const & options) -{ - using TGlobalHolder = GlobalDataHolder; - using TLocalHolder = LocalDataHolder; - - if (options.verbosity >= 2) - printOptions(options); - - TGlobalHolder globalHolder; - - prepareScoring(globalHolder, options); - - loadDbIndexFromDisk(globalHolder, options); - - if (options.lazyQryFile) - countQuery(globalHolder, options); - else - loadQuery(globalHolder, options); - - myWriteHeader(globalHolder, options); - - myPrint(options, - 1, - "Searching and extending hits on-line...progress:\n" - "0% 10% 20% 30% 40% 50% 60% 70% 80% 90% 100%\n|"); - - double start = sysTime(); - uint64_t lastPercent = 0; - - /* Setup lazy-loader for query (if set in options) */ - decltype(createQryView(globalHolder, options)) file_view; - if (options.lazyQryFile) - file_view = createQryView(globalHolder, options); - - SEQAN_OMP_PRAGMA(parallel) - { - TLocalHolder localHolder(options, globalHolder); - - /* Define region of query this thread gets (eager-loading only) */ - size_t const chunk_begin = globalHolder.qrySeqs.size() * omp_get_thread_num() / omp_get_num_threads(); - size_t const chunk_end = globalHolder.qrySeqs.size() * (omp_get_thread_num() + 1) / omp_get_num_threads(); - /* Track (per-thread) batch count (eager-loading only) */ - size_t batch_i = 0; - - while (true) - { - if (localHolder.iterativeSearch != IterativeSearchMode::PHASE2) - { - localHolder.reset(); - - if (options.lazyQryFile) // load records until batch is full or file at end - { - for (auto & [id, seq, qual] : file_view) - { - localHolder.qryIdsTmp.push_back(std::move(id)); - localHolder.qrySeqsTmp.push_back(std::move(seq)); - - if (++localHolder.queryCount == globalHolder.records_per_batch) // no more records in file - break; - } - - localHolder.qryIds = localHolder.qryIdsTmp; - localHolder.qrySeqs = localHolder.qrySeqsTmp; - } - else // select subset from stored query sequences - { - size_t const slice_begin = - std::min(chunk_end, chunk_begin + batch_i * globalHolder.records_per_batch); - size_t const slice_end = std::min(chunk_end, slice_begin + globalHolder.records_per_batch); - - localHolder.qryIds = globalHolder.qryIds | bio::views::slice(slice_begin, slice_end); - localHolder.qrySeqs = globalHolder.qrySeqs | bio::views::slice(slice_begin, slice_end); - - ++batch_i; - localHolder.queryCount = localHolder.qrySeqs.size(); - } - - if (localHolder.queryCount == 0) // no more records in file - break; - - globalHolder.queryCount += localHolder.queryCount; // atomic can be written from multiple threads - } - - localHolder.resetViews(); // views reset after sequences have been loaded - - // seed -#ifdef LAMBDA_MICRO_STATS - double buf = sysTime(); -#endif - search(localHolder); -#ifdef LAMBDA_MICRO_STATS - localHolder.stats.timeSearch += sysTime() - buf; -#endif - // extend - if (localHolder.matches.size() > 0) - iterateMatches(localHolder); - - if ((omp_get_thread_num() == 0) && (options.verbosity >= 1)) - { - // round to even - size_t curPercent = ((globalHolder.queryCount.load() * 50) / globalHolder.queryTotal) * 2; - printProgressBar(lastPercent, curPercent); - } - - // Check which queries are already successfull - iterativeSearchPre(localHolder); - - // write to disk - if (localHolder.blastMatches.size() > 0) - writeRecords(localHolder); - - // prepare second phase if necessary - iterativeSearchPost(localHolder); - - } // implicit thread sync here - - if ((omp_get_thread_num() == 0) && (options.verbosity >= 1)) - printProgressBar(lastPercent, 100); - - SEQAN_OMP_PRAGMA(critical(statsAdd)) - { - globalHolder.stats += localHolder.stats; - } - } - - myPrint(options, 1, "\n"); - - myWriteFooter(globalHolder, options); - - myPrint(options, 2, "Runtime total: ", sysTime() - start, "s.\n\n"); - - printStats(globalHolder.stats, options); -} diff --git a/src/search.hpp b/src/search.hpp deleted file mode 100644 index 27a4b551d..000000000 --- a/src/search.hpp +++ /dev/null @@ -1,24 +0,0 @@ -// ========================================================================== -// lambda -// ========================================================================== -// Copyright (c) 2013-2024, Hannes Hauswedell

-// Copyright (c) 2016-2020, Knut Reinert and Freie Universität Berlin -// All rights reserved. -// -// This file is part of Lambda. -// -// Lambda is Free Software: you can redistribute it and/or modify it -// under the terms found in the LICENSE[.md|.rst] file distributed -// together with this file. -// -// Lambda 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. -// -// ========================================================================== -// search.hpp -// ========================================================================== - -#pragma once - -int searchMain(int const argc, char const ** argv); diff --git a/src/search_algo.hpp b/src/search_algo.hpp deleted file mode 100644 index 09bdd0b75..000000000 --- a/src/search_algo.hpp +++ /dev/null @@ -1,1460 +0,0 @@ -// ========================================================================== -// lambda -// ========================================================================== -// Copyright (c) 2013-2024, Hannes Hauswedell

-// Copyright (c) 2016-2019, Knut Reinert and Freie Universität Berlin -// All rights reserved. -// -// This file is part of Lambda. -// -// Lambda is Free Software: you can redistribute it and/or modify it -// under the terms found in the LICENSE[.md|.rst] file distributed -// together with this file. -// -// Lambda 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. -// -// ========================================================================== -// search_algo.hpp: functions to set up, perform and evaluate the search -// ========================================================================== - -#pragma once - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#if __cpp_lib_ranges <= 202106L -# include -#endif - -#include -#include -#include -#include -#include - -#include "bisulfite_scoring.hpp" -#include "evaluate_bisulfite_alignment.hpp" -#include "search_datastructures.hpp" -#include "search_misc.hpp" -#include "search_options.hpp" -#include "view_dna_n_to_random.hpp" -#include "view_reduce_to_bisulfite.hpp" - -// ============================================================================ -// Functions -// ============================================================================ - -// -------------------------------------------------------------------------- -// Function readIndexOptions() -// -------------------------------------------------------------------------- - -void readIndexOptions(LambdaOptions & options) -{ - std::string filename(options.indexFilePath); - size_t t = std::min(options.threads, 4); // more than four threads is harmful - - /* verify the correct index_generation */ - uint64_t indexGeneration = -1; - if (filename.ends_with(".lba") || filename.ends_with(".lba.gz")) - { - bio::io::transparent_istream is{filename, {.threads = t}}; - cereal::BinaryInputArchive iarchive(is); - iarchive(cereal::make_nvp("generation", indexGeneration)); - } - else if (filename.ends_with(".lta") || filename.ends_with(".lta.gz")) - { - bio::io::transparent_istream is{filename, {.threads = t}}; - cereal::JSONInputArchive iarchive(is); - iarchive(cereal::make_nvp("generation", indexGeneration)); - } - else - { - throw 59; - } - - if (indexGeneration != supportedIndexGeneration) - { - std::string error = "ERROR: this version of Lambda only supports INDEXES of generation " + - std::to_string(supportedIndexGeneration) + - ", but the provided index was of generation: " + std::to_string(indexGeneration) + - ". PLEASE RECREATE THE INDEX!\n"; - throw std::runtime_error{error}; - } - - /* load index "options" */ - fake_index_file f{options.indexFileOptions}; - bio::io::transparent_istream is{filename, {.threads = t}}; - - if (filename.ends_with(".lba") || filename.ends_with(".lba.gz")) - { - cereal::BinaryInputArchive iarchive(is); - iarchive(cereal::make_nvp("lambda index", f)); - } - else if (filename.ends_with(".lta") || filename.ends_with(".lta.gz")) - { - cereal::JSONInputArchive iarchive(is); - iarchive(cereal::make_nvp("lambda index", f)); - } - else - { - throw 59; - } -} - -// -------------------------------------------------------------------------- -// Function checkRAM() -// -------------------------------------------------------------------------- - -void checkRAM(LambdaOptions const & options) -{ - myPrint(options, 1, "Checking memory requirements... "); - uint64_t ram = getTotalSystemMemory(); - uint64_t sizeIndex = 0; - uint64_t sizeQuery = 0; - - sizeIndex = fileSize(options.indexFilePath.c_str()); - - sizeQuery = fileSize(options.queryFile.c_str()); - - uint64_t requiredRAM = 0; - - //TODO I have verified this for 2-16 threads on uniprot, but we should also double-check on Uniref50 - if (options.lazyQryFile) - requiredRAM = (sizeIndex * 12) / 10; // give it +20% - else - requiredRAM = ((sizeIndex + sizeQuery) * 12) / 10; // give it +20% - - if (requiredRAM >= ram) - { - myPrint(options, 1, "done.\n"); - std::cerr << "WARNING: You need approximately " << requiredRAM / 1024 / 1024 << "MB of memory, " - << "but you have only " << ram / 1024 / 1024 - << " :'(\nYou should abort this run and try on a machine with more memory!"; - } - - myPrint(options, 1, "met.\n"); - myPrint(options, 2, "Detected: ", ram / 1024 / 1024, "MB, Estimated: ", requiredRAM / 1024 / 1024, "MB\n\n"); -} - -// -------------------------------------------------------------------------- -// Function prepareScoring() -// -------------------------------------------------------------------------- - -template -void prepareScoring( - GlobalDataHolder & globalHolder, - LambdaOptions const & options) -{ - if constexpr (c_transAlph != AlphabetEnum::AMINO_ACID) - { - // Seqan2 - seqan::setScoreMatch(context(globalHolder.outfileBlastTab).scoringScheme, options.match); - seqan::setScoreMismatch(context(globalHolder.outfileBlastTab).scoringScheme, options.misMatch); - - if constexpr (c_redAlph == AlphabetEnum::DNA3BS) - { - // Seqan2 - seqan::setScoreBisulfiteMatrix(globalHolder.scoringSchemeAlign, - options.match, - options.misMatch, - bsDirection::fwd); - seqan::setScoreBisulfiteMatrix(globalHolder.scoringSchemeAlignBSRev, - options.match, - options.misMatch, - bsDirection::rev); - } - else - { - // Seqan2 - globalHolder.scoringSchemeAlign = seqan::seqanScheme(context(globalHolder.outfileBlastTab).scoringScheme); - globalHolder.scoringSchemeAlignBSRev = - seqan::seqanScheme(context(globalHolder.outfileBlastTab).scoringScheme); - } - } - else - { - seqan::AminoAcidScoreMatrixID seqan2_matrix_id{}; - - switch (options.scoringMethod) - { - case 45: - seqan2_matrix_id = seqan::AminoAcidScoreMatrixID::BLOSUM45; - break; - case 62: - seqan2_matrix_id = seqan::AminoAcidScoreMatrixID::BLOSUM62; - break; - case 80: - seqan2_matrix_id = seqan::AminoAcidScoreMatrixID::BLOSUM80; - break; - default: - break; - } - - // seqan2 - seqan::setScoreMatrixById(seqan::context(globalHolder.outfileBlastTab).scoringScheme._internalScheme, - seqan2_matrix_id); - seqan::setScoreMatrixById(globalHolder.scoringSchemeAlign, seqan2_matrix_id); - seqan::setScoreMatrixById(globalHolder.scoringSchemeAlignBSRev, seqan2_matrix_id); - } - - // seqan2 - seqan::setScoreGapOpenBlast(seqan::context(globalHolder.outfileBlastTab).scoringScheme, options.gapOpen); - seqan::setScoreGapExtend(seqan::context(globalHolder.outfileBlastTab).scoringScheme, options.gapExtend); - - seqan::setScoreGapOpen(globalHolder.scoringSchemeAlign, options.gapOpen + options.gapExtend); - seqan::setScoreGapExtend(globalHolder.scoringSchemeAlign, options.gapExtend); - - seqan::setScoreGapOpen(globalHolder.scoringSchemeAlignBSRev, options.gapOpen + options.gapExtend); - seqan::setScoreGapExtend(globalHolder.scoringSchemeAlignBSRev, options.gapExtend); - - if (!seqan::isValid(seqan::context(globalHolder.outfileBlastTab).scoringScheme)) - throw std::runtime_error{"Could not compute Karlin-Altschul-Values for Scoring Scheme.\n"}; -} - -// -------------------------------------------------------------------------- -// Function loadIndexFromDisk() -// -------------------------------------------------------------------------- - -template -void loadDbIndexFromDisk( - GlobalDataHolder & globalHolder, - LambdaOptions const & options) -{ - std::string strIdent = "Loading Database Index..."; - myPrint(options, 1, strIdent); - double start = sysTime(); - - { - std::string filename(options.indexFilePath); - size_t threads = std::min(options.threads, 4); // more than four threads is harmful - bio::io::transparent_istream is{filename, {.threads = threads}}; - - if (filename.ends_with(".lba") || filename.ends_with(".lba.gz")) - { - cereal::BinaryInputArchive iarchive(is); - iarchive(cereal::make_nvp("lambda index", globalHolder.indexFile)); - } - else if (filename.ends_with(".lta") || filename.ends_with(".lta.gz")) - { - cereal::JSONInputArchive iarchive(is); - iarchive(cereal::make_nvp("lambda index", globalHolder.indexFile)); - } - else - { - throw 88; - } - } - - globalHolder.transSbjSeqs = globalHolder.indexFile.seqs | sbjTransView; - globalHolder.redSbjSeqs = globalHolder.transSbjSeqs | redView; - - size_t searchSpaceSize = 0ull; - - if (options.verbosity == 2) - { - searchSpaceSize = bio::meta::overloaded{[](bio::ranges::concatenated_sequences const & seqs) - { return seqs.concat_size(); }, - [](auto const & seqs) - { - auto v = seqs | std::views::transform(std::ranges::size); - return std::reduce(v.begin(), v.end(), 0ull); - }}(globalHolder.transSbjSeqs); - } - - double finish = sysTime() - start; - myPrint(options, 1, " done.\n"); - - myPrint(options, 2, " # original subjects: ", globalHolder.indexFile.seqs.size(), "\n"); - myPrint(options, 2, " # translated subjects: ", globalHolder.transSbjSeqs.size(), "\n"); - myPrint(options, 2, " # reduced subjects: ", globalHolder.redSbjSeqs.size(), "\n"); - myPrint(options, 2, " size of search space: ", searchSpaceSize, "\n"); - bool const indexHasSTaxIDs = globalHolder.indexFile.sTaxIds.size() == globalHolder.indexFile.seqs.size(); - myPrint(options, 2, " has taxonomic IDs: ", indexHasSTaxIDs, "\n"); - bool const indexHasTaxTree = !globalHolder.indexFile.taxonNames.empty(); - myPrint(options, 2, " has taxonomic tree: ", indexHasTaxTree, "\n"); - myPrint(options, 2, "Runtime: ", finish, "s \n\n"); - - if (options.hasSTaxIds && !indexHasSTaxIDs) - { - throw std::runtime_error{ - "You requested printing of taxonomic IDs and/or taxonomic binning, but the index " - "does not contain taxonomic information. Recreate it and provide --acc-tax-map ."}; - } - if (options.computeLCA && !indexHasTaxTree) - { - throw std::runtime_error{ - "You requested taxonomic binning, but the index " - "does not contain a taxonomic tree. Recreate it and provide --tax-dump-dir ."}; - } - - /* this is actually part of prepareScoring(), but the values are just available now */ - auto sizes = globalHolder.redSbjSeqs | std::views::transform(std::ranges::size); - seqan::context(globalHolder.outfileBlastTab).dbTotalLength = std::accumulate(sizes.begin(), sizes.end(), 0ull); - seqan::context(globalHolder.outfileBlastTab).dbNumberOfSeqs = globalHolder.redSbjSeqs.size(); - seqan::context(globalHolder.outfileBlastTab).dbName = options.indexFilePath; -} - -// -------------------------------------------------------------------------- -// Function loadQuery() -// -------------------------------------------------------------------------- - -template -void loadQuery(GlobalDataHolder & globalHolder, - LambdaOptions const & options) -{ - using TGH = GlobalDataHolder; - - double start = sysTime(); - - std::string strIdent = "Loading Query Sequences..."; - myPrint(options, 1, strIdent); - - bio::io::seq::record r{.id = std::string{}, .seq = std::vector{}, .qual = std::ignore}; - bio::io::seq::reader reader{options.queryFile, bio::io::seq::reader_options{.record = r}}; - for (auto & rec : reader) - { - globalHolder.qryIds.push_back(std::move(rec.id)); - globalHolder.qrySeqs.push_back(std::move(rec.seq)); - } - - // parse the file completely and get count in one line: - globalHolder.queryTotal = globalHolder.qrySeqs.size(); - - // batch-size as set in options (unless too few sequences) - globalHolder.records_per_batch = std::max( - std::min(globalHolder.queryTotal / (options.threads * 10), options.maximumQueryBlockSize), - 1); - double finish = sysTime() - start; - myPrint(options, 1, " done.\n"); - - myPrint(options, 2, "Runtime: ", finish, "s \n\n"); -} - -template -void countQuery(GlobalDataHolder & globalHolder, - LambdaOptions const & options) -{ - double start = sysTime(); - - std::string strIdent = "Counting Query Sequences..."; - myPrint(options, 1, strIdent); - -#if __GNUC__ >= 11 - bio::io::seq::record r{.id = std::ignore, .seq = std::ignore, .qual = std::ignore}; - bio::io::seq::reader reader{options.queryFile, bio::io::seq::reader_options{.record = r}}; -#else // it is absolutely unclear why this workaround is needed here––CTAD with member-init works everywhere else - bio::io::seq::record r{}; - bio::io::seq::reader reader{options.queryFile, bio::io::seq::reader_options{}}; -#endif - - // parse the file completely and get count in one line: - globalHolder.queryTotal = std::ranges::distance(reader); - - // batch-size as set in options (unless too few sequences) - globalHolder.records_per_batch = std::max( - std::min(globalHolder.queryTotal / (options.threads * 10), options.maximumQueryBlockSize), - 1); - double finish = sysTime() - start; - myPrint(options, 1, " done.\n"); - - myPrint(options, 2, "Runtime: ", finish, "s \n\n"); -} - -template -auto createQryView(GlobalDataHolder & globalHolder, - LambdaOptions const & options) -{ - using TGH = GlobalDataHolder; - bio::io::seq::record r{.id = std::string{}, .seq = std::vector{}, .qual = std::ignore}; - bio::io::seq::reader reader{options.queryFile, bio::io::seq::reader_options{.record = r}}; - -#if __cpp_lib_ranges <= 202106L - return std::move(reader) | bio::views::persist | - views::async_input_buffer(globalHolder.records_per_batch * options.threads); -#else - return std::move(reader) | views::async_input_buffer(globalHolder.records_per_batch * options.threads); -#endif -} - -/// THREAD LOCAL STUFF - -// -------------------------------------------------------------------------- -// Function seedLooksPromising() -// -------------------------------------------------------------------------- - -// perform a fast local alignment score calculation on the seed and see if we -// reach above threshold -// WARNING the following function only works for hammingdistanced seeds -template -inline bool seedLooksPromising(LocalDataHolder const & lH, typename TGlobalHolder::TMatch const & m) -{ - int64_t effectiveQBegin = m.qryStart; - int64_t effectiveSBegin = m.subjStart; - uint64_t actualLength = m.qryEnd - m.qryStart; - uint64_t effectiveLength = - std::max(static_cast(lH.searchOpts.seedLength * lH.options.preScoring), actualLength); - - if (effectiveLength > actualLength) - { - effectiveQBegin -= (effectiveLength - actualLength) / 2; - effectiveSBegin -= (effectiveLength - actualLength) / 2; - - int64_t min = std::min(effectiveQBegin, effectiveSBegin); - if (min < 0) - { - effectiveQBegin -= min; - effectiveSBegin -= min; - effectiveLength += min; - } - - effectiveLength = - std::min({static_cast(std::ranges::size(lH.transQrySeqs[m.qryId]) - effectiveQBegin), - static_cast(std::ranges::size(lH.gH.transSbjSeqs[m.subjId]) - effectiveSBegin), - effectiveLength}); - } - - auto const & qSeq = lH.transQrySeqs[m.qryId] | - bio::views::slice(effectiveQBegin, static_cast(effectiveQBegin + effectiveLength)); - auto const & sSeq = lH.gH.transSbjSeqs[m.subjId] | - bio::views::slice(effectiveSBegin, static_cast(effectiveSBegin + effectiveLength)); - - int s = 0; - int maxScore = 0; - int const thresh = lH.options.preScoringThresh * effectiveLength; - - // score the diagonal - auto & currentScoringScheme = TGlobalHolder::c_redAlph == AlphabetEnum::DNA3BS && m.subjId % 2 - ? lH.gH.scoringSchemeAlignBSRev - : lH.gH.scoringSchemeAlign; - - for (uint64_t i = 0; i < effectiveLength; ++i) - { - s += score(currentScoringScheme, qSeq[i], sSeq[i]); - - if (s < 0) - s = 0; - else if (s > maxScore) - maxScore = s; - - if (maxScore >= thresh) - return true; - } - return false; -} - -template -inline void search_impl(LocalDataHolder & lH, TSeed && seed) -{ - if constexpr (TGlobalHolder::c_dbIndexType == DbIndexType::FM_INDEX) - { - fmindex_collection::search_backtracking_with_buffers::search( - lH.gH.indexFile.index, - seed | bio::views::to_rank | fmindex_collection::add_sentinel, - lH.searchOpts.maxSeedDist, - lH.cursor_tmp_buffer, - lH.cursor_tmp_buffer2, - [&](auto cursor, size_t /*errors*/) { lH.cursor_buffer.push_back(cursor); }); - } - else if constexpr (TGlobalHolder::c_dbIndexType == DbIndexType::BI_FM_INDEX) - { - if (lH.searchOpts.maxSeedDist == 0) - { - [&]() - { - using cursor_t = TGlobalHolder::TIndexCursor; - - auto query = seed | bio::views::to_rank | fmindex_collection::add_sentinel; - - auto cur = cursor_t{lH.gH.indexFile.index}; - for (size_t i{0}; i < query.size(); ++i) - { - auto r = query[query.size() - i - 1]; - cur = cur.extendLeft(r); - if (cur.empty()) - { - return; - } - } - lH.cursor_buffer.push_back(cur); - }(); - } - else if (lH.searchOpts.maxSeedDist == 1) - { - fmindex_collection::search_one_error::search(lH.gH.indexFile.index, - seed | bio::views::to_rank | fmindex_collection::add_sentinel, - [&](auto cursor, size_t /*errors*/) - { lH.cursor_buffer.push_back(cursor); }); - } - else - { - fmindex_collection::search_pseudo::search( - lH.gH.indexFile.index, - seed | bio::views::to_rank | fmindex_collection::add_sentinel, - lH.searchScheme, - [&](auto cursor, size_t /*errors*/) { lH.cursor_buffer.push_back(cursor); }); - } - } -} - -template -inline void searchHalfExactImpl(LocalDataHolder & lH, TSeed && seed) -{ - auto extendRight = [&](auto & cursor, auto c) - { - auto newCursor = cursor.extendRight(c.to_rank() + 1); - if (newCursor.empty()) - { - return false; - } - cursor = newCursor; - return true; - }; - - using alph_t = std::ranges::range_value_t; - - lH.cursor_tmp_buffer.clear(); - lH.cursor_tmp_buffer2.clear(); - size_t const seedFirstHalfLength = lH.searchOpts.seedLength / 2; - size_t const seedSecondHalfLength = lH.searchOpts.seedLength - seedFirstHalfLength; - - lH.cursor_tmp_buffer.emplace_back(lH.gH.indexFile.index, 0); - auto & c = lH.cursor_tmp_buffer.back().first; - - // extend by half exactly - for (size_t i = 0; i < seedFirstHalfLength; ++i) - { - auto newCursor = c.extendRight(seed[i].to_rank() + 1); - if (newCursor.empty()) - { - return; - } - c = newCursor; - } - - // manual backtracking - for (size_t i = 0; i < seedSecondHalfLength; ++i) - { - auto seed_at_i = seed[seedFirstHalfLength + i]; - - for (auto & [cursor, error_count] : lH.cursor_tmp_buffer) - { - if (error_count < lH.searchOpts.maxSeedDist) - { - for (size_t r = 0; r < bio::alphabet::size; ++r) - { - alph_t cur_letter = bio::alphabet::assign_rank_to(r, alph_t{}); - - lH.cursor_tmp_buffer2.emplace_back(cursor, error_count + (cur_letter != seed_at_i)); - if (!extendRight(lH.cursor_tmp_buffer2.back().first, cur_letter)) - lH.cursor_tmp_buffer2.pop_back(); - } - } - else - { - lH.cursor_tmp_buffer2.emplace_back(cursor, error_count); - if (!extendRight(lH.cursor_tmp_buffer2.back().first, seed_at_i)) - lH.cursor_tmp_buffer2.pop_back(); - } - } - lH.cursor_tmp_buffer.clear(); - std::swap(lH.cursor_tmp_buffer, lH.cursor_tmp_buffer2); - } - - lH.cursor_buffer.reserve(lH.cursor_buffer.size() + lH.cursor_tmp_buffer.size()); - std::ranges::copy(lH.cursor_tmp_buffer | std::views::elements<0>, std::back_inserter(lH.cursor_buffer)); - lH.cursor_tmp_buffer.clear(); -} - -template -inline void search(LocalDataHolder & lH) -{ - using TTransAlph = typename TGlobalHolder::TTransAlph; - using TMatch = typename TGlobalHolder::TMatch; - - /* The flag changes seeding to take into account how successful previous seeding operations were. - * It basically changes the "heuristicFactor" below to be evidence-based (although the formula is also - * slightly different). - * This makes seeding more robust to different kinds of datasets and options, but due to multi-threading - * it also makes the results becoming non-deterministic (i.e. repeated runs of the program may produce - * slightly different amounts of results). - */ -#ifdef LAMBDA_NONDETERMINISTIC_SEEDS - [[maybe_unused]] size_t const hitPerFinalHit = - (double)lH.stats.hitsAfterSeeding / std::max(lH.stats.hitsFinal, 1.0); -#endif - - size_t hitsThisSeq = 0; // hits per untranslated sequence (multiple frames counted together) - size_t needlesSum = 0; // cumulative size of all frames of a sequence - size_t needlesPos = 0; // current position in the cumulative length - constexpr size_t heuristicFactor = 10; // a vague approximation of the success rate of seeds - - /* These values are used to track how many hits we already have per untranslated sequence, - * how many seeds we still have after the current one, and based on that, how many hits we - * expect that the current seed needs to have. - * With this information, the current seed can be elongated to get better (but fewer) hits. - */ - - for (size_t i = 0; i < std::ranges::size(lH.redQrySeqs); ++i) - { - if (lH.redQrySeqs[i].size() < lH.searchOpts.seedLength) - continue; - - if (i % TGlobalHolder::qryNumFrames == 0) // reset on every "real" new read - { - hitsThisSeq = 0; - needlesSum = 0; - needlesPos = 0; - for (size_t j = 0; j < TGlobalHolder::qryNumFrames; ++j) - needlesSum += lH.redQrySeqs[i + j].size(); - } - - for (size_t seedBegin = 0; /* below */; seedBegin += lH.searchOpts.seedOffset) - { - // skip proteine 'X' or Dna 'N', skip letter if next letter is the same - while ((seedBegin < (lH.redQrySeqs[i].size() - lH.searchOpts.seedLength)) && - ((lH.transQrySeqs[i][seedBegin] == - bio::alphabet::assign_char_to('`', TTransAlph{})) || // assume that '°' gets converted to UNKNOWN - (lH.transQrySeqs[i][seedBegin] == lH.transQrySeqs[i][seedBegin + 1]))) - ++seedBegin; - - // termination criterium - if (seedBegin > (lH.redQrySeqs[i].size() - lH.searchOpts.seedLength)) - break; - - // results are in cursor_buffer - lH.cursor_buffer.clear(); - if (lH.options.seedHalfExact && lH.searchOpts.maxSeedDist != 0) - searchHalfExactImpl(lH, - lH.redQrySeqs[i] | - bio::views::slice(seedBegin, seedBegin + lH.searchOpts.seedLength)); - else - search_impl(lH, lH.redQrySeqs[i] | bio::views::slice(seedBegin, seedBegin + lH.searchOpts.seedLength)); - - if (lH.options.adaptiveSeeding) - lH.offset_modifier_buffer.clear(); - - for (auto & cursor : lH.cursor_buffer) - { - size_t seedLength = lH.searchOpts.seedLength; - - // elongate seeds - if (lH.options.adaptiveSeeding) - { -#ifdef LAMBDA_NONDETERMINISTIC_SEEDS - size_t desiredOccs = - hitsThisSeq >= lH.options.maxMatches * hitPerFinalHit - ? 1 - : (lH.options.maxMatches * hitPerFinalHit - hitsThisSeq) / - std::max((needlesSum - needlesPos - seedBegin) / lH.searchOpts.seedOffset, 1ul); - -#else - // lambda2 mode BUT NOT QUIET - // desiredOccs == the number of seed hits we estimate that we need to reach lH.options.maxMatches - // hitsThisSeq >= lH.options.maxMatches → if we have more than we need already, only look for one - // (lH.options.maxMatches - hitsThisSeq) * heuristicFactor → total desired hits - // ((needlesSum - needlesPos - seedBegin) / lH.searchOpts.seedOffset → number of remaining seeds - // dividing the last two yields desired hits FOR THE CURRENT SEED - size_t desiredOccs = - hitsThisSeq >= lH.options.maxMatches - ? 1 - : (lH.options.maxMatches - hitsThisSeq) * heuristicFactor / - std::max((needlesSum - needlesPos - seedBegin) / lH.searchOpts.seedOffset, 1ul); -#endif - - if (desiredOccs == 0) - desiredOccs = 1; - - // This aborts when we fall under the threshold - auto old_cursor = cursor; - size_t old_count = cursor.count(); - while (seedBegin + seedLength < lH.redQrySeqs[i].size()) - { - cursor = cursor.extendRight((lH.redQrySeqs[i][seedBegin + seedLength]).to_rank() + 1); - - size_t new_count = cursor.count(); - - if (new_count < desiredOccs && - new_count < old_count) // we always continue to extend if we don't loose anything - { - // revert last extension - cursor = old_cursor; - break; - } - - ++seedLength; - old_count = new_count; - old_cursor = cursor; - } - } - - // discard over-abundant seeds (typically seeds at end of sequence that couldn't be elongated) - if (cursor.count() > heuristicFactor * lH.options.maxMatches) - continue; - - // locate hits - for (auto [subjNo, subjOffset] : fmindex_collection::LocateLinear{lH.gH.indexFile.index, cursor}) - { - TMatch m{static_cast(i), - static_cast(subjNo), - static_cast(seedBegin), - static_cast(seedBegin + seedLength), - static_cast(subjOffset), - static_cast(subjOffset + seedLength)}; - - ++lH.stats.hitsAfterSeeding; - - if (!seedLooksPromising(lH, m)) - { - ++lH.stats.hitsFailedPreExtendTest; - } - else - { - lH.matches.push_back(m); - ++hitsThisSeq; -#ifdef LAMBDA_MICRO_STATS - lH.stats.seedLengths.push_back(seedLength); -#endif - } - } - } - } - - needlesPos += lH.redQrySeqs[i].size(); - } -} - -// -------------------------------------------------------------------------- -// Function _setFrames() -// -------------------------------------------------------------------------- - -template -inline void _setFrames(TBlastMatch & bm, typename TLocalHolder::TMatch const & m, TLocalHolder const &) -{ - if constexpr (seqan::qIsTranslated(TLocalHolder::TGlobalHolder::blastProgram)) - { - bm.qFrameShift = (m.qryId % 3) + 1; - if (m.qryId % 6 > 2) - bm.qFrameShift = -bm.qFrameShift; - } - else if constexpr (TLocalHolder::TGlobalHolder::c_redAlph == AlphabetEnum::DNA3BS) - { - bm.qFrameShift = (m.qryId % 2) + 1; - if (m.qryId % 4 > 1) - bm.qFrameShift = -bm.qFrameShift; - } - else if constexpr (seqan::qHasRevComp(TLocalHolder::TGlobalHolder::blastProgram)) - { - bm.qFrameShift = 1; - if (m.qryId % 2) - bm.qFrameShift = -bm.qFrameShift; - } - else - { - bm.qFrameShift = 0; - } - - if constexpr (seqan::sIsTranslated(TLocalHolder::TGlobalHolder::blastProgram)) - { - bm.sFrameShift = (m.subjId % 3) + 1; - if (m.subjId % 6 > 2) - bm.sFrameShift = -bm.sFrameShift; - } - else if constexpr (TLocalHolder::TGlobalHolder::c_redAlph == AlphabetEnum::DNA3BS) - { - bm.sFrameShift = (m.subjId % 2) + 1; - } - else if constexpr (seqan::sHasRevComp(TLocalHolder::TGlobalHolder::blastProgram)) - { - bm.sFrameShift = 1; - if (m.subjId % 2) - bm.sFrameShift = -bm.sFrameShift; - } - else - { - bm.sFrameShift = 0; - } -} - -// -------------------------------------------------------------------------- -// Function _writeMatches() -// -------------------------------------------------------------------------- - -template -inline void _writeRecord(TBlastRecord & record, TLocalHolder & lH) -{ - auto const & const_gH = lH.gH; - - if (record.matches.size() > 0) - { - ++lH.stats.qrysWithHit; - // sort and remove duplicates -> STL, yeah! - auto const before = record.matches.size(); - - // sort matches, using an inverted bitScore to have the highest score first - record.matches.sort( - [](auto const & m1, auto const & m2) - { - // bitscores explicitly switched so larger scores are sorted first - // clang-format off - return std::tie(m1._n_sId, - m1.qStart, - m1.qEnd, - m1.sStart, - m1.sEnd, - m1.qFrameShift, - m1.sFrameShift, - m2.bitScore) < - std::tie(m2._n_sId, - m2.qStart, - m2.qEnd, - m2.sStart, - m2.sEnd, - m2.qFrameShift, - m2.sFrameShift, - m1.bitScore); - // clang-format on - }); - - // removes duplicates and keeping the ones with the greatest score - record.matches.unique( - [](auto const & m1, auto const & m2) - { - return std::tie(m1._n_sId, m1.qStart, m1.qEnd, m1.sStart, m1.sEnd, m1.qFrameShift, m1.sFrameShift) == - std::tie(m2._n_sId, m2.qStart, m2.qEnd, m2.sStart, m2.sEnd, m2.qFrameShift, m2.sFrameShift); - }); - lH.stats.hitsDuplicate2 += before - record.matches.size(); - - // sort by evalue before writing - record.matches.sort([](auto const & m1, auto const & m2) { return m1.bitScore > m2.bitScore; }); - - // cutoff abundant - if (record.matches.size() > lH.options.maxMatches) - { - lH.stats.hitsAbundant += record.matches.size() - lH.options.maxMatches; - record.matches.resize(lH.options.maxMatches); - } - lH.stats.hitsFinal += record.matches.size(); - - /* count uniq qry-subj-pairs */ - lH.uniqSubjIds.clear(); - lH.uniqSubjIds.reserve(record.matches.size()); - for (auto const & bm : record.matches) - lH.uniqSubjIds.insert(bm._n_sId); - - lH.stats.pairs += lH.uniqSubjIds.size(); - - // compute LCA - if (lH.options.computeLCA) - { - record.lcaTaxId = 0; - for (auto const & bm : record.matches) - { - if ((lH.gH.indexFile.sTaxIds[bm._n_sId].size() > 0) && - (const_gH.indexFile.taxonParentIDs[lH.gH.indexFile.sTaxIds[bm._n_sId][0]] != 0)) - { - record.lcaTaxId = lH.gH.indexFile.sTaxIds[bm._n_sId][0]; - break; - } - } - - if (record.lcaTaxId != 0) - for (auto const & bm : record.matches) - for (uint32_t const sTaxId : lH.gH.indexFile.sTaxIds[bm._n_sId]) - // Unassigned subjects are simply ignored - if (const_gH.indexFile.taxonParentIDs[sTaxId] != 0) - record.lcaTaxId = computeLCA(const_gH.indexFile.taxonParentIDs, - const_gH.indexFile.taxonHeights, - sTaxId, - record.lcaTaxId); - - record.lcaId = const_gH.indexFile.taxonNames[record.lcaTaxId]; - } - - myWriteRecord(lH, record); - } -} - -// -------------------------------------------------------------------------- -// Function computeBlastMatch() -// -------------------------------------------------------------------------- - -template -inline void _widenMatch(Match & m, TLocalHolder const & lH) -{ - // move sStart as far left as needed to cover the part of query before qryStart - m.subjStart = (m.subjStart < m.qryStart) ? 0 : m.subjStart - m.qryStart; - - /* always align full query independent of hit-region */ - m.qryStart = 0; - m.qryEnd = lH.transQrySeqs[m.qryId].size(); - - // there is no band in computation but this value extends begin and end of Subj to account for gaps - uint64_t band = _bandSize(lH.transQrySeqs[m.qryId].size()); - - // end on subject is beginning plus full query length plus band - m.subjEnd = - std::min(m.subjStart + lH.transQrySeqs[m.qryId].size() + band, lH.gH.transSbjSeqs[m.subjId].size()); - - // account for band in subj start - m.subjStart = (band < m.subjStart) ? m.subjStart - band : 0; -} - -template -inline auto _untrueQryId(TBlastMatch const & bm, TLocalHolder const &) -{ - using namespace seqan; - - if constexpr (seqan::qIsTranslated(TLocalHolder::TGlobalHolder::blastProgram)) - { - if (bm.qFrameShift > 0) - return bm._n_qId * 6 + bm.qFrameShift - 1; - else - return bm._n_qId * 6 - bm.qFrameShift + 2; - } - else if constexpr (TLocalHolder::TGlobalHolder::c_redAlph == AlphabetEnum::DNA3BS) - { - if (bm.qFrameShift > 0) - return bm._n_qId * 4; - else - return bm._n_qId * 4 + 2; - } - else if constexpr (seqan::qHasRevComp(TLocalHolder::TGlobalHolder::blastProgram)) - { - if (bm.qFrameShift > 0) - return bm._n_qId * 2; - else - return bm._n_qId * 2 + 1; - } - else - { - return bm._n_qId; - } -} - -template -inline auto _untrueSubjId(TBlastMatch const & bm, TLocalHolder const &) -{ - using namespace seqan; - - if constexpr (seqan::sIsTranslated(TLocalHolder::TGlobalHolder::blastProgram)) - { - if (bm.sFrameShift > 0) - return bm._n_sId * 6 + bm.sFrameShift - 1; - else - return bm._n_sId * 6 - bm.sFrameShift + 2; - } - else if constexpr (seqan::sHasRevComp(TLocalHolder::TGlobalHolder::blastProgram) || - TLocalHolder::TGlobalHolder::c_redAlph == AlphabetEnum::DNA3BS) - { - if (bm.sFrameShift > 0) - return bm._n_sId * 2; - else - return bm._n_sId * 2 + 1; - } - else - { - return bm._n_sId; - } -} - -template -inline void _expandAlign(TBlastMatch & bm, TLocalHolder const & lH) -{ - using namespace seqan; - - auto oldQLen = seqan::length(source(bm.alignRow0)); - auto oldSLen = seqan::length(source(bm.alignRow1)); - - // replace source from underneath without triggering reset - bm.alignRow0._source = lH.transQrySeqs[_untrueQryId(bm, lH)] | - bio::views::slice(0, std::ranges::size(lH.transQrySeqs[_untrueQryId(bm, lH)])); - bm.alignRow1._source = lH.gH.transSbjSeqs[_untrueSubjId(bm, lH)] | - bio::views::slice(0, std::ranges::size(lH.gH.transSbjSeqs[_untrueSubjId(bm, lH)])); - - // insert fields into array gaps - if (bm.alignRow0._array[0] == 0) - bm.alignRow0._array[1] += bm.qStart; - else - insert(bm.alignRow0._array, 0, std::vector{0, bm.qStart}); - if (bm.alignRow0._array[seqan::length(bm.alignRow0._array) - 1] == 0) - bm.alignRow0._array[seqan::length(bm.alignRow0._array) - 2] += length(source(bm.alignRow0)) - oldQLen; - else - append(bm.alignRow0._array, std::vector{seqan::length(source(bm.alignRow0)) - oldQLen, 0}); - - if (bm.alignRow1._array[0] == 0) - bm.alignRow1._array[1] += bm.sStart; - else - insert(bm.alignRow1._array, 0, std::vector{0, bm.sStart}); - if (bm.alignRow1._array[length(bm.alignRow1._array) - 1] == 0) - bm.alignRow1._array[length(bm.alignRow1._array) - 2] += seqan::length(source(bm.alignRow1)) - oldSLen; - else - append(bm.alignRow1._array, std::vector{seqan::length(source(bm.alignRow1)) - oldSLen, 0}); - - // the begin positions from the align object are relative to the infix created above - bm.qEnd = bm.qStart + seqan::endPosition(bm.alignRow0); - bm.qStart = bm.qStart + seqan::beginPosition(bm.alignRow0); - bm.sEnd = bm.sStart + seqan::endPosition(bm.alignRow1); - bm.sStart = bm.sStart + seqan::beginPosition(bm.alignRow1); - - // set clipping positions on new gaps objects - seqan::setBeginPosition(bm.alignRow0, bm.qStart); - seqan::setEndPosition(bm.alignRow0, bm.qEnd); - seqan::setBeginPosition(bm.alignRow1, bm.sStart); - seqan::setEndPosition(bm.alignRow1, bm.sEnd); -} - -template -inline void _setupDepSets(TDepSetH & depSetH, TDepSetV & depSetV, TBlastMatches const & blastMatches) -{ - using TSimdAlign = typename seqan::SimdVector::Type; - constexpr unsigned sizeBatch = seqan::LENGTH::VALUE; - unsigned const fullSize = sizeBatch * ((seqan::length(blastMatches) + sizeBatch - 1) / sizeBatch); - - seqan::clear(depSetH); - seqan::clear(depSetV); - seqan::reserve(depSetH, fullSize); - seqan::reserve(depSetV, fullSize); - - for (auto const & bm : blastMatches) - { - seqan::appendValue(depSetH, seqan::source(bm.alignRow0)); - seqan::appendValue(depSetV, seqan::source(bm.alignRow1)); - } - - // fill up last batch - for (size_t i = seqan::length(blastMatches); i < fullSize; ++i) - { - seqan::appendValue(depSetH, seqan::source(seqan::back(blastMatches).alignRow0)); - seqan::appendValue(depSetV, seqan::source(seqan::back(blastMatches).alignRow1)); - } -} - -template -inline void _performAlignment(TDepSetH & depSetH, - TDepSetV & depSetV, - TBlastMatches & blastMatches, - TLocalHolder & lH, - std::integral_constant const &, - bsDirection const dir = bsDirection::fwd) -{ - using TGlobalHolder = typename TLocalHolder::TGlobalHolder; - using TAlignConfig = seqan::AlignConfig2< - seqan::LocalAlignment_<>, - seqan::DPBandConfig, - seqan::FreeEndGaps_, - std::conditional_t>, - seqan::TracebackOff>>; - - using TSimdAlign = typename seqan::SimdVector::Type; - using TSimdScore = seqan::Score>; - using TSize = typename seqan::Size::Type; - using TMatch = typename TGlobalHolder::TMatch; - using TPos = typename TMatch::TPos; - using TTraceSegment = seqan::TraceSegment_; - - constexpr unsigned sizeBatch = seqan::LENGTH::VALUE; - unsigned const fullSize = sizeBatch * ((seqan::length(blastMatches) + sizeBatch - 1) / sizeBatch); - - auto const & currentScoringScheme = - dir == bsDirection::fwd ? lH.gH.scoringSchemeAlign : lH.gH.scoringSchemeAlignBSRev; - TSimdScore simdScoringScheme(currentScoringScheme); - seqan::StringSet> trace; - - // Alignment is not banded, because SeqAn2 doesn't support it for SIMD-fied alignment - TAlignConfig config; //(0, 2*band) - - auto matchIt = blastMatches.begin(); - for (auto pos = 0u; pos < fullSize; pos += sizeBatch) - { - auto infSetH = infixWithLength(depSetH, pos, sizeBatch); - auto infSetV = infixWithLength(depSetV, pos, sizeBatch); - - TSimdAlign resultsBatch; - - seqan::clear(trace); - seqan::resize(trace, sizeBatch, seqan::Exact()); - - seqan::_prepareAndRunSimdAlignment(resultsBatch, - trace, - infSetH, - infSetV, - simdScoringScheme, - config, - typename TLocalHolder::TScoreExtension()); - - for (auto x = pos; x < pos + sizeBatch && x < seqan::length(blastMatches); ++x) - { - if constexpr (withTrace) - seqan::_adaptTraceSegmentsTo(matchIt->alignRow0, matchIt->alignRow1, trace[x - pos]); - else - matchIt->alignStats.alignmentScore = resultsBatch[x - pos]; - - ++matchIt; - } - } -} - -template -inline void _widenAndPreprocessMatches(std::span & matches, TLocalHolder & lH) -{ - auto before = matches.size(); - - for (Match & m : matches) - _widenMatch(m, lH); - - std::ranges::sort(matches); - - if (matches.size() > 1) - { - // pairwise merge from left to right - for (auto it = matches.begin(); it < matches.end() - 1; ++it) - { - Match & l = *it; - Match & r = *(it + 1); - if ((std::tie(l.qryId, l.subjId) == std::tie(r.qryId, r.subjId)) && (l.subjEnd >= r.subjStart)) - { - l.subjEnd = r.subjEnd; - r.subjStart = l.subjStart; - } - } - - // pairwise "swallow" from right to left - for (auto it = matches.rbegin(); it < matches.rend() - 1; ++it) - { - Match & r = *it; - Match & l = *(it + 1); - if ((std::tie(r.qryId, r.subjId) == std::tie(l.qryId, l.subjId)) && (r.subjStart < l.subjEnd)) - { - l = r; - } - } - - auto [new_end, old_end] = std::ranges::unique(matches); // move non-uniq to the end - matches = std::span{matches.begin(), new_end}; // "resize" of the span - lH.stats.hitsDuplicate += (before - matches.size()); - } -} - -template -inline void iterateMatchesFullSimd(std::span lambdaMatches, TLocalHolder & lH, bsDirection const dir) -{ - using TGlobalHolder = typename TLocalHolder::TGlobalHolder; - using TBlastMatch = typename TLocalHolder::TBlastMatch; - - auto const & const_gH = lH.gH; - - // statistics -#ifdef LAMBDA_MICRO_STATS - ++lH.stats.numQueryWithExt; - lH.stats.numExtScore += seqan::length(lambdaMatches); - - double start = sysTime(); -#endif - - // Prepare string sets with sequences. - seqan::StringSet::Type> depSetH; - seqan::StringSet::Type> depSetV; - - // pre-sort and filter - _widenAndPreprocessMatches(lambdaMatches, lH); - - // create blast matches from Lambda matches - std::list blastMatches; - for (Match const & m : lambdaMatches) - { - // create blastmatch in list without copy or move - blastMatches.emplace_back(lH.qryIds[m.qryId / TGlobalHolder::qryNumFrames], - const_gH.indexFile.ids[m.subjId / TGlobalHolder::sbjNumFrames]); - - TBlastMatch & bm = blastMatches.back(); - - bm._n_qId = m.qryId / TGlobalHolder::qryNumFrames; - bm._n_sId = m.subjId / TGlobalHolder::sbjNumFrames; - - bm.qLength = std::ranges::size(lH.qrySeqs[bm._n_qId]); - bm.sLength = std::ranges::size(lH.gH.indexFile.seqs[bm._n_sId]); - - bm.qStart = m.qryStart; - bm.qEnd = m.qryEnd; - bm.sStart = m.subjStart; - bm.sEnd = m.subjEnd; - seqan::assignSource(bm.alignRow0, lH.transQrySeqs[m.qryId] | bio::views::slice(bm.qStart, bm.qEnd)); - seqan::assignSource(bm.alignRow1, lH.gH.transSbjSeqs[m.subjId] | bio::views::slice(bm.sStart, bm.sEnd)); - - _setFrames(bm, m, lH); - - if (lH.options.hasSTaxIds) - bm.sTaxIds = lH.gH.indexFile.sTaxIds[bm._n_sId]; - } - - // sort by lengths to minimize padding in SIMD - blastMatches.sort( - [](auto const & l, auto const & r) - { - return std::make_tuple(seqan::length(seqan::source(l.alignRow0)), seqan::length(seqan::source(l.alignRow1))) < - std::make_tuple(seqan::length(seqan::source(r.alignRow0)), seqan::length(seqan::source(r.alignRow1))); - }); -#ifdef LAMBDA_MICRO_STATS - lH.stats.timeSort += sysTime() - start; - - start = sysTime(); -#endif - - // fill batches - _setupDepSets(depSetH, depSetV, blastMatches); - - // Run extensions WITHOUT ALIGNMENT - _performAlignment(depSetH, depSetV, blastMatches, lH, std::false_type(), dir); - - auto const & currentScoringScheme = - dir == bsDirection::fwd ? lH.gH.scoringSchemeAlign : lH.gH.scoringSchemeAlignBSRev; - - // copmute evalues and filter based on evalue - for (auto it = blastMatches.begin(), itEnd = blastMatches.end(); it != itEnd; /*below*/) - { - TBlastMatch & bm = *it; - - if (lH.options.minBitScore >= 0) - { - seqan::computeBitScore(bm, seqan::context(lH.gH.outfileBlastTab)); - - if (bm.bitScore < lH.options.minBitScore) - { - ++lH.stats.hitsFailedExtendBitScoreTest; - it = blastMatches.erase(it); - continue; - } - } - - if (lH.options.maxEValue >= 0) - { - computeEValueThreadSafe(bm, bm.qLength, seqan::context(lH.gH.outfileBlastTab)); - - if (bm.eValue > lH.options.maxEValue) - { - ++lH.stats.hitsFailedExtendEValueTest; - it = blastMatches.erase(it); - continue; - } - } - - ++it; - } - if (seqan::length(blastMatches) == 0) - return; - - // statistics -#ifdef LAMBDA_MICRO_STATS - lH.stats.numExtAli += seqan::length(blastMatches); - lH.stats.timeExtend += sysTime() - start; - start = sysTime(); -#endif - - // reset and fill batches - _setupDepSets(depSetH, depSetV, blastMatches); - - // Run extensions WITH ALIGNMENT - _performAlignment(depSetH, depSetV, blastMatches, lH, std::true_type(), dir); - - // sort by query - blastMatches.sort([](auto const & lhs, auto const & rhs) { return lhs._n_qId < rhs._n_qId; }); - - // compute the rest of the match properties - for (auto it = blastMatches.begin(), itEnd = blastMatches.end(); it != itEnd; /*below*/) - { - TBlastMatch & bm = *it; - - _expandAlign(bm, lH); - - seqan::computeAlignmentStats(bm.alignStats, bm.alignRow0, bm.alignRow1, currentScoringScheme); - - if (bm.alignStats.alignmentIdentity < lH.options.idCutOff) - { - ++lH.stats.hitsFailedExtendPercentIdentTest; - it = blastMatches.erase(it); - continue; - } - - // not computed previously - if (lH.options.minBitScore < 0) - seqan::computeBitScore(bm, seqan::context(lH.gH.outfileBlastTab)); - - if (lH.options.maxEValue < 0) - computeEValueThreadSafe(bm, bm.qLength, seqan::context(lH.gH.outfileBlastTab)); - - ++it; - } -#ifdef LAMBDA_MICRO_STATS - lH.stats.timeExtendTrace += sysTime() - start; -#endif - - // move the blastMatches into localHolder's cache - lH.blastMatches.splice(lH.blastMatches.end(), blastMatches); -} - -template -inline void writeRecords(TLocalHolder & lH) -{ - using TBlastRecord = typename TLocalHolder::TBlastRecord; - - // divide matches into records (per query) and write - for (auto it = lH.blastMatches.begin(), itLast = lH.blastMatches.begin(); seqan::length(lH.blastMatches) > 0; - /*below*/) - { - if ((it == lH.blastMatches.end()) || ((it != lH.blastMatches.begin()) && (it->_n_qId != itLast->_n_qId))) - { - // create a record for each query - TBlastRecord record(lH.qryIds[itLast->_n_qId]); - record.qLength = seqan::length(lH.qrySeqs[itLast->_n_qId]); - // move the matches into the record - record.matches.splice(record.matches.begin(), lH.blastMatches, lH.blastMatches.begin(), it); - // write to file - _writeRecord(record, lH); - - it = lH.blastMatches.begin(); - itLast = lH.blastMatches.begin(); - } - else - { - itLast = it; - ++it; - } - } -} - -template -inline void iterateMatches(TLocalHolder & lH) -{ - if constexpr (TLocalHolder::TGlobalHolder::c_redAlph == AlphabetEnum::DNA3BS) - { - std::ranges::sort(lH.matches, - [](Match const & l, Match const & r) { - return std::tuple{l.subjId % 2, l} < - std::tuple{r.subjId % 2, r}; - }); - - auto it = std::ranges::find_if(lH.matches, [](Match const & m) { return m.subjId % 2; }); - - iterateMatchesFullSimd(std::span{lH.matches.begin(), it}, lH, bsDirection::fwd); - iterateMatchesFullSimd(std::span{it, lH.matches.end()}, lH, bsDirection::rev); - lH.blastMatches.sort([](auto const & lhs, auto const & rhs) { return lhs._n_qId < rhs._n_qId; }); - } - else - { - iterateMatchesFullSimd(lH.matches, lH, bsDirection::fwd); - } -} - -//----------------------------------------------------------------------- -// iterativeSearch -//----------------------------------------------------------------------- - -void iterativeSearchPre(auto & lH) -{ - switch (lH.iterativeSearch) - { - case IterativeSearchMode::PHASE1: - lH.successfulQueries.clear(); - lH.successfulQueries.resize(lH.qryIds.size()); - for (auto const & bm : lH.blastMatches) - { - assert(bm._n_qId < lH.successfulQueries.size()); - lH.successfulQueries[bm._n_qId] = true; - } - break; - default: - break; - } -} - -void iterativeSearchPost(auto & lH) -{ - switch (lH.iterativeSearch) - { - case IterativeSearchMode::PHASE1: - { - /* remove those queries from set that are already successful */ - size_t successfulCount = - std::accumulate(lH.successfulQueries.begin(), lH.successfulQueries.end(), 0ull); - - if (successfulCount != lH.qryIds.size() && successfulCount != 0) - { - size_t index = 0; - [[maybe_unused]] auto subr1 = std::ranges::remove_if( - lH.qryIds, - [&](size_t pos) { return lH.successfulQueries[pos] == true; }, - [&](auto &&) { return index++; }); // converts element to index - assert(subr1.size() == successfulCount); - - index = 0; - [[maybe_unused]] auto subr2 = std::ranges::remove_if( - lH.qrySeqs, - [&](size_t pos) { return lH.successfulQueries[pos] == true; }, - [&](auto &&) { return index++; }); - assert(subr2.size() == successfulCount); - } - - lH.qryIds = lH.qryIds | std::views::take(lH.qryIds.size() - successfulCount); - lH.qrySeqs = lH.qrySeqs | std::views::take(lH.qrySeqs.size() - successfulCount); - - /* only switch to PHASE2 if there are any left */ - if (!lH.qryIds.empty()) - { - lH.iterativeSearch = IterativeSearchMode::PHASE2; - lH.searchOpts = lH.options.searchOpts; // default - lH.searchScheme = lH.searchScheme1; - - // clear some caches (since we will not reset all of the holder) - lH.matches.clear(); - lH.blastMatches.clear(); - } - break; - } - case IterativeSearchMode::PHASE2: - lH.iterativeSearch = IterativeSearchMode::PHASE1; - lH.searchOpts = lH.options.searchOpts0; // alternative scores - lH.searchScheme = lH.searchScheme0; - break; - default: - break; - } -} diff --git a/src/search_datastructures.hpp b/src/search_datastructures.hpp deleted file mode 100644 index 1d4499ee5..000000000 --- a/src/search_datastructures.hpp +++ /dev/null @@ -1,538 +0,0 @@ -// ========================================================================== -// lambda -// ========================================================================== -// Copyright (c) 2013-2024, Hannes Hauswedell

-// Copyright (c) 2016-2020, Knut Reinert and Freie Universität Berlin -// All rights reserved. -// -// This file is part of Lambda. -// -// Lambda is Free Software: you can redistribute it and/or modify it -// under the terms found in the LICENSE[.md|.rst] file distributed -// together with this file. -// -// Lambda 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. -// -// ========================================================================== -// search_datastructures.hpp: Data container structs -// ========================================================================== - -#pragma once - -#include -#include -#include - -#include -#include -#include -#include - -#include - -#include "bisulfite_scoring.hpp" -#include "search_options.hpp" - -// ============================================================================ -// Tags, Classes, Enums -// ============================================================================ - -// ---------------------------------------------------------------------------- -// struct Match -// ---------------------------------------------------------------------------- - -struct Match -{ - using TQId = uint64_t; - using TSId = uint64_t; - using TPos = uint64_t; - - TQId qryId; - TSId subjId; - TPos qryStart; - TPos qryEnd; - - TPos subjStart; - TPos subjEnd; - - constexpr friend auto operator<=>(Match const &, Match const &) = default; -}; - -// template -inline void setToSkip(Match & m) -{ - using TPos = typename Match::TPos; - constexpr TPos posMax = std::numeric_limits::max(); - m.qryStart = posMax; - m.subjStart = posMax; -} - -// template -inline bool isSetToSkip(Match const & m) -{ - using TPos = typename Match::TPos; - constexpr TPos posMax = std::numeric_limits::max(); - return (m.qryStart == posMax) && (m.subjStart == posMax); -} - -inline void _printMatch(Match const & m) -{ - std::cout << "MATCH Query " << m.qryId << "(" << m.qryStart << ", " << m.qryEnd << ") on Subject " << m.subjId - << "(" << m.subjStart << ", " << m.subjEnd << ")" << std::endl - << std::flush; -} - -// ---------------------------------------------------------------------------- -// struct StatsHolder -// ---------------------------------------------------------------------------- - -struct StatsHolder -{ - // seeding - uint64_t hitsAfterSeeding; - uint64_t hitsMerged; - uint64_t hitsTooShort; - uint64_t hitsMasked; -#ifdef LAMBDA_MICRO_STATS - std::vector seedLengths; -#endif - - // pre-extension - uint64_t hitsFailedPreExtendTest; - - // post-extension - uint64_t hitsFailedExtendPercentIdentTest; - uint64_t hitsFailedExtendBitScoreTest; - uint64_t hitsFailedExtendEValueTest; - uint64_t hitsAbundant; - uint64_t hitsDuplicate; - uint64_t hitsDuplicate2; - - // final - uint64_t hitsFinal; - uint64_t qrysWithHit; - uint64_t pairs; - -#ifdef LAMBDA_MICRO_STATS - // times - double timeGenSeeds; - double timeSearch; - double timeSort; - double timeExtend; - double timeExtendTrace; - - // extension counters - uint64_t numQueryWithExt; - uint64_t numExtScore; - uint64_t numExtAli; -#endif - - StatsHolder() - { - clear(); - } - - void clear() - { - hitsAfterSeeding = 0; - hitsMerged = 0; - hitsTooShort = 0; - hitsMasked = 0; - - hitsFailedPreExtendTest = 0; - - hitsFailedExtendPercentIdentTest = 0; - hitsFailedExtendBitScoreTest = 0; - hitsFailedExtendEValueTest = 0; - hitsAbundant = 0; - hitsDuplicate = 0; - hitsDuplicate2 = 0; - - hitsFinal = 0; - qrysWithHit = 0; - pairs = 0; - -#ifdef LAMBDA_MICRO_STATS - seedLengths.clear(); - timeGenSeeds = 0; - timeSearch = 0; - timeSort = 0; - timeExtend = 0; - timeExtendTrace = 0; - - numQueryWithExt = 0; - numExtScore = 0; - numExtAli = 0; -#endif - } - - StatsHolder plus(StatsHolder const & rhs) - { - hitsAfterSeeding += rhs.hitsAfterSeeding; - hitsMerged += rhs.hitsMerged; - hitsTooShort += rhs.hitsTooShort; - hitsMasked += rhs.hitsMasked; - - hitsFailedPreExtendTest += rhs.hitsFailedPreExtendTest; - - hitsFailedExtendPercentIdentTest += rhs.hitsFailedExtendPercentIdentTest; - hitsFailedExtendBitScoreTest += rhs.hitsFailedExtendBitScoreTest; - hitsFailedExtendEValueTest += rhs.hitsFailedExtendEValueTest; - hitsAbundant += rhs.hitsAbundant; - hitsDuplicate += rhs.hitsDuplicate; - hitsDuplicate2 += rhs.hitsDuplicate2; - - hitsFinal += rhs.hitsFinal; - qrysWithHit += rhs.qrysWithHit; - pairs += rhs.pairs; - -#ifdef LAMBDA_MICRO_STATS - seqan::append(seedLengths, rhs.seedLengths); - timeGenSeeds += rhs.timeGenSeeds; - timeSearch += rhs.timeSearch; - timeSort += rhs.timeSort; - timeExtend += rhs.timeExtend; - timeExtendTrace += rhs.timeExtendTrace; - - numQueryWithExt += rhs.numQueryWithExt; - numExtScore += rhs.numExtScore; - numExtAli += rhs.numExtAli; -#endif - return *this; - } - - StatsHolder operator+(StatsHolder const & rhs) - { - StatsHolder tmp(*this); - return tmp.plus(rhs); - } - - StatsHolder operator+=(StatsHolder const & rhs) - { - this->plus(rhs); - return *this; - } -}; - -void printStats(StatsHolder const & stats, LambdaOptions const & options) -{ - if (options.verbosity >= 2) - { - unsigned long rem = stats.hitsAfterSeeding; - auto const w = seqan::_numberOfDigits(rem); // number of digits -#define R " " << std::setw(w) -#define RR " = " << std::setw(w) -#define BLANKS \ - for (unsigned i = 0; i < w; ++i) \ - std::cout << " "; - std::cout << "\033[1m HITS "; - BLANKS; - std::cout << "Remaining\033[0m" - << "\n after Seeding "; - BLANKS; - std::cout << R << rem; - if (stats.hitsMasked) - std::cout << "\n - masked " << R << stats.hitsMasked << RR << (rem -= stats.hitsMasked); - if (options.preScoring) - std::cout << "\n - failed pre-extend test " << R << stats.hitsFailedPreExtendTest << RR - << (rem -= stats.hitsFailedPreExtendTest); - std::cout << "\n - failed e-value test " << R << stats.hitsFailedExtendEValueTest << RR - << (rem -= stats.hitsFailedExtendEValueTest); - std::cout << "\n - failed bitScore test " << R << stats.hitsFailedExtendBitScoreTest << RR - << (rem -= stats.hitsFailedExtendBitScoreTest); - std::cout << "\n - failed %-identity test " << R << stats.hitsFailedExtendPercentIdentTest << RR - << (rem -= stats.hitsFailedExtendPercentIdentTest); - std::cout << "\n - duplicates " << R << stats.hitsDuplicate << RR << (rem -= stats.hitsDuplicate); - std::cout << "\n - late duplicates " << R << stats.hitsDuplicate2 << RR - << (rem -= stats.hitsDuplicate2); - std::cout << "\n - abundant " << R << stats.hitsAbundant << "\033[1m" << RR - << (rem -= stats.hitsAbundant) << "\033[0m\n\n"; - - if (rem != stats.hitsFinal) - std::cout << "WARNING: hits don't add up\n"; - -#ifdef LAMBDA_MICRO_STATS - std::cout << "Detailed Non-Wall-Clock times:\n" - << " genSeeds: " << stats.timeGenSeeds << "\n" - << " search: " << stats.timeSearch << "\n" - << " sort: " << stats.timeSort << "\n" - << " extend: " << stats.timeExtend << "\n" - << " extendTrace: " << stats.timeExtendTrace << "\n\n"; - - if (seqan::length(stats.seedLengths)) - { - double _seedLengthSum = std::accumulate(stats.seedLengths.begin(), stats.seedLengths.end(), 0.0); - double seedLengthMean = _seedLengthSum / stats.seedLengths.size(); - - double _seedLengthMeanSqSum = - std::inner_product(stats.seedLengths.begin(), stats.seedLengths.end(), stats.seedLengths.begin(), 0.0); - double seedLengthStdDev = - std::sqrt(_seedLengthMeanSqSum / stats.seedLengths.size() - seedLengthMean * seedLengthMean); - uint16_t seedLengthMax = *std::max_element(stats.seedLengths.begin(), stats.seedLengths.end()); - - std::cout << "SeedStats:\n" - << " avgLength: " << seedLengthMean << "\n" - << " stddev: " << seedLengthStdDev << "\n" - << " max: " << seedLengthMax << "\n\n"; - } - if (stats.numQueryWithExt > 0) - std::cout << "Number of Extensions stats:\n" - << " # queries with Extensions: " << stats.numQueryWithExt << "\n" - << " avg # extensions without Ali: " << stats.numExtScore / stats.numQueryWithExt << "\n" - << " avg # extensions with Ali: " << stats.numExtAli / stats.numQueryWithExt << "\n\n"; -#endif - } - - if (options.verbosity >= 1) - { - auto const w = seqan::_numberOfDigits(stats.hitsFinal); - std::cout << "Number of total hits: " << std::setw(w) << stats.hitsFinal - << "\nNumber of Query-Subject pairs: " << std::setw(w) << stats.pairs - << "\nNumber of Queries with at least one valid hit: " << std::setw(w) << stats.qrysWithHit << "\n"; - } -} - -enum class IterativeSearchMode -{ - OFF, - PHASE1, - PHASE2 -}; - -// ---------------------------------------------------------------------------- -// struct GlobalDataHolder -- one object per program -// ---------------------------------------------------------------------------- - -template -class GlobalDataHolder -{ -public: - static constexpr DbIndexType c_dbIndexType = c_dbIndexType_; - static constexpr AlphabetEnum c_origSbjAlph = c_origSbjAlph_; - static constexpr AlphabetEnum c_transAlph = c_transAlph_; - static constexpr AlphabetEnum c_redAlph = c_redAlph_; - static constexpr AlphabetEnum c_origQryAlph = c_origQryAlph_; - - using TOrigQryAlph = _alphabetEnumToType; - using TOrigSbjAlph = _alphabetEnumToType; - using TTransAlph = _alphabetEnumToType; - using TRedAlph = _alphabetEnumToType; - using TMatch = Match; - - // clang-format off - static constexpr seqan::BlastProgram blastProgram = - (c_transAlph != AlphabetEnum::AMINO_ACID) ? seqan::BlastProgram::BLASTN : - (c_origQryAlph == AlphabetEnum::AMINO_ACID && c_origSbjAlph == c_origQryAlph) ? seqan::BlastProgram::BLASTP : - (c_origQryAlph == AlphabetEnum::AMINO_ACID && c_origSbjAlph != c_origQryAlph) ? seqan::BlastProgram::TBLASTN : - (c_origQryAlph != AlphabetEnum::AMINO_ACID && c_origSbjAlph == c_origQryAlph) ? seqan::BlastProgram::TBLASTX : - /*(c_origQryAlph != AlphabetEnum::AMINO_ACID && c_origSbjAlph != c_origQryAlph) ?*/ seqan::BlastProgram::BLASTX; - // clang-format on - - /* untranslated query sequences (ONLY USED FOR SAM/BAM OUTPUT) */ - using TQrySeqs = std::vector>; - using TSbjSeqs = TCDStringSet>; - - /* Translated sequence objects, either as modstrings or as references to original strings */ - using TTransQrySeqs = decltype(std::declval() | qryTransView); - using TTransSbjSeqs = decltype(std::declval() | sbjTransView); - - using TRedQrySeqs = decltype(std::declval() | redView); - using TRedSbjSeqs = decltype(std::declval() | redView); - - /* sequence ID strings */ - using TIds = TCDStringSet; - using TQryIds = std::vector; - using TSubjIds = TIds; - - /* index */ - using TIndexFile = index_file; - using TIndex = typename TIndexFile::TIndex; - using TIndexCursor = fmindex_collection::select_cursor_t; - - /* output file */ - // SeqAn2 scoring scheme for local alignment of extended seeds. This can be adapted for bisulfite scoring. - using TScoreSchemeAlign = - std::conditional_t, - std::conditional_t>, - seqan::Score>, - seqan::Score>>; - - // SeqAn2 scoring scheme for blast statistics (does not work with bisulfite scoring scheme) - using TScoreSchemeStats = - std::conditional_t, - seqan::Score, - seqan::Score>>; - - using TIOContext = seqan::BlastIOContext; - using TBlastTabFile = seqan::FormattedFile; - using TBlastRepFile = seqan::FormattedFile; - using TBamFile = seqan::FormattedFile; - - // Number of frames for subject and query sequences - // clang-format off - static constexpr uint8_t qryNumFrames = (c_redAlph == AlphabetEnum::DNA3BS) ? 4 : - seqan::qIsTranslated(blastProgram) ? 6 : - seqan::qHasRevComp(blastProgram) ? 2 : 1; - static constexpr uint8_t sbjNumFrames = (c_redAlph == AlphabetEnum::DNA3BS) ? 2 : - seqan::sIsTranslated(blastProgram) ? 6 : - seqan::sHasRevComp(blastProgram) ? 2 : 1; - // clang-format on - - /* misc types */ - using TPositions = std::vector; - - /* the actual members */ - TIndexFile indexFile; - - // origin sbjSeqs in indexFile - TTransSbjSeqs transSbjSeqs = indexFile.seqs | sbjTransView; - TRedSbjSeqs redSbjSeqs = transSbjSeqs | redView; - - /* the following are not used when the query is loaded on-demand / lazily */ - TQryIds qryIds; - TQrySeqs qrySeqs; - TTransQrySeqs transQrySeqs = qrySeqs | qryTransView; - TRedQrySeqs redQrySeqs = transQrySeqs | redView; - - TBlastTabFile outfileBlastTab; - TBlastRepFile outfileBlastRep; - TBamFile outfileBam; - - TScoreSchemeAlign scoringSchemeAlign; - TScoreSchemeAlign scoringSchemeAlignBSRev; - - StatsHolder stats{}; - - size_t queryTotal = 0; - std::atomic queryCount = 0; - size_t records_per_batch = -1; // this is always overwritten - - GlobalDataHolder() = default; - GlobalDataHolder(GlobalDataHolder const &) = delete; - GlobalDataHolder(GlobalDataHolder &&) = delete; - GlobalDataHolder & operator=(GlobalDataHolder const &) = delete; - GlobalDataHolder & operator=(GlobalDataHolder &&) = delete; -}; - -// ---------------------------------------------------------------------------- -// struct LocalDataHolder -- one object per thread -// ---------------------------------------------------------------------------- - -template -class LocalDataHolder -{ -public: - using TGlobalHolder = TGlobalHolder_; - using TMatch = typename TGlobalHolder::TMatch; - using TScoreExtension = seqan::AffineGaps; - using TSeqInfix0 = decltype(std::declval>() | - bio::views::slice(0, 1)); - using TSeqInfix1 = decltype(std::declval>() | - bio::views::slice(0, 1)); - - // references to global stuff - LambdaOptions const & options; - TGlobalHolder /*const*/ & gH; - static constexpr seqan::BlastProgram blastProgram = TGlobalHolder::blastProgram; - - // temporary storage used by lazy-loading - typename TGlobalHolder::TQryIds qryIdsTmp; - typename TGlobalHolder::TQrySeqs qrySeqsTmp; - // refers to temporary storage (lazy-loading) or subset of qry in globalHolder (eager-loading) - decltype(qryIdsTmp | bio::views::slice(0, 0)) qryIds; - decltype(qrySeqsTmp | bio::views::slice(0, 0)) qrySeqs; - typename TGlobalHolder::TTransQrySeqs transQrySeqs = - qrySeqs | qryTransView; - typename TGlobalHolder::TRedQrySeqs redQrySeqs = - transQrySeqs | redView; - size_t queryCount = 0; - std::vector successfulQueries; // vector -.- - - // regarding seeding - std::vector cursor_buffer; - std::vector> cursor_tmp_buffer; - std::vector> cursor_tmp_buffer2; - std::vector offset_modifier_buffer; - std::vector> matches_buffer; - std::vector matches; - // allows local override of options for iterative search - IterativeSearchMode iterativeSearch = IterativeSearchMode::OFF; - LambdaOptions::SearchOpts searchOpts; - - // regarding extension - using TAlignRow0 = seqan::Gaps; - using TAlignRow1 = seqan::Gaps; - using TBlastMatch = seqan::BlastMatch, // not used - std::span>; - using TBlastRecord = seqan::BlastRecord, // not used - std::string_view, - uint32_t>; - std::list blastMatches; - std::unordered_set uniqSubjIds; - - // regarding the gathering of stats - StatsHolder stats{}; - - // currently used search scheme - search_schemes::Scheme searchScheme0; // iterative phase 1 scheme - search_schemes::Scheme searchScheme1; // iterative phase 2 scheme - search_schemes::Scheme searchScheme; // the one currently in use - - LocalDataHolder() = delete; - LocalDataHolder(LocalDataHolder const &) = delete; - LocalDataHolder(LocalDataHolder &&) = delete; - LocalDataHolder & operator=(LocalDataHolder const &) = delete; - LocalDataHolder & operator=(LocalDataHolder &&) = delete; - - LocalDataHolder(LambdaOptions const & _options, TGlobalHolder & _gH) : - options{_options}, - gH{_gH}, - searchOpts{options.searchOpts}, - stats{}, - searchScheme0{search_schemes::expand(search_schemes::generator::pigeon_opt(0, options.searchOpts0.maxSeedDist), - options.searchOpts0.seedLength)}, - searchScheme1{search_schemes::expand(search_schemes::generator::pigeon_opt(0, options.searchOpts.maxSeedDist), - options.searchOpts.seedLength)}, - searchScheme{searchScheme1} - { - if (_options.iterativeSearch) - { - iterativeSearch = IterativeSearchMode::PHASE1; - searchOpts = options.searchOpts0; - searchScheme = searchScheme0; - } - } - - void reset() - { - // clear storage - queryCount = 0; - matches.clear(); - qryIdsTmp.clear(); - qrySeqsTmp.clear(); - blastMatches.clear(); - - // stats explicitly not cleared, because accumulated - } - - void resetViews() - { - transQrySeqs = - qrySeqs | qryTransView; - redQrySeqs = transQrySeqs | redView; - } -}; diff --git a/src/search_misc.hpp b/src/search_misc.hpp deleted file mode 100644 index 805c8be2c..000000000 --- a/src/search_misc.hpp +++ /dev/null @@ -1,112 +0,0 @@ -// ========================================================================== -// lambda -// ========================================================================== -// Copyright (c) 2013-2024, Hannes Hauswedell

-// Copyright (c) 2016-2020, Knut Reinert and Freie Universität Berlin -// All rights reserved. -// -// This file is part of Lambda. -// -// Lambda is Free Software: you can redistribute it and/or modify it -// under the terms found in the LICENSE[.md|.rst] file distributed -// together with this file. -// -// Lambda 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. -// -// ========================================================================== -// search_misc.h: misc stuff for search -// ========================================================================== - -#pragma once - -#include - -#include - -// ============================================================================ -// Exceptions -// ============================================================================ - -struct IndexException : public std::runtime_error -{ - using std::runtime_error::runtime_error; -}; - -struct QueryException : public std::runtime_error -{ - using std::runtime_error::runtime_error; -}; - -// ============================================================================ -// Alignment-related -// ============================================================================ - -inline int64_t _bandSize(uint64_t const seqLength) -{ - // Currently only used for padding of the subject sequences - return static_cast(std::sqrt(seqLength)) + 1; -} - -// ---------------------------------------------------------------------------- -// Function computeEValueThreadSafe -// ---------------------------------------------------------------------------- - -template -inline double computeEValueThreadSafe(TBlastMatch & match, uint64_t ql, seqan::BlastIOContext & context) -{ -#if defined(__FreeBSD__) - // && version < 11 && defined(STDLIB_LLVM) because of https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=192320 - // || version >= 11 && defined(STDLIB_GNU) because of https://bugs.freebsd.org/bugzilla/show_bug.cgi?id=215709 - static std::vector> _cachedLengthAdjustmentsArray(omp_get_num_threads()); - std::unordered_map & _cachedLengthAdjustments = - _cachedLengthAdjustmentsArray[omp_get_thread_num()]; -#else - static thread_local std::unordered_map _cachedLengthAdjustments; -#endif - - // convert to 64bit and divide for translated sequences - ql = ql / (seqan::qIsTranslated(context.blastProgram) ? 3 : 1); - // length adjustment not yet computed - if (_cachedLengthAdjustments.find(ql) == _cachedLengthAdjustments.end()) - _cachedLengthAdjustments[ql] = _lengthAdjustment(context.dbTotalLength, ql, context.scoringScheme); - - uint64_t adj = _cachedLengthAdjustments[ql]; - - match.eValue = - _computeEValue(match.alignStats.alignmentScore, ql - adj, context.dbTotalLength - adj, context.scoringScheme); - return match.eValue; -} - -// ---------------------------------------------------------------------------- -// compute LCA -// ---------------------------------------------------------------------------- - -template -T computeLCA(std::vector const & taxParents, std::vector const & taxHeights, T n1, T n2) -{ - if (n1 == n2) - return n1; - - // move up so that nodes are on same height - for (auto i = taxHeights[n1]; i > taxHeights[n2]; --i) - n1 = taxParents[n1]; - - for (auto i = taxHeights[n2]; i > taxHeights[n1]; --i) - n2 = taxParents[n2]; - - while ((n1 != 0) && (n2 != 0)) - { - // common ancestor - if (n1 == n2) - return n1; - - // move up in parallel - n1 = taxParents[n1]; - n2 = taxParents[n2]; - } - - throw std::runtime_error{"LCA-computation error: One of the paths didn't lead to root."}; - return 0; // avoid warnings on clang -} diff --git a/src/search_options.hpp b/src/search_options.hpp deleted file mode 100644 index dc347e64e..000000000 --- a/src/search_options.hpp +++ /dev/null @@ -1,910 +0,0 @@ -// ========================================================================== -// lambda -// ========================================================================== -// Copyright (c) 2013-2024, Hannes Hauswedell

-// Copyright (c) 2016-2020, Knut Reinert and Freie Universität Berlin -// All rights reserved. -// -// This file is part of Lambda. -// -// Lambda is Free Software: you can redistribute it and/or modify it -// under the terms found in the LICENSE[.md|.rst] file distributed -// together with this file. -// -// Lambda 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. -// -// ========================================================================== -// search_options.h: contains the options and argument parser for the search -// ========================================================================== - -#pragma once - -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include - -#include "search_output.hpp" - -// ========================================================================== -// Forwards -// ========================================================================== - -// template -// struct SamBamExtraTags; - -// ========================================================================== -// Classes -// ========================================================================== - -// -------------------------------------------------------------------------- -// Class LambdaOptions -// -------------------------------------------------------------------------- - -struct LambdaOptions : public SharedOptions -{ - std::string queryFile; - - AlphabetEnum qryOrigAlphabet; - bool revComp = true; - - int32_t outFileFormat; // -1 = BLAST-Report, 0 = BLAST-Tabular, 1 = SAM, 2 = BAM - bool blastTabularWithComments = false; - std::string output = "output.m8"; - std::vector::Enum> columns; - std::string outputBam; - std::bitset<64> samBamTags; - bool samWithRefHeader = false; - unsigned samBamSeq; - bool samBamHardClip; - bool versionInformationToOutputFile = true; - size_t maximumQueryBlockSize = 10; // possibly increase this - - bool lazyQryFile = false; - - bool seedHalfExact = true; - bool adaptiveSeeding = true; - - struct SearchOpts - { - size_t seedLength = 0; - size_t maxSeedDist = 1; - size_t seedOffset = 0; - }; - - SearchOpts searchOpts0; - SearchOpts searchOpts; - - // 0 = manual, positive X = blosumX, negative Y = pamY - int32_t scoringMethod = 62; - // scores - int32_t gapOpen = -11; - int32_t gapExtend = -1; - int32_t match = 2; // only for manual - int32_t misMatch = -3; // only for manual - - int32_t minBitScore = -1; - double maxEValue = 1e-2; - int32_t idCutOff = 0; - uint64_t maxMatches = 25; - - bool computeLCA = false; - bio::alphabet::genetic_code geneticCodeQry; - - int32_t preScoring = 2; // 0 = off, 1 = seed, 2 = region - double preScoringThresh = 2.0; - - bool iterativeSearch = true; - std::string profile = "none"; -}; - -void parseCommandLine(LambdaOptions & options, int argc, char const ** argv) -{ - // save commandLine - for (int i = 0; i < argc; ++i) - options.commandLine += std::string(argv[i]) + " "; - seqan::eraseBack(options.commandLine); - - std::string const subcommand = std::string(argv[0]); - std::string const programName = "lambda3-" + subcommand; - - // this is important for option handling: - if (subcommand == "searchp") - options.domain = domain_t::protein; - else if (subcommand == "searchn") - options.domain = domain_t::nucleotide; - else if (subcommand == "searchbs") - options.domain = domain_t::bisulfite; - else - throw std::runtime_error{"Unknown subcommand."}; - - std::string const mkdindex_subcommand = "mkindex"s + subcommand.substr(6); - - sharg::parser parser(programName, argc, argv, sharg::update_notifications::off); - - // Set short description, version, and date. - parser.info.short_description = "the Local Aligner for Massive Biological DatA"; - - // Define usage line and long description. - parser.info.synopsis.push_back( - "lambda3 "s + subcommand + - " [\\fIOPTIONS\\fP] \\fI-q QUERY.fasta\\fP \\fI-i INDEX.lambda\\fP [\\fI-o output.m8\\fP]"); - - sharedSetup(parser); - - parser.add_option(options.verbosity, - sharg::config{ - .short_id = 'v', - .long_id = "verbosity", - .description = "Display more/less diagnostic output during operation: " - "0 [only errors]; 1 [default]; 2 [+run-time, options and statistics].", - - .validator = sharg::arithmetic_range_validator{0, 2} - }); - - parser.add_section("Input options"); - - std::vector extensions{"fa", "fq", "fasta", "fastq", "fna", "faa"}; -#ifdef SEQAN_HAS_ZLIB - for (auto const & ext : extensions) - extensions.push_back(ext + ".gz"); -#endif - parser.add_option(options.queryFile, - sharg::config{.short_id = 'q', - .long_id = "query", - .description = "Query sequences.", - .required = true, - .validator = sharg::input_file_validator{extensions}}); - - std::string inputAlphabetTmp = "auto"; - int32_t geneticCodeTmp = 1; - - if (options.domain == domain_t::protein) - { - parser.add_option(inputAlphabetTmp, - sharg::config{ - .short_id = 'a', - .long_id = "input-alphabet", - .description = "Alphabet of the query sequences (specify to override auto-detection). " - "Dna sequences will be translated.", - .advanced = true, - .validator = sharg::value_list_validator{"auto", "dna5", "aminoacid"} - }); - } - else - { - options.qryOrigAlphabet = AlphabetEnum::DNA5; - } - - parser.add_option(options.lazyQryFile, - sharg::config{.long_id = "lazy-query", - .description = "Load query sequences on-demand (instead of at start); " - "reduces memory usage but \"wastes\" one thread on I/O.", - .advanced = true}); - - extensions = {"lba", "lta"}; -#ifdef SEQAN_HAS_ZLIB - for (auto const & ext : extensions) - extensions.push_back(ext + ".gz"); -#endif - parser.add_option(options.indexFilePath, - sharg::config{.short_id = 'i', - .long_id = "index", - .description = std::string{"The database index (created by the 'lambda "} + - mkdindex_subcommand + "' command).", - .required = true, - .validator = sharg::input_file_validator{extensions}}); - - parser.add_section("Output options"); - - extensions = {"m0", "m8", "m9", "bam", "sam"}; -#ifdef SEQAN_HAS_ZLIB - for (auto const & ext : extensions) - extensions.push_back(ext + ".gz"); -#endif - parser.add_option( - options.output, - sharg::config{ - .short_id = 'o', - .long_id = "output", - .description = "File to hold reports on hits (.m* are blastall -m* formats; .m8 is tab-seperated " - ".m9 is tab-seperated with with comments, .m0 is pairwise format).", - .validator = sharg::output_file_validator{sharg::output_file_open_options::create_new, extensions} - }); - - std::string outputColumnsTmp = "std"; - parser.add_option( - outputColumnsTmp, - sharg::config{.short_id = '\0', - .long_id = "output-columns", - .description = "Print specified column combination and/or order (.m8 and .m9 outputs only); call " - "-oc help for more details.", - .advanced = true}); - - parser.add_option(options.idCutOff, - sharg::config{ - .short_id = '\0', - .long_id = "percent-identity", - .description = "Output only matches above this threshold (checked before e-value check).", - - .validator = sharg::arithmetic_range_validator{0, 100} - }); - - parser.add_option(options.minBitScore, - sharg::config{ - .short_id = '\0', - .long_id = "bit-score", - .description = "Output only matches that score >= this threshold (-1 means no check).", - - .validator = sharg::arithmetic_range_validator{-1, 1000} - }); - - parser.add_option(options.maxEValue, - sharg::config{ - .short_id = 'e', - .long_id = "e-value", - .description = "Output only matches that score below this threshold (-1 means no check).", - - .validator = sharg::arithmetic_range_validator{-1, 100} - }); - - if (options.domain == domain_t::bisulfite) - { - options.maxEValue = 1e-9; - } - - int32_t numMatchesTmp = 25; - parser.add_option(numMatchesTmp, - sharg::config{ - .short_id = 'n', - .long_id = "num-matches", - .description = "Print at most this number of matches per query.", - - .validator = sharg::arithmetic_range_validator{0, 10000} - }); - - parser.add_option( - options.samWithRefHeader, - sharg::config{.short_id = '\0', - .long_id = "sam-with-refheader", - .description = "BAM files require all subject names to be written to the header. For SAM this is " - "not required, so Lambda " - "does " - "not automatically do it to save space (especially for protein database this is a " - "lot!). If you still want " - "them with SAM, e.g. for better BAM compatibility, use this option.", - .advanced = true}); - - std::string samBamSeqDescr; - - if (options.domain != domain_t::protein) - { - samBamSeqDescr = "Write matching DNA subsequence into SAM/BAM file."; - options.gapOpen = -5; - options.gapExtend = -2; - } - else - { - samBamSeqDescr = - "For BLASTX and TBLASTX the matching protein " - "sequence is \"untranslated\" and positions retransformed to the original sequence. For BLASTP and " - "TBLASTN " - "there is no DNA sequence so a \"*\" is written to the SEQ column. The matching protein sequence " - "can be " - "written as an optional tag, see --sam-bam-tags."; - options.gapOpen = -11; - options.gapExtend = -1; - } - - switch (options.domain) - { - case domain_t::protein: - options.searchOpts0.seedLength = 10; - options.searchOpts0.seedOffset = 5; - options.searchOpts0.maxSeedDist = 0; - options.searchOpts.seedLength = 11; - options.searchOpts.seedOffset = 3; - options.searchOpts.maxSeedDist = 1; - break; - case domain_t::nucleotide: - options.searchOpts0.seedLength = 14; - options.searchOpts0.seedOffset = 9; - options.searchOpts0.maxSeedDist = 0; - options.searchOpts.seedLength = 14; - options.searchOpts.seedOffset = 7; - options.searchOpts.maxSeedDist = 1; - options.preScoringThresh = 1.4; - break; - case domain_t::bisulfite: - options.searchOpts0.seedLength = 17; - options.searchOpts0.seedOffset = 10; - options.searchOpts0.maxSeedDist = 0; - options.searchOpts.seedLength = 17; - options.searchOpts.seedOffset = 10; - options.searchOpts.maxSeedDist = 1; - options.preScoringThresh = 1.5; - break; - } - - std::string samBamSeqDescrTmp = "uniq"; - parser.add_option(samBamSeqDescrTmp, - sharg::config{ - .short_id = '\0', - .long_id = "sam-bam-seq", - .description = samBamSeqDescr + - " If set to uniq than the sequence is " - "omitted iff it is identical to the previous match's subsequence.", - .advanced = true, - .validator = sharg::value_list_validator{"always", "uniq", "never"} - }); - - std::string samBamTagsTmp = "AS NM ae ai qf"; - parser.add_option( - samBamTagsTmp, - sharg::config{.short_id = '\0', - .long_id = "sam-bam-tags", - .description = "Write the specified optional columns to the SAM/BAM file. Call --sam-bam-tags help " - "for more details.", - .advanced = true}); - - std::string samBamClip = "hard"; - parser.add_option(samBamClip, - sharg::config{ - .short_id = '\0', - .long_id = "sam-bam-clip", - .description = "Whether to hard-clip or soft-clip the regions beyond the local match. " - "Soft-clipping retains the full sequence " - "in the output file, but obviously uses more space.", - .advanced = true, - .validator = sharg::value_list_validator{"hard", "soft"} - }); - - parser.add_option( - options.versionInformationToOutputFile, - sharg::config{.short_id = '\0', - .long_id = "version-to-outputfile", - .description = "Write the Lambda program tag and version number to the output file.", - .hidden = true}); - - parser.add_section("General Options"); -#ifdef _OPENMP - parser.add_option(options.threads, - sharg::config{ - .short_id = 't', - .long_id = "threads", - .description = "Number of threads to run concurrently.", - .advanced = true, - .validator = sharg::arithmetic_range_validator{1, 1000} - }); -#else - parser.add_option(options.threads, - sharg::config{ - .short_id = 't', - .long_id = "threads", - .description = "LAMBDA BUILT WITHOUT OPENMP; setting this option has no effect.", - .advanced = true, - .validator = sharg::arithmetic_range_validator{1, 1} - }); -#endif - - parser.add_option( - options.profile, - sharg::config{ - .short_id = 'p', - .long_id = "profile", - .description = "Profiles are presets of a group of parameters. See below.", - .validator = sharg::value_list_validator{"none", "fast", "sensitive", "pairs-default", "pairs-sensitive"} - }); - - parser.add_section("Seeding / Filtration"); - - parser.add_option(options.adaptiveSeeding, - sharg::config{.short_id = '\0', - .long_id = "adaptive-seeding", - .description = "Grow the seed if it has too many hits (low complexity filter).", - .advanced = true}); - - parser.add_option(options.seedHalfExact, - sharg::config{.short_id = '\0', - .long_id = "seed-half-exact", - .description = "Allow errors only in second half of seed.", - .advanced = true}); - - parser.add_option(options.searchOpts.seedLength, - sharg::config{ - .short_id = '\0', - .long_id = "seed-length", - .description = "Length of the seeds.", - .advanced = true, - .validator = sharg::arithmetic_range_validator{3, 50} - }); - - parser.add_option(options.searchOpts.seedOffset, - sharg::config{ - .short_id = '\0', - .long_id = "seed-offset", - .description = "Offset for seeding. " - "Distance between seed begin positions.", - - .validator = sharg::arithmetic_range_validator{1, 50} - }); - - parser.add_option(options.searchOpts.maxSeedDist, - sharg::config{ - .short_id = '\0', - .long_id = "seed-delta", - .description = "Maximum seed distance.", - .advanced = true, - .validator = sharg::arithmetic_range_validator{0, 3} - }); - - /* iterative search parameters */ - parser.add_option(options.iterativeSearch, - sharg::config{.short_id = '\0', - .long_id = "search0", - .description = "If (cheaper) pre-search yield results, skip regular search.", - .advanced = true}); - - parser.add_option(options.searchOpts0.seedLength, - sharg::config{ - .short_id = '\0', - .long_id = "seed-length0", - .description = "Length of the seeds.", - .advanced = true, - .validator = sharg::arithmetic_range_validator{3, 50} - }); - - parser.add_option(options.searchOpts0.seedOffset, - sharg::config{ - .short_id = '\0', - .long_id = "seed-offset0", - .description = "Offset for seeding. " - "Distance between seed begin positions.", - - .validator = sharg::arithmetic_range_validator{1, 50} - }); - - parser.add_option(options.searchOpts0.maxSeedDist, - sharg::config{ - .short_id = '\0', - .long_id = "seed-delta0", - .description = "Maximum seed distance.", - .advanced = true, - .validator = sharg::arithmetic_range_validator{0, 5} - }); - - parser.add_section("Miscellaneous Heuristics"); - - parser.add_option(options.preScoring, - sharg::config{ - .short_id = '\0', - .long_id = "pre-scoring", - .description = "Evaluate score of a region NUM times the size of the seed " - "before extension (0 -> no pre-scoring, 1 -> evaluate seed, n-> area " - "around seed, as well; default = 1 if no reduction is used).", - .advanced = true, - .validator = sharg::arithmetic_range_validator{1, 10} - }); - - parser.add_option(options.preScoringThresh, - sharg::config{ - .short_id = '\0', - .long_id = "pre-scoring-threshold", - .description = "Minimum average score per position in pre-scoring region.", - .advanced = true, - .validator = sharg::arithmetic_range_validator{0, 20} - }); - - parser.add_section("Scoring"); - - if (options.domain == domain_t::protein) - { - parser.add_option(options.scoringMethod, - sharg::config{ - .short_id = 's', - .long_id = "scoring-scheme", - .description = "Use '45' for Blosum45; '62' for Blosum62 (default); '80' for Blosum80.", - .advanced = true, - .validator = sharg::value_list_validator{45, 62, 80} - }); - } - else - { - parser.add_option(options.match, - sharg::config{ - .short_id = '\0', - .long_id = "score-match", - .description = "Match score", - .advanced = true, - .validator = sharg::arithmetic_range_validator{-1000, 1000} - }); - - parser.add_option(options.misMatch, - sharg::config{ - .short_id = '\0', - .long_id = "score-mismatch", - .description = "Mismatch score", - .advanced = true, - .validator = sharg::arithmetic_range_validator{-1000, 1000} - }); - } - - parser.add_option(options.gapExtend, - sharg::config{ - .short_id = '\0', - .long_id = "score-gap", - .description = "Score per gap character.", - .advanced = true, - .validator = sharg::arithmetic_range_validator{-1000, 1000} - }); - - parser.add_option(options.gapOpen, - sharg::config{ - .short_id = '\0', - .long_id = "score-gap-open", - .description = "Additional cost for opening gap.", - .advanced = true, - .validator = sharg::arithmetic_range_validator{-1000, 1000} - }); - - parser.add_section("Profiles"); - parser.add_line( - "Setting a profile other than \"none\" always overwrites manually given command line " - "arguments!", - true); - - switch (options.domain) - { - case domain_t::protein: - parser.add_line("\"fast\"", false); - parser.add_line("--seed-length0 12 --seed-offset0 8 --seed-length 10 --seed-offset 5 --seed-delta 0", true); - parser.add_line("\"sensitive\"", false); - parser.add_line( - "--seed-length0 9 --seed-offset0 4 --seed-length 8 --seed-offset 3 --pre-scoring 3 " - "--pre-scoring-threshold 1.9", - true); - parser.add_line("\"pairs-default\"", false); - parser.add_line("--search0 OFF --seed-length 8 --seed-offset 3 --pre-scoring 3 --pre-scoring-threshold 1.9", - true); - parser.add_line("\"pairs-sensitive\"", false); - parser.add_line("--search0 OFF --seed-length 7 --seed-offset 3 --pre-scoring 3 --pre-scoring-threshold 1.9", - true); - break; - case domain_t::nucleotide: - parser.add_line("\"fast\"", false); - parser.add_line("--search0 OFF --seed-length 14 --seed-offset 9 --seed-delta 0", true); - parser.add_line("\"sensitive\"", false); - parser.add_line("--seed-length0 14 --seed-offset0 3 --seed-length 14 --seed-offset 3", true); - parser.add_line("\"pairs-default\"", false); - parser.add_line("--search0 OFF --seed-length 14 --seed-offset 3", true); - parser.add_line("\"pairs-sensitive\"", false); - parser.add_line("--search0 OFF --seed-length 13 --seed-offset 3", true); - break; - case domain_t::bisulfite: - parser.add_line("\"fast\"", false); - parser.add_line("--search0 OFF --seed-length 17 --seed-offset 10 --seed-delta 0", true); - parser.add_line("\"sensitive\"", false); - parser.add_line("--seed-length0 16 --seed-offset0 8 --seed-length 15 --seed-offset 10", true); - parser.add_line("\"pairs-default\"", false); - parser.add_line("--search0 OFF --seed-length 15 --seed-offset 10", true); - parser.add_line("\"pairs-sensitive\"", false); - parser.add_line("--search0 OFF --seed-length 14 --seed-offset 10", true); - break; - } - - parser.add_line( - "The \"pairs\" profiles are for use in combination with higher --num-matches. " - "They are based on the sensitive profile but in addition to increasing the number of query-" - "sequences-with-one-or-more-hits, they also increase the number of qry-subj-pairs, i.e. the " - "number of hits per query.", - false); - parser.add_line("For further information see the wiki: ", false); - - // parse command line. - parser.parse(); - - // set query alphabet and genetic code depending on options - if (options.domain == domain_t::protein) - { - if (inputAlphabetTmp == "auto") - options.qryOrigAlphabet = AlphabetEnum::DNA4; - else if (inputAlphabetTmp == "dna5") - options.qryOrigAlphabet = AlphabetEnum::DNA5; - else if (inputAlphabetTmp == "aminoacid") - options.qryOrigAlphabet = AlphabetEnum::AMINO_ACID; - else - throw sharg::parser_error("ERROR: Invalid argument to --input-alphabet\n"); - - options.geneticCodeQry = static_cast(geneticCodeTmp); - } - - if (options.profile == "fast") - { - if (options.domain != domain_t::protein) - { - options.iterativeSearch = false; - options.searchOpts.maxSeedDist = 0; - - if (options.domain == domain_t::nucleotide) - { - options.searchOpts.seedOffset = 9; - } - } - else - { - options.searchOpts0.seedLength = 12; - options.searchOpts0.seedOffset = 8; - options.searchOpts.seedLength = 10; - options.searchOpts.seedOffset = 5; - options.searchOpts.maxSeedDist = 0; - } - } - else if ((options.profile == "sensitive") || options.profile.starts_with("pairs")) - { - switch (options.domain) - { - case domain_t::protein: - options.searchOpts0.seedLength = 9; - options.searchOpts0.seedOffset = 4; - options.searchOpts.seedLength = 8; - options.searchOpts.seedOffset = 3; - - options.preScoring = 3; - options.preScoringThresh = 1.9; - break; - case domain_t::nucleotide: - options.searchOpts0.seedOffset = 3; - options.searchOpts.seedOffset = 3; - break; - case domain_t::bisulfite: - options.searchOpts0.seedLength = 16; - options.searchOpts0.seedOffset = 8; - options.searchOpts.seedLength = 15; - options.searchOpts.seedOffset = 10; - break; - } - - if (options.profile.starts_with("pairs")) - options.iterativeSearch = false; - - if (options.profile == "pairs-sensitive") - --options.searchOpts.seedLength; - } - - // set output file format - std::string outputPath = options.output; - if (std::filesystem::path(outputPath).extension() == ".gz") - outputPath.resize(seqan::length(outputPath) - 3); - else if (std::filesystem::path(outputPath).extension() == ".bz2") - outputPath.resize(seqan::length(outputPath) - 4); - - if (std::filesystem::path(outputPath).extension() == ".sam") - options.outFileFormat = 1; - else if (std::filesystem::path(outputPath).extension() == ".bam") - options.outFileFormat = 2; - else if (std::filesystem::path(outputPath).extension() == ".m0") - options.outFileFormat = -1; - else if (std::filesystem::path(outputPath).extension() == ".m8") - { - options.outFileFormat = 0; - options.blastTabularWithComments = false; - } - else if (std::filesystem::path(outputPath).extension() == ".m9") - { - options.outFileFormat = 0; - options.blastTabularWithComments = true; - } - else - { - throw 99; - } - - // help page for output columns - if (outputColumnsTmp == "help") - { - std::cout << "Please specify the columns in this format -oc 'column1 column2', i.e. " - "space-separated " - "and " - << "enclosed in single quotes.\nThe specifiers are the same as in NCBI Blast, currently " - << "the following are supported:\n"; - for (unsigned i = 0; i < seqan::length(seqan::BlastMatchField<>::implemented); ++i) - { - if (seqan::BlastMatchField<>::implemented[i]) - { - std::cout << "\t" << seqan::BlastMatchField<>::optionLabels[i] - << (seqan::length(seqan::BlastMatchField<>::optionLabels[i]) >= 8 ? "\t" : "\t\t") - << seqan::BlastMatchField<>::descriptions[i] << "\n"; - } - } - std::exit(0); - } - else - { - seqan::StringSet fields; - seqan::strSplit(fields, outputColumnsTmp, seqan::IsSpace(), false); - for (auto str : fields) - { - bool resolved = false; - for (unsigned i = 0; i < seqan::length(seqan::BlastMatchField<>::optionLabels); ++i) - { - if (seqan::BlastMatchField<>::optionLabels[i] == str) - { - seqan::appendValue(options.columns, static_cast::Enum>(i)); - resolved = true; - if (static_cast::Enum>(i) == seqan::BlastMatchField<>::Enum::S_TAX_IDS) - options.hasSTaxIds = true; - else if ((static_cast::Enum>(i) == - seqan::BlastMatchField<>::Enum::LCA_ID) || - (static_cast::Enum>(i) == - seqan::BlastMatchField<>::Enum::LCA_TAX_ID)) - options.computeLCA = true; - break; - } - } - if (!resolved) - { - throw sharg::parser_error(std::string("Unknown column specifier \"") + toCString(str) + - std::string("\". Please see -oc help for valid options.\n")); - } - } - } - - // set max matches - options.maxMatches = static_cast(numMatchesTmp); - - // set SamBamSeq - if (samBamSeqDescrTmp == "never") - options.samBamSeq = 0; - else if (samBamSeqDescrTmp == "uniq") - options.samBamSeq = 1; - else - options.samBamSeq = 2; - - // help page for SAM/BAM tags - if (samBamTagsTmp == "help") - { - std::cout << "Please specify the tags in this format -oc 'tag1 tag2', i.e. space-separated and " - << "enclosed in quotes. The order of tags is not preserved.\nThe following specifiers " - "are " - << "supported:\n"; - - for (auto const & c : SamBamExtraTags<>::keyDescPairs) - std::cout << "\t" << std::get<0>(c) << "\t" << std::get<1>(c) << "\n"; - - std::exit(0); - } - else - { - seqan::StringSet fields; - seqan::strSplit(fields, samBamTagsTmp, seqan::IsSpace(), false); - for (auto str : fields) - { - bool resolved = false; - for (unsigned i = 0; i < seqan::length(SamBamExtraTags<>::keyDescPairs); ++i) - { - if (std::get<0>(SamBamExtraTags<>::keyDescPairs[i]) == str) - { - options.samBamTags[i] = true; - resolved = true; - break; - } - } - if (!resolved) - { - std::cerr << "Unknown column specifier \"" << str - << "\". Please see \"--sam-bam-tags help\" for valid options.\n"; - throw sharg::parser_error(std::string("Unknown column specifier \"") + seqan::toCString(str) + - std::string("\". Please see \"--sam-bam-tags help\" for valid options.\n")); - } - } - } - - if (options.samBamTags[SamBamExtraTags<>::S_TAX_IDS]) - options.hasSTaxIds = true; - - if (options.samBamTags[SamBamExtraTags<>::LCA_ID] || options.samBamTags[SamBamExtraTags<>::LCA_TAX_ID]) - options.computeLCA = true; - - // lca computation requires tax ids - if (options.computeLCA) - options.hasSTaxIds = true; - - // set samBamHardClip - options.samBamHardClip = (samBamClip == "hard"); - - if (options.threads == 1ull && options.lazyQryFile) - throw sharg::parser_error{"Lazy query loading requires at least two total threads."}; -} - -// -------------------------------------------------------------------------- -// Function printOptions() -// -------------------------------------------------------------------------- - -template -inline void printOptions(LambdaOptions const & options) -{ - std::cout << "OPTIONS\n" - << " INPUT\n" - << " query file: " << options.queryFile << "\n" - << " index file: " << options.indexFilePath << "\n" - << " OUTPUT (file)\n" - << " output file: " << options.output << "\n" - << " maximum e-value: " << options.maxEValue << "\n" - << " minimum bit-score: " << options.minBitScore << "\n" - << " minimum % identity: " << options.idCutOff << "\n" - << " max #matches per query: " << options.maxMatches << "\n" - << " include subj names in sam:" << options.samWithRefHeader << "\n" - << " include seq in sam/bam: " << options.samBamSeq << "\n" - << " with subject tax ids: " << options.hasSTaxIds << '\n' - << " compute LCA: " << options.computeLCA << '\n' - << " OUTPUT (stdout)\n" - << " stdout is terminal: " << options.isTerm << "\n" - << " terminal width: " << options.terminalCols << "\n" - << " verbosity: " << options.verbosity << "\n" - << " GENERAL\n" - << " threads: " << uint(options.threads) << "\n" - << " TRANSLATION AND ALPHABETS\n" - << " domain: " << domain2string(options.domain) << "\n" - << " genetic code: " << (int)options.geneticCodeQry << "\n" - << " original alphabet (query):" << _alphabetEnumToName(options.qryOrigAlphabet) << "\n" - << " SEEDING\n" - << " seed length: " << options.searchOpts.seedLength << "\n" - << " seed offset: " << options.searchOpts.seedOffset << "\n" - << " seed delta: " << options.searchOpts.maxSeedDist << "\n" - << " adaptive seeding: " << (options.adaptiveSeeding ? std::string("on") : std::string("off")) - << "\n" - << " pre-search: " << (options.iterativeSearch ? std::string("on") : std::string("off")) - << "\n" - << " seed length0: " << options.searchOpts0.seedLength << "\n" - << " seed offset0: " << options.searchOpts0.seedOffset << "\n" - << " seed delta0: " << options.searchOpts0.maxSeedDist << "\n" - << " MISCELLANEOUS HEURISTICS\n" - << " pre-scoring: " << (options.preScoring ? std::string("on") : std::string("off")) << "\n" - << " pre-scoring-region: " - << (options.preScoring ? std::to_string(options.preScoring * options.searchOpts.seedLength) - : std::string("n/a")) - << "\n" - << " pre-scoring-threshold: " - << (options.preScoring ? std::to_string(options.preScoringThresh) : std::string("n/a")) << "\n" - << " SCORING\n" - << " scoring scheme: " << options.scoringMethod << "\n" - << " score-match: " - << (options.scoringMethod ? std::string("n/a") : std::to_string(options.match)) << "\n" - << " score-mismatch: " - << (options.scoringMethod ? std::string("n/a") : std::to_string(options.misMatch)) << "\n" - << " score-gap: " << options.gapExtend << "\n" - << " score-gap-open: " << options.gapOpen << "\n" - << " BUILD OPTIONS:\n" - << " cmake_build_type: " << std::string(CMAKE_BUILD_TYPE) << "\n" - << " native_build: " -#if defined(LAMBDA_NATIVE_BUILD) - << "on\n" -#else - << "off\n" -#endif - << " static_build: " -#if defined(LAMBDA_STATIC_BUILD) - << "on\n" -#else - << "off\n" -#endif - << " seqan_simd: " -#if defined(__AVX2__) - << "avx2\n" -#elif defined(__SSE4_2__) - << "sse4\n" -#else - << "off\n" -#endif - << "\n"; -} diff --git a/src/search_output.hpp b/src/search_output.hpp deleted file mode 100644 index adcc7478c..000000000 --- a/src/search_output.hpp +++ /dev/null @@ -1,750 +0,0 @@ -// ========================================================================== -// lambda -// ========================================================================== -// Copyright (c) 2013-2024, Hannes Hauswedell

-// Copyright (c) 2016-2020, Knut Reinert and Freie Universität Berlin -// All rights reserved. -// -// This file is part of Lambda. -// -// Lambda is Free Software: you can redistribute it and/or modify it -// under the terms found in the LICENSE[.md|.rst] file distributed -// together with this file. -// -// Lambda 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. -// -// ========================================================================== -// search_output.hpp: contains routines for file-writing -// ========================================================================== - -#pragma once - -#include -#include -#include -#include - -template -struct SamBamExtraTags -{ - enum Enum - { - // Q_START, - // S_START, - BIT_SCORE, - Q_AA_CIGAR, - EDIT_DISTANCE, - MATCH_COUNT, - SCORE, - E_VALUE, - P_IDENT, - P_POS, - Q_FRAME, - Q_AA_SEQ, - S_FRAME, - S_TAX_IDS, - LCA_ID, - LCA_TAX_ID - }; - - // clang-format off - static constexpr const std::array, 14> keyDescPairs - { - { -// { "ZS", "query start (in DNA if original was DNA)" }, // Q_START, -// { "YS", "subject start (in DNA if original was DNA)" }, // S_START, - { "AS", "bit score" }, // BIT_SCORE, - { "OC", "query protein cigar (* for BLASTN)"}, // Q_AA_CIGAR, - { "NM", "edit distance (in protein space unless BLASTN)"}, // EDIT_DISTANCE - { "IH", "number of matches this query has"}, // MATCH_COUNT - { "ar", "raw score" }, // SCORE, - { "ae", "expect value" }, // E_VALUE, - { "ai", "% identity (in protein space unless BLASTN) " }, // P_IDENT, - { "ap", "% positive (in protein space unless BLASTN)"}, // P_POS, - { "qf", "query frame" }, // Q_FRAME, - { "qs", "query protein sequence (* for BLASTN)"}, // Q_AA_SEQ, - { "sf", "subject frame" }, // S_FRAME, - { "st", "subject taxonomy IDs (* if n/a)" }, // S_TAX_IDS, - { "ls", "lowest common ancestor scientific name" }, // LCA_ID, - { "lt", "lowest common ancestor taxonomy ID" }, // LCA_TAX_ID, - } - }; - // clang-format on -}; - -template -constexpr const std::array, 14> SamBamExtraTags::keyDescPairs; - -// ---------------------------------------------------------------------------- -// Function _untranslatedClipPositions() -// ---------------------------------------------------------------------------- - -// similar to _untranslatePositions() from the blast module -template -inline void _untranslateSequence(TSequence1 & target, - TSequence2 const & source, - TNum const qStart, - TNum const qEnd, - int const qFrameShift) -{ - if (qFrameShift >= 0) - { - seqan::copy_range( - source | bio::views::slice(3 * qStart + std::abs(qFrameShift) - 1, 3 * qEnd + std::abs(qFrameShift) - 1) | - bio::views::to_char, - target); - } - else - { - seqan::copy_range(source | - bio::views::slice(seqan::length(source) - (3 * qEnd + std::abs(qFrameShift) - 1), - seqan::length(source) - (3 * qStart + std::abs(qFrameShift) - 1)) | - bio::views::to_char, - target); - - reverseComplement(target); - } -} - -// ---------------------------------------------------------------------------- -// Function blastMatchToCigar() convert seqan align to cigar -// ---------------------------------------------------------------------------- - -template -inline void blastMatchOneCigar(TCigar & cigar, TBlastMatch const & m, TBlastRecord const & r, TLocalHolder const & lH) -{ - using TCElem = typename seqan::Value::Type; - using TGlobalHolder = typename TLocalHolder::TGlobalHolder; - - SEQAN_ASSERT_EQ(seqan::length(m.alignRow0), seqan::length(m.alignRow1)); - - // translate positions into dna space - unsigned const transFac = qIsTranslated(TGlobalHolder::blastProgram) ? 3 : 1; - // clips resulting from translation / frameshift are always hard clips - unsigned const leftFrameClip = std::abs(m.qFrameShift) - 1; - unsigned const rightFrameClip = qIsTranslated(TGlobalHolder::blastProgram) ? (r.qLength - leftFrameClip) % 3 : 0; - - // regular clipping from local alignment (regions outside match) can be hard or soft - unsigned const leftClip = m.qStart * transFac; - unsigned const rightClip = (seqan::length(seqan::source(m.alignRow0)) - m.qEnd) * transFac; - - if (lH.options.samBamHardClip) - { - if (leftFrameClip + leftClip > 0) - seqan::appendValue(cigar, TCElem('H', leftFrameClip + leftClip)); - } - else - { - if (leftFrameClip > 0) - seqan::appendValue(cigar, TCElem('H', leftFrameClip)); - if (leftClip > 0) - seqan::appendValue(cigar, TCElem('S', leftClip)); - } - - for (unsigned i = 0, count = 0; i < seqan::length(m.alignRow0); /* incremented below */) - { - // deletion in query - count = 0; - while (seqan::isGap(m.alignRow0, i) && (i < seqan::length(m.alignRow0))) - { - ++count; - ++i; - } - if (count > 0) - seqan::appendValue(cigar, TCElem('D', count * transFac)); - - // insertion in query - count = 0; - while (seqan::isGap(m.alignRow1, i) && (i < seqan::length(m.alignRow0))) - { - ++count; - ++i; - } - if (count > 0) - seqan::appendValue(cigar, TCElem('I', count * transFac)); - - // match or mismatch - count = 0; - while ((!seqan::isGap(m.alignRow0, i)) && (!seqan::isGap(m.alignRow1, i)) && (i < seqan::length(m.alignRow0))) - { - ++count; - ++i; - } - if (count > 0) - seqan::appendValue(cigar, TCElem('M', count * transFac)); - } - - if (lH.options.samBamHardClip) - { - if (rightFrameClip + rightClip > 0) - seqan::appendValue(cigar, TCElem('H', rightFrameClip + rightClip)); - } - else - { - if (rightClip > 0) - seqan::appendValue(cigar, TCElem('S', rightClip)); - if (rightFrameClip > 0) - seqan::appendValue(cigar, TCElem('H', rightFrameClip)); - } - - if (m.qFrameShift < 0) - reverse(cigar); -} - -// translation happened and we want both cigars -template -inline void blastMatchTwoCigar(TCigar & dnaCigar, - TCigar & protCigar, - TBlastMatch const & m, - TBlastRecord const & r, - TLocalHolder const & lH) -{ - using TCElem = typename seqan::Value::Type; - - SEQAN_ASSERT_EQ(seqan::length(m.alignRow0), seqan::length(m.alignRow1)); - - // clips resulting from translation / frameshift are always hard clips - unsigned const leftFrameClip = std::abs(m.qFrameShift) - 1; // in dna space - unsigned const rightFrameClip = (r.qLength - leftFrameClip) % 3; // in dna space - // regular clipping from local alignment (regions outside match) can be hard or soft - unsigned const leftClip = m.qStart; // in protein space - unsigned const rightClip = seqan::length(seqan::source(m.alignRow0)) - m.qEnd; // in protein space - - if (lH.options.samBamHardClip) - { - if (leftFrameClip + leftClip > 0) - seqan::appendValue(dnaCigar, TCElem('H', leftFrameClip + 3 * leftClip)); - if (leftClip > 0) - seqan::appendValue(protCigar, TCElem('H', leftClip)); - } - else - { - if (leftFrameClip > 0) - seqan::appendValue(dnaCigar, TCElem('H', leftFrameClip)); - - if (leftClip > 0) - { - seqan::appendValue(dnaCigar, TCElem('S', 3 * leftClip)); - seqan::appendValue(protCigar, TCElem('S', leftClip)); - } - } - - for (unsigned i = 0, count = 0; i < seqan::length(m.alignRow0); /* incremented below */) - { - // deletion in query - count = 0; - while (seqan::isGap(m.alignRow0, i) && (i < seqan::length(m.alignRow0))) - { - ++count; - ++i; - } - if (count > 0) - { - seqan::appendValue(dnaCigar, TCElem('D', count * 3)); - seqan::appendValue(protCigar, TCElem('D', count)); - } - - // insertion in query - count = 0; - while (seqan::isGap(m.alignRow1, i) && (i < seqan::length(m.alignRow0))) - { - ++count; - ++i; - } - if (count > 0) - { - seqan::appendValue(dnaCigar, TCElem('I', count * 3)); - seqan::appendValue(protCigar, TCElem('I', count)); - } - - // match or mismatch - count = 0; - while ((!seqan::isGap(m.alignRow0, i)) && (!seqan::isGap(m.alignRow1, i)) && (i < seqan::length(m.alignRow0))) - { - ++count; - ++i; - } - if (count > 0) - { - seqan::appendValue(dnaCigar, TCElem('M', count * 3)); - seqan::appendValue(protCigar, TCElem('M', count)); - } - } - - if (lH.options.samBamHardClip) - { - if (rightFrameClip + rightClip > 0) - seqan::appendValue(dnaCigar, TCElem('H', rightFrameClip + 3 * rightClip)); - if (rightClip > 0) - seqan::appendValue(protCigar, TCElem('H', rightClip)); - } - else - { - if (rightClip > 0) - { - seqan::appendValue(dnaCigar, TCElem('S', 3 * rightClip)); - seqan::appendValue(protCigar, TCElem('S', rightClip)); - } - - if (rightFrameClip > 0) - seqan::appendValue(dnaCigar, TCElem('H', rightFrameClip)); - } - - if (m.qFrameShift < 0) - seqan::reverse(dnaCigar); - // protCigar never reversed -} - -// ---------------------------------------------------------------------------- -// Function myWriteHeader() -// ---------------------------------------------------------------------------- - -template -inline void myWriteHeader(TGH & globalHolder, TLambdaOptions const & options) -{ - if (options.outFileFormat <= 0) // Blast - { - std::string versionString; - seqan::append(versionString, _programTagToString(TGH::blastProgram)); - seqan::append(versionString, " 2.2.26+ [created by LAMBDA"); - if (options.versionInformationToOutputFile) - { - seqan::append(versionString, "-"); - seqan::append(versionString, SEQAN_APP_VERSION); - } - seqan::append(versionString, ", see http://seqan.de/lambda and please cite correctly in your academic work]"); - - if (options.outFileFormat == -1) // BLAST-rep - { - // copy details from tabular file - seqan::context(globalHolder.outfileBlastRep) = seqan::context(globalHolder.outfileBlastTab); - - if (options.versionInformationToOutputFile) - seqan::context(globalHolder.outfileBlastRep).versionString += versionString; - - seqan::open(globalHolder.outfileBlastRep, options.output.c_str()); - seqan::context(globalHolder.outfileBlastRep).fields = options.columns; - seqan::writeHeader(globalHolder.outfileBlastRep); - } - else // BLAST-tab - { - if (options.blastTabularWithComments) - seqan::context(globalHolder.outfileBlastTab).tabularSpec = seqan::BlastTabularSpec::COMMENTS; - else - seqan::context(globalHolder.outfileBlastTab).tabularSpec = seqan::BlastTabularSpec::NO_COMMENTS; - - if (options.versionInformationToOutputFile) - seqan::context(globalHolder.outfileBlastTab).versionString += versionString; - - seqan::open(globalHolder.outfileBlastTab, options.output.c_str()); - seqan::context(globalHolder.outfileBlastTab).fields = options.columns; - seqan::writeHeader(globalHolder.outfileBlastTab); - } - } - else // SAM or BAM - { - seqan::open(globalHolder.outfileBam, options.output.c_str()); - auto & context = seqan::context(globalHolder.outfileBam); - auto & subjSeqLengths = seqan::contigLengths(context); - auto & subjIds = seqan::contigNames(context); - - // compute seqan::lengths ultra-fast - seqan::resize(subjSeqLengths, globalHolder.indexFile.seqs.size()); - SEQAN_OMP_PRAGMA(parallel for simd) - for (size_t i = 0; i < globalHolder.indexFile.seqs.size(); ++i) - subjSeqLengths[i] = globalHolder.indexFile.seqs[i].size(); - - // set namestore - resize(subjIds, globalHolder.indexFile.ids.size()); - SEQAN_OMP_PRAGMA(parallel for) - for (unsigned i = 0; i < globalHolder.indexFile.ids.size(); ++i) - { - if (auto it = std::ranges::find(globalHolder.indexFile.ids[i], ' '), - e = globalHolder.indexFile.ids[i].end(); - it == e) - { - subjIds[i] = globalHolder.indexFile.ids[i]; - } - else - { - resize(subjIds[i], e - it); - std::ranges::copy(globalHolder.indexFile.ids[i].begin(), e, begin(subjIds[i])); - } - } - - typedef seqan::BamHeaderRecord::TTag TTag; - - // CREATE HEADER - seqan::BamHeader header; - // Fill first header line. - seqan::BamHeaderRecord firstRecord; - firstRecord.type = seqan::BAM_HEADER_FIRST; - seqan::appendValue(firstRecord.tags, TTag("VN", "1.4")); - // seqan::appendValue(firstRecord.tags, TTag("SO", "unsorted")); - seqan::appendValue(firstRecord.tags, TTag("GO", "query")); - seqan::appendValue(header, firstRecord); - - // Fill program header line. - if (options.versionInformationToOutputFile) - { - seqan::BamHeaderRecord pgRecord; - pgRecord.type = seqan::BAM_HEADER_PROGRAM; - seqan::appendValue(pgRecord.tags, TTag("ID", "lambda")); - seqan::appendValue(pgRecord.tags, TTag("PN", "lambda")); - seqan::appendValue(pgRecord.tags, TTag("VN", SEQAN_APP_VERSION)); - seqan::appendValue(pgRecord.tags, TTag("CL", options.commandLine)); - seqan::appendValue(header, pgRecord); - } - - // Fill homepage header line. - seqan::BamHeaderRecord hpRecord0; - hpRecord0.type = seqan::BAM_HEADER_COMMENT; - seqan::appendValue(hpRecord0.tags, - TTag("CO", - "Lambda is a high performance BLAST compatible local aligner, " - "please see http://seqan.de/lambda for more information.")); - seqan::appendValue(header, hpRecord0); - seqan::BamHeaderRecord hpRecord1; - hpRecord1.type = seqan::BAM_HEADER_COMMENT; - seqan::appendValue(hpRecord1.tags, - TTag("CO", - "SAM/BAM dialect documentation is available here: " - "https://github.com/seqan/lambda/wiki/Output-Formats")); - seqan::appendValue(header, hpRecord1); - seqan::BamHeaderRecord hpRecord2; - hpRecord2.type = seqan::BAM_HEADER_COMMENT; - seqan::appendValue(hpRecord2.tags, - TTag("CO", - "If you use any results found by Lambda, please cite " - "Hauswedell et al. (2014) doi: 10.1093/bioinformatics/btu439")); - seqan::appendValue(header, hpRecord2); - - // Fill extra tags header line. - seqan::BamHeaderRecord tagRecord; - tagRecord.type = seqan::BAM_HEADER_COMMENT; - std::string columnHeaders = "Optional tags as follow"; - for (unsigned i = 0; i < seqan::length(SamBamExtraTags<>::keyDescPairs); ++i) - { - if (options.samBamTags[i]) - { - columnHeaders += '\t'; - columnHeaders += std::get<0>(SamBamExtraTags<>::keyDescPairs[i]); - columnHeaders += ':'; - columnHeaders += std::get<1>(SamBamExtraTags<>::keyDescPairs[i]); - } - } - seqan::appendValue(tagRecord.tags, TTag("CO", columnHeaders)); - seqan::appendValue(header, tagRecord); - - // sam and we don't want the headers - if (!options.samWithRefHeader && (options.outFileFormat == 1)) - { - // we only write the header records that we actually created ourselves - for (unsigned i = 0; i < seqan::length(header); ++i) - seqan::write(globalHolder.outfileBam.iter, - header[i], - seqan::context(globalHolder.outfileBam), - seqan::Sam()); - } - else - { - // ref header records are automatically added with default writeHeader() - seqan::writeHeader(globalHolder.outfileBam, header); - } - } -} - -// ---------------------------------------------------------------------------- -// Function myWriteRecord() -// ---------------------------------------------------------------------------- - -template -inline void myWriteRecord(TLH & lH, TRecord const & record) -{ - using TGH = typename TLH::TGlobalHolder; - if (lH.options.outFileFormat == 0) // BLAST-Tab - { - SEQAN_OMP_PRAGMA(critical(filewrite)) - { - seqan::writeRecord(lH.gH.outfileBlastTab, record); - } - } - else if (lH.options.outFileFormat == -1) // BLAST - { - SEQAN_OMP_PRAGMA(critical(filewrite)) - { - seqan::writeRecord(lH.gH.outfileBlastRep, record); - } - } - else // SAM or BAM - { - // convert multi-match blast-record to multiple SAM/BAM-Records - std::vector bamRecords; - bamRecords.resize(record.matches.size()); - - seqan::String> protCigar; - std::string protCigarString = "*"; - - auto mIt = seqan::begin(record.matches, seqan::Standard()); - for (auto & bamR : bamRecords) - { - // untranslate for sIsTranslated - if constexpr (seqan::sIsTranslated(TGH::blastProgram)) - { - bamR.beginPos = mIt->sStart * 3 + std::abs(mIt->sFrameShift) - 1; - if (mIt->sFrameShift < 0) - bamR.beginPos = record.qLength - bamR.beginPos; - } - else - { - bamR.beginPos = mIt->sStart; - } - - bamR.flag = seqan::BAM_FLAG_SECONDARY; // all are secondary for now - if (mIt->qFrameShift < 0) - bamR.flag |= seqan::BAM_FLAG_RC; - // truncated query name+ - for (char c : record.qId | std::views::take_while(!bio::io::is_space)) - seqan::appendValue(bamR.qName, c); - // reference ID - bamR.rID = mIt->_n_sId; - - // compute cigar - if (lH.options.samBamTags[SamBamExtraTags<>::Q_AA_CIGAR]) // amino acid cigar, too? - { - seqan::clear(protCigar); - // native protein - if constexpr ((TGH::blastProgram == seqan::BlastProgram::BLASTP) || - (TGH::blastProgram == seqan::BlastProgram::TBLASTN)) - blastMatchOneCigar(protCigar, *mIt, record, lH); - else if constexpr (qIsTranslated(TGH::blastProgram)) // translated - blastMatchTwoCigar(bamR.cigar, protCigar, *mIt, record, lH); - else // BLASTN can't have protein sequence - blastMatchOneCigar(bamR.cigar, *mIt, record, lH); - } - else - { - if constexpr ((TGH::blastProgram != seqan::BlastProgram::BLASTP) && - (TGH::blastProgram != seqan::BlastProgram::TBLASTN)) - blastMatchOneCigar(bamR.cigar, *mIt, record, lH); - } - // we want to include the seq - bool writeSeq = false; - if (lH.options.samBamSeq > 1) - { - writeSeq = true; - } - else if (lH.options.samBamSeq == 1) // only uniq sequences - { - if (mIt == begin(record.matches, seqan::Standard())) - { - writeSeq = true; - } - else - { - decltype(mIt) mPrevIt = mIt - 1; - writeSeq = ((mIt->qFrameShift != mPrevIt->qFrameShift) || - (seqan::beginPosition(mIt->alignRow0) != seqan::beginPosition(mPrevIt->alignRow0)) || - (seqan::endPosition(mIt->alignRow0) != seqan::endPosition(mPrevIt->alignRow0))); - } - } - - if constexpr (TGH::blastProgram == seqan::BlastProgram::BLASTN) - { - if (lH.options.samBamHardClip) - { - if (writeSeq) - { - seqan::copy_range(seqan::source(mIt->alignRow0) | - bio::views::slice(seqan::beginPosition(mIt->alignRow0), - seqan::endPosition(mIt->alignRow0)) | - std::views::transform([](bio::alphabet::dna5 a) - { return seqan::Iupac{bio::alphabet::to_char(a)}; }), - bamR.seq); - } - } - else - { - if (writeSeq) - { - seqan::copy_range(seqan::source(mIt->alignRow0) | - std::views::transform([](bio::alphabet::dna5 a) - { return seqan::Iupac{bio::alphabet::to_char(a)}; }), - bamR.seq); - } - } - } - else if constexpr (qIsTranslated(TGH::blastProgram)) - { - if (lH.options.samBamHardClip) - { - if (writeSeq) - _untranslateSequence(bamR.seq, - lH.qrySeqs[mIt->_n_qId], - mIt->qStart, - mIt->qEnd, - mIt->qFrameShift); - } - else - { - if (writeSeq) - _untranslateSequence(bamR.seq, - lH.qrySeqs[mIt->_n_qId], - decltype(seqan::length(seqan::source(mIt->alignRow0)))(0u), - seqan::length(seqan::source(mIt->alignRow0)), - mIt->qFrameShift); - } - } // else original query is protein and cannot be printed - - // custom tags - if (lH.options.samBamTags[SamBamExtraTags<>::E_VALUE]) - seqan::appendTagValue(bamR.tags, - std::get<0>(SamBamExtraTags<>::keyDescPairs[SamBamExtraTags<>::E_VALUE]), - float(mIt->eValue), - 'f'); - if (lH.options.samBamTags[SamBamExtraTags<>::BIT_SCORE]) - seqan::appendTagValue(bamR.tags, - std::get<0>(SamBamExtraTags<>::keyDescPairs[SamBamExtraTags<>::BIT_SCORE]), - uint16_t(mIt->bitScore), - 'S'); - if (lH.options.samBamTags[SamBamExtraTags<>::SCORE]) - seqan::appendTagValue(bamR.tags, - std::get<0>(SamBamExtraTags<>::keyDescPairs[SamBamExtraTags<>::SCORE]), - uint8_t(mIt->alignStats.alignmentScore), - 'C'); - if (lH.options.samBamTags[SamBamExtraTags<>::P_IDENT]) - seqan::appendTagValue(bamR.tags, - std::get<0>(SamBamExtraTags<>::keyDescPairs[SamBamExtraTags<>::P_IDENT]), - uint8_t(mIt->alignStats.alignmentIdentity), - 'C'); - if (lH.options.samBamTags[SamBamExtraTags<>::P_POS]) - seqan::appendTagValue(bamR.tags, - std::get<0>(SamBamExtraTags<>::keyDescPairs[SamBamExtraTags<>::P_POS]), - uint16_t(mIt->alignStats.alignmentSimilarity), - 'S'); - if (lH.options.samBamTags[SamBamExtraTags<>::Q_FRAME]) - seqan::appendTagValue(bamR.tags, - std::get<0>(SamBamExtraTags<>::keyDescPairs[SamBamExtraTags<>::Q_FRAME]), - int8_t(mIt->qFrameShift), - 'c'); - if (lH.options.samBamTags[SamBamExtraTags<>::S_FRAME]) - seqan::appendTagValue(bamR.tags, - std::get<0>(SamBamExtraTags<>::keyDescPairs[SamBamExtraTags<>::S_FRAME]), - int8_t(mIt->sFrameShift), - 'c'); - if (lH.options.samBamTags[SamBamExtraTags<>::S_TAX_IDS]) - { - seqan::CharString buf; - auto it = begin(buf); - if (seqan::length(mIt->sTaxIds) == 0) - { - buf = "*"; - } - else - { - seqan::appendNumber(it, mIt->sTaxIds[0]); - for (unsigned i = 1; i < seqan::length(mIt->sTaxIds); ++i) - { - write(it, ";"); - seqan::appendNumber(it, mIt->sTaxIds[i]); - } - } - seqan::appendTagValue(bamR.tags, - std::get<0>(SamBamExtraTags<>::keyDescPairs[SamBamExtraTags<>::S_TAX_IDS]), - buf, - 'Z'); - } - if (lH.options.samBamTags[SamBamExtraTags<>::LCA_ID]) - seqan::appendTagValue(bamR.tags, - std::get<0>(SamBamExtraTags<>::keyDescPairs[SamBamExtraTags<>::LCA_ID]), - record.lcaId, - 'Z'); - if (lH.options.samBamTags[SamBamExtraTags<>::LCA_TAX_ID]) - seqan::appendTagValue(bamR.tags, - std::get<0>(SamBamExtraTags<>::keyDescPairs[SamBamExtraTags<>::LCA_TAX_ID]), - uint32_t(record.lcaTaxId), - 'I'); - if (lH.options.samBamTags[SamBamExtraTags<>::Q_AA_SEQ]) - { - if ((TGH::blastProgram == seqan::BlastProgram::BLASTN) || (!writeSeq)) - seqan::appendTagValue(bamR.tags, - std::get<0>(SamBamExtraTags<>::keyDescPairs[SamBamExtraTags<>::Q_AA_SEQ]), - "*", - 'Z'); - else if (lH.options.samBamHardClip) - seqan::appendTagValue( - bamR.tags, - std::get<0>(SamBamExtraTags<>::keyDescPairs[SamBamExtraTags<>::Q_AA_SEQ]), - seqan::source(mIt->alignRow0) | - bio::views::slice(seqan::beginPosition(mIt->alignRow0), seqan::endPosition(mIt->alignRow0)) | - bio::views::to_char, - 'Z'); - else // full prot sequence - seqan::appendTagValue(bamR.tags, - std::get<0>(SamBamExtraTags<>::keyDescPairs[SamBamExtraTags<>::Q_AA_SEQ]), - seqan::source(mIt->alignRow0) | bio::views::to_char, - 'Z'); - } - if (lH.options.samBamTags[SamBamExtraTags<>::Q_AA_CIGAR]) - { - if (seqan::empty(protCigar)) - { - protCigarString = "*"; - } - else - { - seqan::clear(protCigarString); - for (unsigned i = 0; i < seqan::length(protCigar); ++i) - { - seqan::appendNumber(protCigarString, protCigar[i].count); - seqan::appendValue(protCigarString, protCigar[i].operation); - } - } - seqan::appendTagValue(bamR.tags, - std::get<0>(SamBamExtraTags<>::keyDescPairs[SamBamExtraTags<>::Q_AA_CIGAR]), - protCigarString, - 'Z'); - } - if (lH.options.samBamTags[SamBamExtraTags<>::EDIT_DISTANCE]) - seqan::appendTagValue(bamR.tags, - std::get<0>(SamBamExtraTags<>::keyDescPairs[SamBamExtraTags<>::EDIT_DISTANCE]), - uint32_t(mIt->alignStats.alignmentLength - mIt->alignStats.numMatches), - 'I'); - if (lH.options.samBamTags[SamBamExtraTags<>::MATCH_COUNT]) - seqan::appendTagValue(bamR.tags, - std::get<0>(SamBamExtraTags<>::keyDescPairs[SamBamExtraTags<>::MATCH_COUNT]), - uint32_t(seqan::length(record.matches)), - 'I'); - - // goto next match - ++mIt; - } - - bamRecords.front().flag -= seqan::BAM_FLAG_SECONDARY; // remove BAM_FLAG_SECONDARY for first - - SEQAN_OMP_PRAGMA(critical(filewrite)) - { - for (auto & r : bamRecords) - seqan::writeRecord(lH.gH.outfileBam, r); - } - } -} - -// ---------------------------------------------------------------------------- -// Function myWriteFooter() -// ---------------------------------------------------------------------------- - -template -inline void myWriteFooter(TGH & globalHolder, TLambdaOptions const & options) -{ - if (options.outFileFormat == 0) // BLAST - { - seqan::writeFooter(globalHolder.outfileBlastTab); - } - else if (options.outFileFormat == -1) // BLAST - { - seqan::writeFooter(globalHolder.outfileBlastRep); - } -} diff --git a/src/seqan2_to_biocpp.hpp b/src/seqan2_to_biocpp.hpp deleted file mode 100644 index 767a5dac5..000000000 --- a/src/seqan2_to_biocpp.hpp +++ /dev/null @@ -1,416 +0,0 @@ -#pragma once - -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -// Some things needs to be defined before including SeqAn2 headers. -// This does not make sense, but oh well ¯\_(ツ)_/¯ - -namespace seqan -{ - -template - requires(!std::is_lvalue_reference_v>) -inline void const * getObjectId(T const & me) -{ - // return 0; - return std::addressof(me); -} - -template -inline bio::alphabet::gapped gapValueImpl(bio::alphabet::gapped *) -{ - return bio::alphabet::gapped{bio::alphabet::gap{}}; -} - -template -inline bio::alphabet::gapped gapValueImpl(bio::alphabet::gapped const *) -{ - return bio::alphabet::gapped{bio::alphabet::gap{}}; -} - -} // namespace seqan - -#include -#include -#include -#include - -#include "holder_tristate_overload.h" -#include "bisulfite_scoring.hpp" - -namespace seqan -{ - -// cpp20 span does not define const_iterator -#if defined(__cpp_lib_span) -template - requires(!requires { typename TContainer::const_iterator; }) -struct Value> -{ - typedef TContainer const TContainer_; - typedef typename TContainer::iterator const TIterator_; - typedef typename std::iterator_traits::value_type Type; -}; -#endif - -template -inline constexpr bool is_new_range = false; -template -inline constexpr bool is_new_range> = true; -template -inline constexpr bool is_new_range> = true; -template -inline constexpr bool is_new_range> = true; -template -inline constexpr bool is_new_range> = true; -template -inline constexpr bool is_new_range> = true; -template -inline constexpr bool is_new_range> = true; -template -inline constexpr bool is_new_range> = true; - -template -concept NonSeqAn2Range = is_new_range>; - -template -struct Value -{ - using Type = std::ranges::range_value_t; -}; -template -struct Value -{ - using Type = std::ranges::range_value_t; -}; -template -struct Reference -{ - using Type = std::ranges::range_reference_t; -}; -template -struct Reference -{ - using Type = std::ranges::range_reference_t; -}; -template -struct GetValue -{ - using Type = std::ranges::range_reference_t; -}; -template -struct GetValue -{ - using Type = std::ranges::range_reference_t; -}; -template -struct Position -{ - using Type = size_t; -}; -template -struct Position -{ - using Type = size_t; -}; -template -struct Size -{ - using Type = size_t; -}; -template -struct Size -{ - using Type = size_t; -}; -template -struct Iterator -{ - typedef Iter Type; -}; -template -struct Iterator -{ - typedef Iter Type; -}; -template -struct Iterator -{ - typedef Iter>> Type; -}; -template -struct Iterator -{ - typedef Iter>> Type; -}; -template -struct IsSequence : True -{}; -template -struct IsSequence : True -{}; -template -struct StdContainerIterator -{ - using Type = std::ranges::iterator_t; -}; -template -struct StdContainerIterator -{ - using Type = std::ranges::iterator_t; -}; -template -struct Reference> -{ - using Type = std::ranges::range_reference_t; -}; -template -struct Reference> -{ - using Type = std::ranges::range_reference_t; -}; -template -struct IsContiguous : std::conditional_t, True, False> -{}; -template -struct HasSubscriptOperator : std::conditional_t, True, False> -{}; - -template -SEQAN_CONCEPT_IMPL((T), (StlContainerConcept)); - -template -struct GetValue> -{ - using Type = std::ranges::range_reference_t; -}; - -template -struct GetValue> -{ - using Type = std::ranges::range_reference_t; -}; - -template -decltype(auto) source(Gaps const & gaps) -{ - return value(gaps._source); -} - -template -decltype(auto) source(Gaps & gaps) -{ - return value(gaps._source); -} - -template -inline void assignSource(Gaps & gaps, TSequence const & source) -{ - setValue(gaps._source, source); - _reinitArrayGaps(gaps); -} - -// –--------------------------------------------------------------------------- -// range stuff -// –--------------------------------------------------------------------------- - -template -void copy_range(TSource && in, String & out) -{ - if constexpr (std::ranges::sized_range) - { - resize(out, std::ranges::size(in)); - size_t i = 0; - for (auto && v : in) - out[i++] = std::forward(v); - } - else - { - clear(out); - for (auto && v : in) - appendValue(out, std::forward(v)); - } -} - -// –--------------------------------------------------------------------------- -// alphabet stuff -// –--------------------------------------------------------------------------- - -template - requires(!std::integral) -inline void write(stream_t & s, alph_t const alph) -{ - write(s, bio::alphabet::to_char(alph)); -} - -template - requires(!std::integral && requires(alph_t & a) { {bio::alphabet::to_char(a)}; }) -inline bool operator==(alph_t alph, char c) -{ - return bio::alphabet::to_char(alph) == c; -} - -template - requires(!std::integral && requires(alph_t & a) { {bio::alphabet::to_char(a)}; }) -inline bool operator==(char c, alph_t alph) -{ - return bio::alphabet::to_char(alph) == c; -} - -template -inline auto score(Score> const & scheme, - alph_t const a1, - alph_t const a2) noexcept -{ - return score(scheme, AminoAcid{bio::alphabet::to_char(a1)}, AminoAcid{bio::alphabet::to_char(a2)}); -} - -template -inline auto score(Score> const & scheme, - bio::alphabet::gapped const a1, - bio::alphabet::gapped const a2) noexcept -{ - return score(scheme, a1.template convert_unsafely_to(), a2.template convert_unsafely_to()); -} - -template -inline auto score(Score> const & scheme, - bio::alphabet::dna5 const a1, - bio::alphabet::dna5 const a2) noexcept -{ - return score(scheme, Dna5{bio::alphabet::to_char(a1)}, Dna5{bio::alphabet::to_char(a2)}); -} - -template -inline auto score(Score const & scheme, - bio::alphabet::dna5 const a1, - bio::alphabet::dna5 const a2) noexcept -{ - return score(scheme, Dna5{bio::alphabet::to_char(a1)}, Dna5{bio::alphabet::to_char(a2)}); -} - -template -inline auto score(Score const & scheme, - bio::alphabet::dna4 const a1, - bio::alphabet::dna4 const a2) noexcept -{ - return score(scheme, Dna{bio::alphabet::to_char(a1)}, Dna{bio::alphabet::to_char(a2)}); -} - -template -inline auto score(Score const & scheme, - bio::alphabet::gapped const a1, - bio::alphabet::gapped const a2) noexcept -{ - return score(scheme, a1.template convert_unsafely_to(), a2.template convert_unsafely_to()); -} - -template - requires(!std::integral) -char convertImpl(seqan::Convert, alph_t const & a) -{ - return bio::alphabet::to_char(a); -} - -template - requires(!std::integral) -int_t convertImpl(seqan::Convert, alph_t const & a) -{ - return bio::alphabet::to_rank(a); -} - -template - requires(!std::integral) -alph_t convertImpl(seqan::Convert>, bio::alphabet::gapped const & a) -{ - // return a.template convert_unsafely_to(); - return a.template convert_unsafely_to(); -} - -template - requires(!std::integral) -struct GappedValueType -{ - using Type = bio::alphabet::gapped; -}; - -// default is invalid; only used for alphabets that are scored with matrixes -template -inline constexpr std::array biocpp_rank_to_seqan2rank{}; - -// aa27 are not: -template <> -inline constexpr std::array biocpp_rank_to_seqan2rank = - // clang-format off -//A B C D E F G H I J K L M N O P Q R S T U V W X Y Z * <- biocpp -{ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 25, 23, 24, 26 }; -//A B C D E F G H I J K L M N O P Q R S T U V W Y Z X * <- seqan2 -// ↑ ↑ ↑ -// dna5 is scored via matrix in bisulfite-mode -template <> -inline constexpr std::array biocpp_rank_to_seqan2rank = -//A C G N T <- biocpp -{ 0, 1, 2, 4, 3 }; -//A C G T N <- seqan2 -// ↑ ↑ -// clang-format on - -// –--------------------------------------------------------------------------- -// SIMD Support -// SeqAn2 converts input sequence values into SIMD lanes via implicit conversion. -// This works for SeqAn2 alphabets, because they are implicitly convertible -// to all integral types but fails for SeqAn3 alphabets that are not. -// -// Below is an overload of the SIMD representation conversion function in SeqAn2. -// It gets chosen for ranges-over-ranges-over-SeqAn3-alphabet. -// And it applies a two-dimensional SeqAn2 View on top of that range-of-range -// that lazily converts the SeqAn3 alphabet to its rank representation which -// can then be used to create the SIMD lanes. -// -// –--------------------------------------------------------------------------- - -struct seqan2_to_rank_inner -{ - using result_type = uint8_t; - - template - constexpr uint8_t operator()(t const c) const noexcept - { - if constexpr (std::is_same_v || - std::is_same_v) // dna5 used in bisulfite-mode - return biocpp_rank_to_seqan2rank[bio::alphabet::to_rank(c)]; - else // alphabets that are scored with seqan::SimpleScore don't need extra conversion - return bio::alphabet::to_rank(c); - } -}; - -template -struct seqan2_to_rank_outer -{ - using argument_type = typename GetValue::Type; - using result_type = - seqan::ModifiedString const, seqan::ModView>; - - constexpr result_type operator()(argument_type const & c) const noexcept { return result_type{c}; } -}; - -template - requires((!std::integral>)&&bio::alphabet::alphabet< - bio::ranges::range_innermost_value_t>) -inline void _createSimdRepImpl(TSimdVecs & simdStr, TStrings const & strings) -{ - using TModT = seqan::ModifiedString>>; - _createSimdRepImpl(simdStr, TModT(strings)); -} - -} // namespace seqan diff --git a/src/shared_definitions.hpp b/src/shared_definitions.hpp deleted file mode 100644 index 28784fb6b..000000000 --- a/src/shared_definitions.hpp +++ /dev/null @@ -1,391 +0,0 @@ -// ========================================================================== -// lambda -// ========================================================================== -// Copyright (c) 2013-2024, Hannes Hauswedell

-// Copyright (c) 2016-2020, Knut Reinert and Freie Universität Berlin -// All rights reserved. -// -// This file is part of Lambda. -// -// Lambda is Free Software: you can redistribute it and/or modify it -// under the terms found in the LICENSE[.md|.rst] file distributed -// together with this file. -// -// Lambda 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. -// -// ========================================================================== -// shared_definitions.h: commonly used types and functions -// ========================================================================== - -#pragma once - -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include "view_dna_n_to_random.hpp" -#include "view_duplicate.hpp" -#include "view_reduce_to_bisulfite.hpp" - -#ifndef LAMBDA_WITH_BIFM -# define LAMBDA_WITH_BIFM 0 -#endif - -// ========================================================================== -// DbIndexType -// ========================================================================== - -enum class DbIndexType : uint8_t -{ - FM_INDEX, - BI_FM_INDEX -}; - -inline std::string _indexEnumToName(DbIndexType const t) -{ - switch (t) - { - case DbIndexType::FM_INDEX: - return "fm_index"; - case DbIndexType::BI_FM_INDEX: - return "bi_fm_index"; - } - - throw std::runtime_error("Error: unknown index type"); - return ""; -} - -inline DbIndexType _indexNameToEnum(std::string const t) -{ - if (t == "bi_fm_index") - return DbIndexType::BI_FM_INDEX; - else if (t == "fm_index") - return DbIndexType::FM_INDEX; - - throw std::runtime_error("Error: unknown index type"); - return DbIndexType::FM_INDEX; -} - -// ========================================================================== -// Alphabet stuff -// ========================================================================== - -constexpr char const * _alphTypeToName(bio::alphabet::semialphabet_any<6> const & /**/) -{ - return "dna3bs"; -} - -constexpr char const * _alphTypeToName(bio::alphabet::dna4 const & /**/) -{ - return "dna4"; -} - -constexpr char const * _alphTypeToName(bio::alphabet::dna5 const & /**/) -{ - return "dna5"; -} - -constexpr char const * _alphTypeToName(bio::alphabet::aa27 const & /**/) -{ - return "aminoacid"; -} - -constexpr char const * _alphTypeToName(bio::alphabet::aa10murphy const & /**/) -{ - return "murphy10"; -} - -constexpr char const * _alphTypeToName(bio::alphabet::aa10li const & /**/) -{ - return "li10"; -} - -enum class AlphabetEnum : uint8_t -{ - UNDEFINED, - DNA3BS, - DNA4, - DNA5, - AMINO_ACID, - MURPHY10, - LI10, -}; - -inline std::string _alphabetEnumToName(AlphabetEnum const t) -{ - switch (t) - { - case AlphabetEnum::UNDEFINED: - return "UNDEFINED"; - case AlphabetEnum::DNA3BS: - return _alphTypeToName(bio::alphabet::semialphabet_any<6>{}); - case AlphabetEnum::DNA4: - return _alphTypeToName(bio::alphabet::dna4{}); - case AlphabetEnum::DNA5: - return _alphTypeToName(bio::alphabet::dna5{}); - case AlphabetEnum::AMINO_ACID: - return _alphTypeToName(bio::alphabet::aa27{}); - case AlphabetEnum::MURPHY10: - return _alphTypeToName(bio::alphabet::aa10murphy{}); - case AlphabetEnum::LI10: - return _alphTypeToName(bio::alphabet::aa10li{}); - } - - throw std::runtime_error("Error: unknown alphabet type"); - return ""; -} - -inline AlphabetEnum _alphabetNameToEnum(std::string const t) -{ - if ((t == "UNDEFINED") || (t == "auto")) - return AlphabetEnum::UNDEFINED; - else if (t == _alphTypeToName(bio::alphabet::semialphabet_any<6>{})) - return AlphabetEnum::DNA3BS; - else if (t == _alphTypeToName(bio::alphabet::dna4{})) - return AlphabetEnum::DNA4; - else if (t == _alphTypeToName(bio::alphabet::dna5{})) - return AlphabetEnum::DNA5; - else if (t == _alphTypeToName(bio::alphabet::aa27{})) - return AlphabetEnum::AMINO_ACID; - else if (t == _alphTypeToName(bio::alphabet::aa10murphy{})) - return AlphabetEnum::MURPHY10; - else if (t == _alphTypeToName(bio::alphabet::aa10li{})) - return AlphabetEnum::LI10; - - throw std::runtime_error("Error: unknown alphabet type"); - return AlphabetEnum::DNA4; -} - -template -struct _alphabetEnumToType_; - -template <> -struct _alphabetEnumToType_ -{ - using type = bio::alphabet::semialphabet_any<6>; -}; - -template <> -struct _alphabetEnumToType_ -{ - using type = bio::alphabet::dna4; -}; - -template <> -struct _alphabetEnumToType_ -{ - using type = bio::alphabet::dna5; -}; - -template <> -struct _alphabetEnumToType_ -{ - using type = bio::alphabet::aa27; -}; - -template <> -struct _alphabetEnumToType_ -{ - using type = bio::alphabet::aa10murphy; -}; - -template <> -struct _alphabetEnumToType_ -{ - using type = bio::alphabet::aa10li; -}; - -template -using _alphabetEnumToType = typename _alphabetEnumToType_::type; - -// ========================================================================== -// Global variables -// ========================================================================== - -// this is increased after incompatible changes to on-disk format -inline constexpr uint64_t currentIndexGeneration = 0; - -// ========================================================================== -// Index specs -// ========================================================================== - -template -using IndexSpec = fmindex_collection::occtable::interleavedEPR32V2::OccTable; - -// ========================================================================== -// Misc. aliases -// ========================================================================== - -template -using TCDStringSet = bio::ranges::concatenated_sequences; - -template -inline constexpr auto sbjTransView = []() -{ - if constexpr (c_redAlph == AlphabetEnum::DNA3BS) - return views::duplicate; - else if constexpr (c_origSbjAlph != c_transAlph) - return bio::views::translate_join; - else - return bio::views::type_reduce; -}(); - -template -constexpr auto qryTransView = []() -{ - if constexpr (c_redAlph == AlphabetEnum::DNA3BS) - return bio::views::type_reduce | bio::views::add_reverse_complement | views::duplicate; - else if constexpr (bio::alphabet::nucleotide<_alphabetEnumToType>) - return bio::views::type_reduce | bio::views::add_reverse_complement; - else if constexpr (c_origQryAlph == c_transAlph) - return bio::views::type_reduce; - else - return bio::views::type_reduce | bio::views::translate_join; -}(); - -template -constexpr auto redView = []() -{ - if constexpr (c_transAlph == c_redAlph) - return bio::views::type_reduce; - else if constexpr (c_transAlph == AlphabetEnum::AMINO_ACID) - return bio::views::type_reduce | bio::views::deep{bio::views::convert<_alphabetEnumToType>}; - else if constexpr (c_redAlph == AlphabetEnum::DNA3BS) - return bio::views::type_reduce | views::dna_n_to_random | views::reduce_to_bisulfite; - else - return bio::views::type_reduce | views::dna_n_to_random; -}(); - -// ========================================================================== -// overload serialisation -// ========================================================================== - -namespace cereal -{ - -template - requires std::is_trivially_copyable_v -void save(cereal::BinaryOutputArchive & archive, std::vector const & vec) -{ - archive(static_cast(vec.size())); - archive(cereal::binary_data(vec.data(), vec.size() * sizeof(alph_t))); -} - -template - requires std::is_trivially_copyable_v -void load(cereal::BinaryInputArchive & archive, std::vector & vec) -{ - uint64_t s = 0; - archive(s); - - vec.resize(s); - archive(cereal::binary_data(vec.data(), s * sizeof(alph_t))); -} - -} // namespace cereal - -// ========================================================================== -// The index -// ========================================================================== - -// bump this on incompatible changes -inline constexpr uint64_t supportedIndexGeneration = 0; - -struct index_file_options -{ - uint64_t indexGeneration{supportedIndexGeneration}; - - DbIndexType indexType{}; - - AlphabetEnum origAlph{}; - AlphabetEnum transAlph{}; - AlphabetEnum redAlph{}; - - bio::alphabet::genetic_code geneticCode{}; - - template - void serialize(TArchive & archive) - { - archive(cereal::make_nvp("generation", indexGeneration), - cereal::make_nvp("index type", indexType), - cereal::make_nvp("orig alph", origAlph), - cereal::make_nvp("trans alph", transAlph), - cereal::make_nvp("red alph", redAlph), - cereal::make_nvp("genetic code", geneticCode)); - } -}; - -/* actual index */ -template // <- all members of index_file_options that influence types -struct index_file -{ - index_file_options options{}; - - TCDStringSet ids; - TCDStringSet>> seqs; - TCDStringSet> sTaxIds; - - std::vector taxonParentIDs; - std::vector taxonHeights; - TCDStringSet taxonNames; - - using TRedAlph = _alphabetEnumToType; - using TIndexSpec = IndexSpec>; - using TIndex = std::conditional_t, - fmindex_collection::ReverseFMIndex>; - - // Special c'tor that supports 'default' initialization to allow deserialize - TIndex index{fmindex_collection::cereal_tag{}}; - - template - void serialize(TArchive & archive) - { - archive(cereal::make_nvp("options", options), - cereal::make_nvp("ids", ids), - cereal::make_nvp("seqs", seqs), - cereal::make_nvp("sTaxIds", sTaxIds), - cereal::make_nvp("taxonParentIDs", taxonParentIDs), - cereal::make_nvp("taxonHeights", taxonHeights), - cereal::make_nvp("taxonNames", taxonNames), - cereal::make_nvp("index", index)); - } -}; - -/* pseudo-index that can be used to only load the options from disk */ -struct fake_index_file -{ - index_file_options & options; - - template - void serialize(TArchive & archive) - { - archive(cereal::make_nvp("options", options)); - } -}; diff --git a/src/shared_misc.hpp b/src/shared_misc.hpp deleted file mode 100644 index 573d65e1a..000000000 --- a/src/shared_misc.hpp +++ /dev/null @@ -1,219 +0,0 @@ -// ========================================================================== -// lambda -// ========================================================================== -// Copyright (c) 2013-2024, Hannes Hauswedell

-// Copyright (c) 2016-2020, Knut Reinert and Freie Universität Berlin -// All rights reserved. -// -// This file is part of Lambda. -// -// Lambda is Free Software: you can redistribute it and/or modify it -// under the terms found in the LICENSE[.md|.rst] file distributed -// together with this file. -// -// Lambda 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. -// -// ========================================================================== -// shared_misc.h: misc stuff for indexer and search -// ========================================================================== - -#pragma once - -#include -#include -#include -#include -#include -#include - -#if defined(__APPLE__) -# include -#endif - -#include - -#include "shared_options.hpp" - -// ============================================================================ -// Functions for translation and retranslation -// ============================================================================ - -template -inline bool inRange(TPos const i, TPos const beg, TPos const end) -{ - return ((i >= beg) && (i < end)); -} - -inline int64_t intervalOverlap(uint64_t const s1, uint64_t const e1, uint64_t const s2, uint64_t const e2) -{ - return std::min(e1, e2) - std::max(s1, s2); -} - -inline void printProgressBar(uint64_t & lastPercent, uint64_t curPerc) -{ - //round down to even - curPerc = curPerc & ~1; - // #pragma omp critical(stdout) - if ((curPerc > lastPercent) && (curPerc <= 100)) - { - for (uint64_t i = lastPercent + 2; i <= curPerc; i += 2) - { - if (i == 100) - std::cout << "|" << std::flush; - else if (i % 10 == 0) - std::cout << ":" << std::flush; - else - std::cout << "." << std::flush; - } - lastPercent = curPerc; - } -} - -template -constexpr bool all_valid(TRange && r) -{ - for (auto const c : r) - if (!bio::alphabet::char_is_valid_for(c)) - return false; - return true; -} - -inline AlphabetEnum detectSeqFileAlphabet(std::string const & path) -{ - using rec_t = decltype(bio::io::seq::record{.id = std::ignore, .seq = std::string_view{}, .qual = std::ignore}); - bio::io::seq::reader reader{path, bio::io::seq::reader_options{.record = rec_t{}}}; - - auto & seq = reader.begin()->seq; - - if (all_valid(seq)) - { - return AlphabetEnum::DNA5; - } - else if (all_valid(seq)) - { - std::cerr << "\nWARNING: You query file was detected as non-standard DNA, but it could be AminoAcid, too.\n" - "To explicitly read as AminoAcid, add '--input-alphabet aminoacid'.\n" - "To ignore and disable this warning, add '--input-alphabet dna5'.\n"; - return AlphabetEnum::DNA5; - } - else if (all_valid(seq)) - { - return AlphabetEnum::AMINO_ACID; - } - - throw std::runtime_error("Your query file contains illegal characters in the first sequence."); - - // unreachable - return AlphabetEnum::AMINO_ACID; -} - -// ---------------------------------------------------------------------------- -// print if certain verbosity is set -// ---------------------------------------------------------------------------- - -template -inline void myPrintImpl(SharedOptions const & /**/, T const & first) -{ - std::cout << first; -} - -template -inline void myPrintImpl(SharedOptions const & options, T const & first, Args const &... args) -{ - myPrintImpl(options, first); - myPrintImpl(options, args...); -} - -template -inline void myPrint(SharedOptions const & options, int const verbose, Args const &... args) -{ - if (options.verbosity >= verbose) - { - myPrintImpl(options, args...); - std::cout << std::flush; - } -} - -// ---------------------------------------------------------------------------- -// Function sysTime() -// ---------------------------------------------------------------------------- - -inline double sysTime() -{ - // return std::time(NULL); - return static_cast( - std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) - .count()) / - 1000; - // return std::chrono::system_clock::now().time_since_epoch().count() / 1000; -} - -// ---------------------------------------------------------------------------- -// Function fileSize() -// ---------------------------------------------------------------------------- - -inline uint64_t fileSize(char const * fileName) -{ - struct stat st; - if (stat(fileName, &st) != 0) - throw std::runtime_error{"Could not read File.\n"}; - return st.st_size; -} - -// ---------------------------------------------------------------------------- -// Function dirSize() -// ---------------------------------------------------------------------------- - -inline uint64_t dirSize(char const * dirName) -{ - DIR * d; - struct dirent * de; - struct stat buf; - int exists; - uint64_t total_size; - - d = opendir(dirName); - if (d == NULL) - throw std::runtime_error{"Could not read index directory.\n"}; - - total_size = 0; - - for (de = readdir(d); de != NULL; de = readdir(d)) - { - std::string curPath = dirName + std::string{"/"} + de->d_name; - exists = stat(curPath.c_str(), &buf); - if (exists < 0) - { - closedir(d); - throw std::runtime_error{"Could not read index directory.\n"}; - } - else - { - total_size += buf.st_size; - } - } - closedir(d); - return total_size; -} - -// ---------------------------------------------------------------------------- -// Function fileSize() -// ---------------------------------------------------------------------------- - -inline uint64_t getTotalSystemMemory() -{ -#if defined(__APPLE__) - uint64_t mem; - size_t len = sizeof(mem); - sysctlbyname("hw.memsize", &mem, &len, NULL, 0); - return mem; -#elif defined(__unix__) - long pages = sysconf(_SC_PHYS_PAGES); - long page_size = sysconf(_SC_PAGE_SIZE); - return pages * page_size; -#else -# error "no way to get phys pages" -#endif -} diff --git a/src/shared_options.hpp b/src/shared_options.hpp deleted file mode 100644 index 06e2533f1..000000000 --- a/src/shared_options.hpp +++ /dev/null @@ -1,153 +0,0 @@ -// ========================================================================== -// lambda -// ========================================================================== -// Copyright (c) 2013-2024, Hannes Hauswedell

-// Copyright (c) 2016-2020, Knut Reinert and Freie Universität Berlin -// All rights reserved. -// -// This file is part of Lambda. -// -// Lambda is Free Software: you can redistribute it and/or modify it -// under the terms found in the LICENSE[.md|.rst] file distributed -// together with this file. -// -// Lambda 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. -// -// ========================================================================== -// shared_options.h: contains the options and argument parser -// ========================================================================== - -#pragma once - -#include -#include -#include -#include -#include - -#include -#include - -#include "shared_definitions.hpp" - -using namespace std::string_literals; - -// -------------------------------------------------------------------------- -// Class SharedOptions -// -------------------------------------------------------------------------- - -enum class domain_t : uint8_t -{ - protein, - nucleotide, - bisulfite -}; - -inline std::string_view domain2string(domain_t const d) -{ - switch (d) - { - case domain_t::protein: - return "protein"; - case domain_t::nucleotide: - return "nucleotide"; - case domain_t::bisulfite: - return "bisulfite"; - } - throw std::logic_error{__FUNCTION__}; -} - -struct SharedOptions -{ - // Verbosity level. 0 -- quiet, 1 -- normal, 2 -- verbose - int32_t verbosity = 1; - - std::string commandLine; - - std::filesystem::path indexFilePath; - - index_file_options indexFileOptions{}; - - domain_t domain = domain_t::nucleotide; - bool need_to_translate = false; - - bool isTerm = true; - unsigned terminalCols = 80; - - uint64_t threads = std::thread::hardware_concurrency(); - - bool hasSTaxIds = false; - - SharedOptions() - { - // isTerm = seqan::isTerminal(); - // if (isTerm) - // { - // unsigned _rows; - // seqan::getTerminalSize(terminalCols, _rows); - // } - } -}; - -inline void sharedSetup(sharg::parser & parser) -{ - // Set short description, version, and date - parser.info.version = SEQAN_APP_VERSION; - parser.info.date = __DATE__; - parser.info.citation = "Hauswedell & Hetzal et al (2024); doi: 10.1093/bioinformatics/btae097"; - parser.info.short_copyright = - "2013-2024 Hannes Hauswedell & Sara Hetzel, released under the GNU AGPL v3 (or later); " - "2016-2020 Knut Reinert and Freie Universität Berlin, released under the 3-clause-BSDL"; - parser.info.long_copyright = - " Copyright (c) 2013-2024, Hannes Hauswedell & Sara Hetzel\n" - " All rights reserved.\n" - "\n" - " This program is free software: you can redistribute it and/or modify\n" - " it under the terms of the GNU Affero General Public License as\n" - " published by the Free Software Foundation, either version 3 of the\n" - " License, or (at your option) any later version.\n" - "\n" - " Lambda is distributed in the hope that it will be useful,\n" - " but WITHOUT ANY WARRANTY; without even the implied warranty of\n" - " MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n" - " GNU General Public License for more details.\n" - "\n" - " You should have received a copy of the GNU Affero General Public License\n" - " along with this program. If not, see .\n" - "\n" - " Copyright (c) 2016-2020 Knut Reinert and Freie Universität Berlin\n" - " All rights reserved.\n" - "\n" - " Redistribution and use in source and binary forms, with or without\n" - " modification, are permitted provided that the following conditions are met:\n" - "\n" - " * Redistributions of source code must retain the above copyright\n" - " notice, this list of conditions and the following disclaimer.\n" - " * Redistributions in binary form must reproduce the above copyright\n" - " notice, this list of conditions and the following disclaimer in the\n" - " documentation and/or other materials provided with the distribution.\n" - " * Neither the name of Knut Reinert or the FU Berlin nor the names of\n" - " its contributors may be used to endorse or promote products derived\n" - " from this software without specific prior written permission.\n" - "\n" - " THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS \"AS IS\"\n" - " AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE\n" - " IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE\n" - " ARE DISCLAIMED. IN NO EVENT SHALL KNUT REINERT OR THE FU BERLIN BE LIABLE\n" - " FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL\n" - " DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR\n" - " SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER\n" - " CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT\n" - " LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY\n" - " OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH\n" - " DAMAGE.\n"; - parser.info.description.push_back( - "Lambda is a local aligner capable of performing protein, nucleotide and bisulfite searches. " - "It is compatible to BLAST, but much faster than BLAST and many other comparable tools."); - - parser.info.description.push_back( - "Detailed information is available in the wiki: " - ""); -} diff --git a/src/view_async_input_buffer.hpp b/src/view_async_input_buffer.hpp deleted file mode 100644 index c38e0a77e..000000000 --- a/src/view_async_input_buffer.hpp +++ /dev/null @@ -1,463 +0,0 @@ -// ----------------------------------------------------------------------------------------------------- -// Copyright (c) 2006-2022, Knut Reinert & Freie Universität Berlin -// Copyright (c) 2016-2022, Knut Reinert & MPI für molekulare Genetik -// This file may be used, modified and/or redistributed under the terms of the 3-clause BSD-License -// shipped with this file and also available at: https://github.com/seqan/seqan3/blob/master/LICENSE.md -// ----------------------------------------------------------------------------------------------------- - -/*!\file - * \author Hannes Hauswedell - * \brief Provides views::async_input_buffer. - */ - -#pragma once - -#include -#include -#include -#include -#include - -#include -#include - -//----------------------------------------------------------------------------- -// This is the path a value takes when using this views:: -// urange -// → async_input_buffer_view.buffer [size n] -// → iterator.cached_value [size 1] -// → user -//----------------------------------------------------------------------------- - -/*!\brief The type returned by views::async_input_buffer. - * \tparam urng_t The underlying range type. - * \implements std::ranges::input_range - * \ingroup io_views - */ -template -class async_input_buffer_view : public std::ranges::view_interface> -{ -private: - static_assert(std::ranges::input_range, - "The range parameter to async_input_buffer_view must be at least a std::ranges::input_range."); - static_assert(std::ranges::view, - "The range parameter to async_input_buffer_view must model std::ranges::view."); - static_assert(std::movable>, - "The range parameter to async_input_buffer_view must have a value_type that is std::movable."); - static_assert( - std::constructible_from, - std::remove_reference_t> &&>, - "The range parameter to async_input_buffer_view must have a value_type that is constructible by a moved " - "value of its reference type."); - - //!\brief The iterator type for the underlying range. - using urng_iterator_type = std::ranges::iterator_t; - - //!\brief Buffer and thread and shared between copies of this type. - struct state - { - //!\brief The underlying range. - urng_t urange; - - //!\brief The buffer queue. - bio::io::contrib::fixed_buffer_queue> buffer; - - //!\brief Thread that rebuffers in the background. - std::thread producer; - }; - - //!\brief Shared holder of the state. - std::shared_ptr state_ptr = nullptr; - - //!\brief The iterator of the detail::async_input_buffer_view. - class iterator; - -public: - /*!\name Constructor, destructor, and assignment. - * \{ - */ - async_input_buffer_view() = default; //!< Defaulted. - async_input_buffer_view(async_input_buffer_view const &) = default; //!< Defaulted. - async_input_buffer_view(async_input_buffer_view &&) = default; //!< Defaulted. - async_input_buffer_view & operator=(async_input_buffer_view const &) = default; //!< Defaulted. - async_input_buffer_view & operator=(async_input_buffer_view &&) = default; //!< Defaulted. - ~async_input_buffer_view() = default; //!< Defaulted. - - //!\brief Construction from the underlying view. - async_input_buffer_view(urng_t _urng, size_t const buffer_size) - { - auto deleter = [](state * p) - { - if (p != nullptr) - { - p->buffer.close(); - p->producer.join(); - delete p; - } - }; - - state_ptr = std::shared_ptr( - new state{std::move(_urng), - bio::io::contrib::fixed_buffer_queue>{buffer_size}, - std::thread{}}, // thread is set/started below, needs rest of state - deleter); - - auto runner = [&state = *state_ptr]() - { - for (auto && val : state.urange) - if (state.buffer.wait_push(std::move(val)) == bio::io::contrib::queue_op_status::closed) - break; - - state.buffer.close(); - }; - - state_ptr->producer = std::thread{runner}; - } - - //!\brief Construction from std::ranges::viewable_range. - template - requires(!std::same_as, async_input_buffer_view>) - && // prevent recursive instantiation - std::ranges::viewable_range && - std::constructible_from>> - async_input_buffer_view(other_urng_t && _urng, size_t const buffer_size) : - async_input_buffer_view{std::views::all(_urng), buffer_size} - {} - //!\} - - /*!\name Iterators - * \{ - */ - /*!\brief Returns an iterator to the current begin of the underlying range. - * - * \details - * - * ### Thread-Safety - * - * It is thread-safe to call this function. Subsequent calls to begin will result in different - * iterators that are each valid individually. It is thread-safe to operate on different iterators - * from different threads (however it is not thread-safe to operate on a single iterator from different - * threads). - */ - iterator begin() - { - assert(state_ptr != nullptr); - return {state_ptr->buffer}; - } - - //!\brief Const-qualified async_input_buffer_view::begin() is deleted, because iterating changes the view. - iterator begin() const = delete; - - //!\brief Returns a sentinel. - std::default_sentinel_t end() { return std::default_sentinel; } - - //!\brief Const-qualified async_input_buffer_view::end() is deleted, because iterating changes the view. - std::default_sentinel_t end() const = delete; - //!\} -}; - -//!\brief The iterator of the detail::async_input_buffer_view. -template -class async_input_buffer_view::iterator -{ - //!\brief The sentinel type to compare to. - using sentinel_type = std::default_sentinel_t; - - //!\brief The pointer to the associated view. - bio::io::contrib::fixed_buffer_queue> * buffer_ptr = nullptr; - - //!\brief The cached value this iterator holds. - mutable std::ranges::range_value_t cached_value; - - //!\brief Whether this iterator is at end (the buffer is empty and closed). - bool at_end = false; - -public: - /*!\name Associated types - * \{ - */ - //!\brief Difference type. - using difference_type = std::iter_difference_t; - //!\brief Value type. - using value_type = std::iter_value_t; - //!\brief Pointer type. - using pointer = bio::ranges::detail::iter_pointer_t; - //!\brief Reference type. - using reference = std::iter_reference_t; - //!\brief Iterator category. - using iterator_category = std::input_iterator_tag; - //!\brief Iterator concept. - using iterator_concept = iterator_category; - //!\} - - /*!\name Construction, destruction and assignment - * \brief Not explicitly `noexcept` because this depends on construction/copy/... of value_type. - * \{ - */ - iterator() = default; //!< Defaulted. - iterator(iterator const & rhs) = delete; //!< Deleted. - iterator(iterator && rhs) = default; //!< Defaulted. - iterator & operator=(iterator const & rhs) = delete; //!< Deleted. - iterator & operator=(iterator && rhs) = default; //!< Defaulted. - ~iterator() noexcept = default; //!< Defaulted. - - //!\brief Constructing from the underlying async_input_buffer_view. - iterator(bio::io::contrib::fixed_buffer_queue> & buffer) noexcept : - buffer_ptr{&buffer} - { - ++(*this); // cache first value - } - //!\} - - /*!\name Access operations - * \{ - */ - //!\brief Return the cached value. - reference operator*() const noexcept { return cached_value; } - - //!\brief Returns pointer to the pointed-to object. - pointer operator->() const noexcept { return std::addressof(cached_value); } - //!\} - - /*!\name Iterator operations - * \{ - */ - //!\brief Pre-increment. - iterator & operator++() noexcept - { - if (at_end) - return *this; - - assert(buffer_ptr != nullptr); - - if (buffer_ptr->wait_pop(cached_value) == bio::io::contrib::queue_op_status::closed) - at_end = true; - - return *this; - } - - //!\brief Post-increment. - void operator++(int) noexcept { ++(*this); } - //!\} - - /*!\name Comparison operators - * \{ - */ - //!\brief Compares for equality with sentinel. - friend constexpr bool operator==(iterator const & lhs, std::default_sentinel_t const &) noexcept - { - return lhs.at_end; - } - - //!\copydoc operator== - friend constexpr bool operator==(std::default_sentinel_t const &, iterator const & rhs) noexcept - { - return rhs == std::default_sentinel_t{}; - } - - //!\brief Compares for inequality with sentinel. - friend constexpr bool operator!=(iterator const & lhs, std::default_sentinel_t const &) noexcept - { - return !(lhs == std::default_sentinel_t{}); - } - - //!\copydoc operator!= - friend constexpr bool operator!=(std::default_sentinel_t const &, iterator const & rhs) noexcept - { - return rhs != std::default_sentinel_t{}; - } - //!\} -}; - -/*!\name Deduction guide. - * \relates detail::async_input_buffer_view - * \{ - */ -//!\brief Deduces the async_input_buffer_view from the underlying range if it is a std::ranges::viewable_range. -template -async_input_buffer_view(urng_t &&, size_t const buffer_size) -> async_input_buffer_view>; -//!\} - -// ============================================================================ -// async_input_buffer_fn (adaptor definition -// ============================================================================ - -//!\brief Definition of the range adaptor object type for views::async_input_buffer. -struct async_input_buffer_fn -{ - //!\brief Store the argument and return a range adaptor closure object. - constexpr auto operator()(size_t const buffer_size) const - { - return bio::ranges::detail::adaptor_from_functor{*this, buffer_size}; - } - - /*!\brief Directly return an instance of the view, initialised with the given parameters. - * \param[in] urange The underlying range. - * \param[in] buffer_size The frame that should be used for translation. - * \returns A range of translated sequence(s). - */ - template - constexpr auto operator()(urng_t && urange, size_t const buffer_size) const - { - static_assert(std::ranges::input_range, - "The range parameter to views::async_input_buffer must be at least a std::ranges::input_range."); - static_assert(std::ranges::viewable_range, - "The range parameter to views::async_input_buffer cannot be a temporary of a non-view range."); - static_assert(std::movable>, - "The range parameter to views::async_input_buffer must have a value_type that is std::movable."); - static_assert( - std::constructible_from, - std::remove_reference_t> &&>, - "The range parameter to views::async_input_buffer must have a value_type that is constructible by a moved " - "value of its reference type."); - - if (buffer_size == 0) - throw std::invalid_argument{"The buffer_size parameter to views::async_input_buffer must be > 0."}; - - return async_input_buffer_view{std::forward(urange), buffer_size}; - } -}; - -//----------------------------------------------------------------------------- -// View shortcut for functor. -//----------------------------------------------------------------------------- - -namespace views -{ - -/*!\brief A view adapter that returns a concurrent-queue-like view over the underlying range. - * \tparam urng_t The type of the range being processed. See below for requirements. - * \param[in,out] urange The range being processed. - * \param[in] buffer_size Size of the buffer. Choose the size (> 0) depending on the expected work per element. - * \returns A view that pre-fetches elements from the underlying range and provides a thread-safe interface. - * See below for the properties of the returned range. - * \ingroup io_views - * - * \details - * - * - * ### Summary - * - * This view spawns a background thread that pre-fetches elements from the underlying range and stores them in a - * concurrent queue. Iterating over this view then pops elements out of the queue and returns them. - * This is primarily useful if dereferencing/incrementing the iterator of the underlying range - * is expensive, e.g. with SeqAn files which lazily perform I/O. - * - * Another advantage of this view is that multiple iterators can be created that are safe to iterate individually, - * even from different threads, i.e. you can use multiple threads to iterate safely over a single-pass input view - * with the added benefit of background pre-fetching. - * - * In technical terms: this view facilitates a single-producer, multi-consumer design; it's a range interface over - * a concurrent queue. - * - * ### Size of the buffer - * - * The `buffer_size` parameter should be chosen depending on the expected work per element, e.g. if the underlying - * range is an input file over short reads, a buffer size of 100 or 1000 could be beneficial; if on the other hand - * the file contains genome-sized sequences, it would be better to buffer only a single sequence (buffering 100 - * sequences would result in the entire file being preloaded and likely consuming significant memory). - * - * ### Range consumption - * - * This view always moves elements from the underlying range into its buffer which means that the elements in - * the underlying range will be invalidated! For underlying ranges that are single-pass, this makes no difference, but - * it might be unexpected for multi-pass ranges (std::ranges::forward_range). - * - * Typically this adaptor is used when you want to consume the entire underlying range. Destructing - * this view before all elements have been read will also stop the thread that moves object from the underlying - * range. - * **In general, it is not safe to access the underlying range in other contexts once it has been passed - * to views::async_input_buffer.** - * - * Note that in addition to the buffer of the view, every iterator has its own one-element-buffer. Dereferencing - * the iterator returns a reference to the element in the buffer, usually you will want to move this element out - * of the buffer with std::move std::ranges::iter_move. Incrementing the iterator refills the buffer from the queue - * inside the view (which in turn is then refilled from the underlying range). - * - * ### View properties - * - * | concepts and reference type | `urng_t` (underlying range type) | `rrng_t` (returned range type) | - * |-------------------------------------------|:---------------------------------:|:--------------------------------------:| - * | std::ranges::input_range | *required* | *preserved* | - * | std::ranges::forward_range | | *lost* | - * | std::ranges::bidirectional_range | | *lost* | - * | std::ranges::random_access_range | | *lost* | - * | std::ranges::contiguous_range | | *lost* | - * | | | | - * | std::ranges::viewable_range | *required* | *guaranteed* | - * | std::ranges::view | | *guaranteed* | - * | std::ranges::sized_range | | *lost* | - * | std::ranges::common_range | | *lost* | - * | std::ranges::output_range | | *lost* | - * | seqan3::const_iterable_range | | *lost* | - * | | | | - * | std::ranges::range_reference_t | | `std::ranges::range_value_t &` | - * | | | | - * | std::iterator_traits \::iterator_category | | *none* | - * - * See the \link views views submodule documentation \endlink for detailed descriptions of the view properties. - * - * ### Thread safety - * - * The following operations are **thread-safe**: - * - * * calling `.begin()` and `.end()` on the view returned by this adaptor; - * * calling operators on the different iterator objects. - * - * Calling operators on the same iterator object from different threads is not safe, i.e. you can pass the view - * to different threads by reference, and have each of those threads call `begin()` on the view and then - * perform operations (dereference, increment...) on that iterator from the respective thread; but you - * cannot call `begin()` in a parent thread, pass the iterator to different threads and operate on that - * concurrently. - * - * ### Example - * - * \include test/snippet/io/views/async_input_buffer.cpp - * - * Running the snippet could yield the following output: - * - * ``` - * Thread: 0x80116bf00 Seq: seq2 - * Thread: 0x80116bf00 Seq: seq3 - * Thread: 0x80116ba00 Seq: seq1 - * Thread: 0x80116bf00 Seq: seq4 - * Thread: 0x80116bf00 Seq: seq6 - * Thread: 0x80116ba00 Seq: seq5 - * Thread: 0x80116bf00 Seq: seq7 - * Thread: 0x80116ba00 Seq: seq8 - * Thread: 0x80116bf00 Seq: seq9 - * Thread: 0x80116bf00 Seq: seq11 - * Thread: 0x80116bf00 Seq: seq12 - * Thread: 0x80116ba00 Seq: seq10 - * ``` - * This shows that indeed elements from the underlying range are processed non-sequentially, that there are two threads - * and that work is "balanced" between them (one thread processed more element than the other, because its "work" - * per item happened to be smaller). - * - * Note that you might encounter jumbled output if by chance two threads write to the stream at the exact same time. - * - * If you remove the line starting with `auto f1 = ...` you will get sequential processing: - * ``` - * Thread: 0x80116aa00 Seq: seq1 - * Thread: 0x80116aa00 Seq: seq2 - * Thread: 0x80116aa00 Seq: seq3 - * Thread: 0x80116aa00 Seq: seq4 - * Thread: 0x80116aa00 Seq: seq5 - * Thread: 0x80116aa00 Seq: seq6 - * Thread: 0x80116aa00 Seq: seq7 - * Thread: 0x80116aa00 Seq: seq8 - * Thread: 0x80116aa00 Seq: seq9 - * Thread: 0x80116aa00 Seq: seq10 - * Thread: 0x80116aa00 Seq: seq11 - * Thread: 0x80116aa00 Seq: seq12 - * ``` - * - * Note that even if you have a single processing thread, using this view can still improve performance measurably, - * because loading of the elements into the buffer (which reads input from disk) happens in a background thread. - * - * \hideinitializer - * - * \experimentalapi{Experimental since version 3.1.} - */ -inline constexpr auto async_input_buffer = async_input_buffer_fn{}; -} // namespace views diff --git a/src/view_dna_n_to_random.hpp b/src/view_dna_n_to_random.hpp deleted file mode 100644 index 630685bc1..000000000 --- a/src/view_dna_n_to_random.hpp +++ /dev/null @@ -1,73 +0,0 @@ -// ========================================================================== -// lambda -// ========================================================================== -// Copyright (c) 2019-2024, Sara Hetzel and MPI für Molekulare Genetik -// Copyright (c) 2016-2020, Knut Reinert and Freie Universität Berlin -// All rights reserved. -// -// This file is part of Lambda. -// -// Lambda is Free Software: you can redistribute it and/or modify it -// under the terms found in the LICENSE[.md|.rst] file distributed -// together with this file. -// -// Lambda 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. -// -// ========================================================================== -// view_dna_n_to_random.hpp: View that converts N into random selection of -// {A,C,G,T} if target alphabet is dna4 -// ========================================================================== - -#pragma once - -#include -#include - -#include -#include -#include -#include - -// Definition of the range adaptor object type for views::dna_n_to_random. -struct dna_n_to_random_fn -{ - template - constexpr auto operator()(urng_t && urange) const - { - static_assert(std::ranges::viewable_range, - "The range parameter to dna_n_to_random cannot be a temporary of a non-view range."); - static_assert(std::ranges::sized_range, - "The range parameter to dna_n_to_random must model std::ranges::sized_range."); - static_assert(std::ranges::random_access_range, - "The range parameter to dna_n_to_random must model std::ranges::random_access_range."); - static_assert(std::same_as>, - "The range parameter to dna_n_to_random must be over elements of bio::alphabet::dna5."); - - std::shared_ptr rng{new std::mt19937{0xDEADBEEF}}; - - return std::forward(urange) | - std::views::transform( - [rng](bio::alphabet::dna5 const c) - { - return (bio::alphabet::to_char(c) == 'N') - ? bio::alphabet::assign_rank_to((*rng)() % 4, bio::alphabet::dna4{}) - : static_cast(c); - }); - } - - template - constexpr friend auto operator|(urng_t && urange, dna_n_to_random_fn const & me) - { - return me(std::forward(urange)); - } -}; - -// A view that converts every ambiguous nucleotide 'N' randomly into a letter of a new alphabet (e.g. bio::alphabet::dna4). -namespace views -{ - -inline constexpr auto dna_n_to_random = bio::views::deep{dna_n_to_random_fn{}}; - -} // namespace views diff --git a/src/view_duplicate.hpp b/src/view_duplicate.hpp deleted file mode 100644 index 4612e89ac..000000000 --- a/src/view_duplicate.hpp +++ /dev/null @@ -1,72 +0,0 @@ -// ========================================================================== -// lambda -// ========================================================================== -// Copyright (c) 2019-2024, Sara Hetzel and MPI für Molekulare Genetik -// Copyright (c) 2016-2020, Knut Reinert and Freie Universität Berlin -// All rights reserved. -// -// This file is part of Lambda. -// -// Lambda is Free Software: you can redistribute it and/or modify it -// under the terms found in the LICENSE[.md|.rst] file distributed -// together with this file. -// -// Lambda 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. -// -// ========================================================================== -// view_duplicate.hpp: View that duplicates a range in a range-of-ranges -// ========================================================================== - -#pragma once - -#include - -#include - -// Definition of the range adaptor object type for views::duplicate. -struct duplicate_fn -{ - template - constexpr auto operator()(urng_t && urange) const - { - static_assert(bio::ranges::range_dimension_v == 2, - "This adaptor only handles range-of-range (two dimensions) as input."); - static_assert(std::ranges::viewable_range, - "The range parameter to views::duplicate cannot be a temporary of a non-view range."); - static_assert(std::ranges::viewable_range>, - "The inner range of the range parameter to views::duplicate cannot be a temporary of " - "a non-view range."); - static_assert(std::ranges::sized_range, - "The range parameter to views::duplicate must model std::ranges::sized_range."); - static_assert(std::ranges::sized_range>, - "The inner range of the range parameter to views::duplicate must model " - "std::ranges::sized_range."); - static_assert(std::ranges::random_access_range, - "The range parameter to views::duplicate must model std::ranges::random_access_range."); - static_assert(std::ranges::random_access_range>, - "The inner range of the range parameter to views::duplicate must model " - "std::ranges::random_access_range."); - - return std::forward(urange) | - bio::views::transform_by_pos([](auto && urange, size_t pos) -> decltype(auto) - { return urange[(pos - (pos % 2)) / 2]; }, - [](auto && urange) { return std::ranges::size(urange) * 2; }); - } - - template - constexpr friend auto operator|(urng_t && urange, duplicate_fn const & me) - { - return me(std::forward(urange)); - } -}; - -// A view that duplicates the inner ranges in a range-of-ranges. The output range has twice the size of the input range -// where duplicates appear directly after each other. -namespace views -{ - -inline constexpr auto duplicate = duplicate_fn{}; - -} // namespace views diff --git a/src/view_reduce_to_bisulfite.hpp b/src/view_reduce_to_bisulfite.hpp deleted file mode 100644 index b540767f8..000000000 --- a/src/view_reduce_to_bisulfite.hpp +++ /dev/null @@ -1,148 +0,0 @@ -// ========================================================================== -// lambda -// ========================================================================== -// Copyright (c) 2019-2024, Sara Hetzel and MPI für Molekulare Genetik -// Copyright (c) 2016-2020, Knut Reinert and Freie Universität Berlin -// All rights reserved. -// -// This file is part of Lambda. -// -// Lambda is Free Software: you can redistribute it and/or modify it -// under the terms found in the LICENSE[.md|.rst] file distributed -// together with this file. -// -// Lambda 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. -// -// ========================================================================== -// view_reduce_to_bisulfite.hpp: View that converts dna sequences into bisulfite -// forward and reverse sequences -// ========================================================================== - -#pragma once - -#include - -#include -#include -#include -#include -#include - -#include "bisulfite_scoring.hpp" - -// Definition of the range adaptor object type for views::to_bisulfite_semialphabet. -struct to_bisulfite_semialphabet_fn -{ - constexpr auto operator()(bsDirection const direction) const - { - return bio::ranges::detail::adaptor_from_functor{*this, direction}; - } - - // Rank - // 0 = A forward - // 1 = C/T forward - // 2 = G forward - // 3 = A/G reverse - // 4 = C reverse - // 5 = T reverse -private: - static constexpr std::array dna4_to_rank_bs_fwd = {0, 1, 2, 1}; - static constexpr std::array dna4_to_rank_bs_rev = {3, 4, 3, 5}; - - static auto func_fwd(auto && urange, size_t pos) - { - return bio::alphabet::assign_rank_to(dna4_to_rank_bs_fwd[bio::alphabet::to_rank(urange[pos])], - bio::alphabet::semialphabet_any<6>{}); - } - static auto func_rev(auto && urange, size_t pos) - { - return bio::alphabet::assign_rank_to(dna4_to_rank_bs_rev[bio::alphabet::to_rank(urange[pos])], - bio::alphabet::semialphabet_any<6>{}); - } - -public: - template - constexpr auto operator()(urng_t && urange, bsDirection const direction) const - { - static_assert( - std::ranges::viewable_range, - "The range parameter to views::to_bisulfite_semialphabet cannot be a temporary of a non-view range."); - static_assert(std::ranges::sized_range, - "The range parameter to views::to_bisulfite_semialphabet must model std::ranges::sized_range."); - static_assert( - std::ranges::random_access_range, - "The range parameter to views::to_bisulfite_semialphabet must model std::ranges::random_access_range."); - static_assert( - std::is_same_v>, bio::alphabet::dna4>, - "The range parameter to views::to_bisulfite_semialphabet must be over elements of bio::alphabet::dna4."); - - auto l = &func_fwd const &>; - if (direction == bsDirection::rev) - l = &func_rev const &>; - return std::forward(urange) | bio::views::transform_by_pos(l); - } -}; - -// A view that converts elements of the bio::alphabet::dna4 alphabet to a semialphabet that models reduced forward and reverse -// alphabets for the bisulfite mode. Depending on the `direction` parameter, letters get converted to the rank of the bisulfite -// reduced alphabet for forward sequences or reverse sequences which both are included in the same semialphabet of size 6. -namespace views -{ - -inline constexpr auto to_bisulfite_semialphabet = bio::views::deep{to_bisulfite_semialphabet_fn{}}; - -} // namespace views - -// Definition of the range adaptor object type for views::reduce_to_bisulfite. -struct reduce_to_bisulfite_fn -{ - template - constexpr auto operator()(urng_t && urange) const - { - static_assert(bio::ranges::range_dimension_v == 2, - "This adaptor only handles range-of-range (two dimensions) as input."); - static_assert(std::ranges::viewable_range, - "The range parameter to views::reduce_to_bisulfite cannot be a temporary of a non-view range."); - static_assert(std::ranges::viewable_range>, - "The inner range of the range parameter to views::reduce_to_bisulfite cannot be a " - "temporary of a non-view range."); - static_assert(std::ranges::sized_range, - "The range parameter to views::reduce_to_bisulfite must model std::ranges::sized_range."); - static_assert(std::ranges::sized_range>, - "The inner range of the range parameter to views::reduce_to_bisulfite must model " - "std::ranges::sized_range."); - static_assert(std::ranges::random_access_range, - "The range parameter to views::reduce_to_bisulfite must model std::ranges::random_access_range."); - static_assert(std::ranges::random_access_range>, - "The inner range of the range parameter to views::reduce_to_bisulfite must model " - "std::ranges::random_access_range."); - static_assert( - std::is_same_v>, bio::alphabet::dna4>, - "The range parameter to views::reduce_to_bisulfite must be over a range over elements of " - "bio::alphabet::dna4."); - - return std::forward(urange) | - bio::views::transform_by_pos( - [](auto && urange, size_t pos) - { return urange[pos] | views::to_bisulfite_semialphabet((bsDirection)(pos % 2)); }); - } - - template - constexpr friend auto operator|(urng_t && urange, reduce_to_bisulfite_fn const & me) - { - return me(std::forward(urange)); - } -}; - -// A view that operates on a range-of-ranges where the inner range needs to be of type bio::alphabet::dna4. -// Inner ranges with an even index get reduced to forward bisulfite sequences while inner ranges with an odd index get -// converted to reverse bisulfite sequences. The output range is a range-of-range where the type of the inner ranges is -// a semialphabet of size 6. -namespace views -{ - -inline constexpr auto reduce_to_bisulfite = reduce_to_bisulfite_fn{}; - -} // namespace views diff --git a/stylesheets/github-light.css b/stylesheets/github-light.css new file mode 100644 index 000000000..872a6f4b2 --- /dev/null +++ b/stylesheets/github-light.css @@ -0,0 +1,116 @@ +/* + Copyright 2014 GitHub Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + +*/ + +.pl-c /* comment */ { + color: #969896; +} + +.pl-c1 /* constant, markup.raw, meta.diff.header, meta.module-reference, meta.property-name, support, support.constant, support.variable, variable.other.constant */, +.pl-s .pl-v /* string variable */ { + color: #0086b3; +} + +.pl-e /* entity */, +.pl-en /* entity.name */ { + color: #795da3; +} + +.pl-s .pl-s1 /* string source */, +.pl-smi /* storage.modifier.import, storage.modifier.package, storage.type.java, variable.other, variable.parameter.function */ { + color: #333; +} + +.pl-ent /* entity.name.tag */ { + color: #63a35c; +} + +.pl-k /* keyword, storage, storage.type */ { + color: #a71d5d; +} + +.pl-pds /* punctuation.definition.string, string.regexp.character-class */, +.pl-s /* string */, +.pl-s .pl-pse .pl-s1 /* string punctuation.section.embedded source */, +.pl-sr /* string.regexp */, +.pl-sr .pl-cce /* string.regexp constant.character.escape */, +.pl-sr .pl-sra /* string.regexp string.regexp.arbitrary-repitition */, +.pl-sr .pl-sre /* string.regexp source.ruby.embedded */ { + color: #183691; +} + +.pl-v /* variable */ { + color: #ed6a43; +} + +.pl-id /* invalid.deprecated */ { + color: #b52a1d; +} + +.pl-ii /* invalid.illegal */ { + background-color: #b52a1d; + color: #f8f8f8; +} + +.pl-sr .pl-cce /* string.regexp constant.character.escape */ { + color: #63a35c; + font-weight: bold; +} + +.pl-ml /* markup.list */ { + color: #693a17; +} + +.pl-mh /* markup.heading */, +.pl-mh .pl-en /* markup.heading entity.name */, +.pl-ms /* meta.separator */ { + color: #1d3e81; + font-weight: bold; +} + +.pl-mq /* markup.quote */ { + color: #008080; +} + +.pl-mi /* markup.italic */ { + color: #333; + font-style: italic; +} + +.pl-mb /* markup.bold */ { + color: #333; + font-weight: bold; +} + +.pl-md /* markup.deleted, meta.diff.header.from-file */ { + background-color: #ffecec; + color: #bd2c00; +} + +.pl-mi1 /* markup.inserted, meta.diff.header.to-file */ { + background-color: #eaffea; + color: #55a532; +} + +.pl-mdr /* meta.diff.range */ { + color: #795da3; + font-weight: bold; +} + +.pl-mo /* meta.output */ { + color: #1d3e81; +} + diff --git a/stylesheets/styles.css b/stylesheets/styles.css new file mode 100644 index 000000000..ba4eeb04f --- /dev/null +++ b/stylesheets/styles.css @@ -0,0 +1,427 @@ +@import url(https://fonts.googleapis.com/css?family=Arvo:400,700,400italic); + +/* MeyerWeb Reset */ + +html, body, div, span, applet, object, iframe, +h1, h2, h3, h4, h5, h6, p, blockquote, pre, +a, abbr, acronym, address, big, cite, code, +del, dfn, em, img, ins, kbd, q, s, samp, +small, strike, strong, sub, sup, tt, var, +b, u, i, center, +dl, dt, dd, ol, ul, li, +fieldset, form, label, legend, +table, caption, tbody, tfoot, thead, tr, th, td, +article, aside, canvas, details, embed, +figure, figcaption, footer, header, hgroup, +menu, nav, output, ruby, section, summary, +time, mark, audio, video { + margin: 0; + padding: 0; + border: 0; + font: inherit; + vertical-align: baseline; +} + + +/* Base text styles */ + +body { + padding:10px 50px 0 0; + font-family:"Helvetica Neue", Helvetica, Arial, sans-serif; + font-size: 14px; + color: #232323; + background-color: #FBFAF7; + margin: 0; + line-height: 1.8em; + -webkit-font-smoothing: antialiased; + +} + +h1, h2, h3, h4, h5, h6 { + color:#232323; + margin:36px 0 10px; +} + +p, ul, ol, table, dl { + margin:0 0 22px; +} + +h1, h2, h3 { + font-family: Arvo, Monaco, serif; + line-height:1.3; + font-weight: normal; +} + +h1,h2, h3 { + display: block; + border-bottom: 1px solid #ccc; + padding-bottom: 5px; +} + +h1 { + font-size: 30px; +} + +h2 { + font-size: 24px; +} + +h3 { + font-size: 18px; +} + +h4, h5, h6 { + font-family: Arvo, Monaco, serif; + font-weight: 700; +} + +a { + color:#C30000; + font-weight:200; + text-decoration:none; +} + +a:hover { + text-decoration: underline; +} + +a small { + font-size: 12px; +} + +em { + font-style: italic; +} + +strong { + font-weight:700; +} + +ul { + list-style-position: inside; + list-style: disc; + padding-left: 25px; +} + +ol { + list-style-position: inside; + list-style: decimal; + padding-left: 25px; +} + +blockquote { + margin: 0; + padding: 0 0 0 20px; + font-style: italic; +} + +dl, dt, dd, dl p { + font-color: #444; +} + +dl dt { + font-weight: bold; +} + +dl dd { + padding-left: 20px; + font-style: italic; +} + +dl p { + padding-left: 20px; + font-style: italic; +} + +hr { + border:0; + background:#ccc; + height:1px; + margin:0 0 24px; +} + +/* Images */ + +img { + position: relative; + margin: 0 auto; + max-width: 650px; + padding: 5px; + margin: 10px 0 32px 0; + border: 1px solid #ccc; +} + +p img { + display: inline; + margin: 0; + padding: 0; + vertical-align: middle; + text-align: center; + border: none; +} + +/* Code blocks */ + +code, pre { + font-family: Monaco, "Bitstream Vera Sans Mono", "Lucida Console", Terminal, monospace; + color:#000; + font-size:14px; +} + +pre { + padding: 4px 12px; + background: #FDFEFB; + border-radius:4px; + border:1px solid #D7D8C8; + overflow: auto; + overflow-y: hidden; + margin-bottom: 32px; +} + + +/* Tables */ + +table { + width:100%; +} + +table { + border: 1px solid #ccc; + margin-bottom: 32px; + text-align: left; + } + +th { + font-family: 'Arvo', Helvetica, Arial, sans-serif; + font-size: 18px; + font-weight: normal; + padding: 10px; + background: #232323; + color: #FDFEFB; + } + +td { + padding: 10px; + background: #ccc; + } + + +/* Wrapper */ +.wrapper { + width:960px; + z-index:10; +} + + +/* Header */ + +header { + background-color: #171717; + color: #FDFDFB; + width:170px; + float:left; + position:fixed; + border: 1px solid #000; + -webkit-border-top-right-radius: 4px; + -webkit-border-bottom-right-radius: 4px; + -moz-border-radius-topright: 4px; + -moz-border-radius-bottomright: 4px; + border-top-right-radius: 4px; + border-bottom-right-radius: 4px; + padding: 34px 25px 22px 50px; + margin: 30px 25px 0 0; + -webkit-font-smoothing: antialiased; + z-index:5; +} + +p.header { + font-size: 16px; +} + +h1.header { + font-family: Arvo, sans-serif; + font-size: 30px; + font-weight: 300; + line-height: 1.3em; + border-bottom: none; + margin-top: 0; +} + + +h1.header, a.header, a.name, header a{ + color: #fff; +} + +a.header { + text-decoration: underline; +} + +a.name { + white-space: nowrap; +} + +header ul { + list-style:none; + padding:0; +} + +header li { + list-style-type: none; + width:132px; + height:15px; + margin-bottom: 12px; + line-height: 1em; + padding: 6px 6px 6px 7px; + + background: #AF0011; + background: -moz-linear-gradient(top, #AF0011 0%, #820011 100%); + background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f8f8f8), color-stop(100%,#dddddd)); + background: -webkit-linear-gradient(top, #AF0011 0%,#820011 100%); + background: -o-linear-gradient(top, #AF0011 0%,#820011 100%); + background: -ms-linear-gradient(top, #AF0011 0%,#820011 100%); + background: linear-gradient(top, #AF0011 0%,#820011 100%); + + border-radius:4px; + border:1px solid #0D0D0D; + + -webkit-box-shadow: inset 0px 1px 1px 0 rgba(233,2,38, 1); + box-shadow: inset 0px 1px 1px 0 rgba(233,2,38, 1); + +} + +header li:hover { + background: #C3001D; + background: -moz-linear-gradient(top, #C3001D 0%, #950119 100%); + background: -webkit-gradient(linear, left top, left bottom, color-stop(0%,#f8f8f8), color-stop(100%,#dddddd)); + background: -webkit-linear-gradient(top, #C3001D 0%,#950119 100%); + background: -o-linear-gradient(top, #C3001D 0%,#950119 100%); + background: -ms-linear-gradient(top, #C3001D 0%,#950119 100%); + background: linear-gradient(top, #C3001D 0%,#950119 100%); +} + +a.buttons { + -webkit-font-smoothing: antialiased; + background: url(../images/arrow-down.png) no-repeat; + font-weight: normal; + text-shadow: rgba(0, 0, 0, 0.4) 0 -1px 0; + padding: 2px 2px 2px 22px; + height: 30px; +} + +a.github { + background: url(../images/octocat-small.png) no-repeat 1px; +} + +a.buttons:hover { + color: #fff; + text-decoration: none; +} + + +/* Section - for main page content */ + +section { + width:650px; + float:right; + padding-bottom:50px; +} + + +/* Footer */ + +footer { + width:170px; + float:left; + position:fixed; + bottom:10px; + padding-left: 50px; + overflow: hidden; + z-index:1; +} + +@media print, screen and (max-width: 960px) { + + div.wrapper { + width:auto; + margin:0; + } + + header, section, footer { + float:none; + position:static; + width:auto; + } + + footer { + border-top: 1px solid #ccc; + margin:0 84px 0 50px; + padding:0; + } + + header { + padding-right:320px; + } + + section { + padding:20px 84px 20px 50px; + margin:0 0 20px; + } + + header a small { + display:inline; + } + + header ul { + position:absolute; + right:130px; + top:84px; + } +} + +@media print, screen and (max-width: 720px) { + body { + word-wrap:break-word; + } + + header { + padding:10px 20px 0; + margin-right: 0; + } + + section { + padding:10px 0 10px 20px; + margin:0 0 30px; + } + + footer { + margin: 0 0 0 30px; + } + + header ul, header p.view { + position:static; + } +} + +@media print, screen and (max-width: 480px) { + + header ul li.download { + display:none; + } + + footer { + margin: 0 0 0 20px; + } + + footer a{ + display:block; + } + +} + +@media print { + body { + padding:0.4in; + font-size:12pt; + color:#444; + } +} diff --git a/submodules/biocpp-core b/submodules/biocpp-core deleted file mode 160000 index 3c7c5dd28..000000000 --- a/submodules/biocpp-core +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 3c7c5dd28e9fe676674c973a3139887ca36c9659 diff --git a/submodules/biocpp-io b/submodules/biocpp-io deleted file mode 160000 index c7f1b6703..000000000 --- a/submodules/biocpp-io +++ /dev/null @@ -1 +0,0 @@ -Subproject commit c7f1b6703e05814ac28fb35afa035b73cf6999fd diff --git a/submodules/cereal b/submodules/cereal deleted file mode 160000 index ddd467244..000000000 --- a/submodules/cereal +++ /dev/null @@ -1 +0,0 @@ -Subproject commit ddd467244713ea4fe63733628992efcdd6a9187d diff --git a/submodules/fmindex-collection b/submodules/fmindex-collection deleted file mode 160000 index f4bf4a347..000000000 --- a/submodules/fmindex-collection +++ /dev/null @@ -1 +0,0 @@ -Subproject commit f4bf4a347af80fcdc9f678fd10155b85a1bd515f diff --git a/submodules/seqan b/submodules/seqan deleted file mode 160000 index 92e8e7a52..000000000 --- a/submodules/seqan +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 92e8e7a52eaae4a1d787ff5fcd53affdad073be8 diff --git a/submodules/sharg-parser b/submodules/sharg-parser deleted file mode 160000 index 88ffb13e5..000000000 --- a/submodules/sharg-parser +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 88ffb13e5178c419fdb70fb988962e61b31682b6 diff --git a/test/CMakeLists.txt b/test/CMakeLists.txt deleted file mode 100644 index 6b22287a2..000000000 --- a/test/CMakeLists.txt +++ /dev/null @@ -1,115 +0,0 @@ -cmake_minimum_required (VERSION 3.8) - -############################################################################### -# App tests -############################################################################### - -# Set directories for test output files, input data and binaries. -file (MAKE_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}/output) -add_definitions (-DOUTPUTDIR=\"${CMAKE_CURRENT_BINARY_DIR}/output/\") -add_definitions (-DDATADIR=\"${CMAKE_CURRENT_BINARY_DIR}/data/\") -add_definitions (-DBINDIR=\"${PROJECT_BINARY_DIR}/bin/\") - -# Define cmake configuration flags to configure and build external projects with the same flags as specified for -# this project. -# We also pass the C_COMPILER such that googletest is built with the corresponding GCC. -# Otherwise, it might happen that the app is built with, e.g., g++-11, but gtest with gcc-7, which might cause trouble. -set (BIOCPP_EXTERNAL_PROJECT_CMAKE_ARGS "") -list (APPEND BIOCPP_EXTERNAL_PROJECT_CMAKE_ARGS "-DCMAKE_C_COMPILER=${CMAKE_C_COMPILER}") -list (APPEND BIOCPP_EXTERNAL_PROJECT_CMAKE_ARGS "-DCMAKE_CXX_COMPILER=${CMAKE_CXX_COMPILER}") -list (APPEND BIOCPP_EXTERNAL_PROJECT_CMAKE_ARGS "-DCMAKE_BUILD_TYPE=${CMAKE_BUILD_TYPE}") -list (APPEND BIOCPP_EXTERNAL_PROJECT_CMAKE_ARGS "-DCMAKE_INSTALL_PREFIX=${PROJECT_BINARY_DIR}") -list (APPEND BIOCPP_EXTERNAL_PROJECT_CMAKE_ARGS "-DCMAKE_VERBOSE_MAKEFILE=${CMAKE_VERBOSE_MAKEFILE}") -set (BIOCPP_TEST_CLONE_DIR "${PROJECT_BINARY_DIR}/vendor/googletest") - -include ("${BIOCPP_CORE_CLONE_DIR}/test/cmake/biocpp_require_test.cmake") -biocpp_require_test () - -# Build tests just before their execution, because they have not been built with "all" target. -# The trick is here to provide a cmake file as a directory property that executes the build command. -file (WRITE "${CMAKE_CURRENT_BINARY_DIR}/build_test_targets.cmake" - "execute_process (COMMAND ${CMAKE_COMMAND} --build ${CMAKE_BINARY_DIR} --target cli_test)\n") -set_directory_properties (PROPERTIES TEST_INCLUDE_FILE "${CMAKE_CURRENT_BINARY_DIR}/build_test_targets.cmake") - -# Test executables and libraries should not mix with the application files. -unset (CMAKE_ARCHIVE_OUTPUT_DIRECTORY) -unset (CMAKE_LIBRARY_OUTPUT_DIRECTORY) -unset (CMAKE_RUNTIME_OUTPUT_DIRECTORY) - -# Define the test targets. All depending targets are built just before the test execution. -add_custom_target (cli_test) - -# A macro that adds an api or cli test. -macro (add_app_test test_filename) - # Extract the test target name. - file (RELATIVE_PATH source_file "${CMAKE_SOURCE_DIR}" "${CMAKE_CURRENT_LIST_DIR}/${test_filename}") - get_filename_component (target "${source_file}" NAME_WE) - - # since we are not linking biocpp, we need to manually add c++20 - set(CMAKE_CXX_STANDARD 20) - - # Create the test target. - add_executable (${target} ${test_filename}) - target_link_libraries (${target} gtest gtest_main) - - # Make biocpp::test available for both cli and api tests. - # target_include_directories (${target} PUBLIC "${BIOCPP_CORE_CLONE_DIR}/test/include") - target_include_directories (${target} PUBLIC "${BIOCPP_TEST_CLONE_DIR}/googletest/include/") - - add_dependencies (${target} "${PROJECT_NAME}") # cli test needs the application executable - add_dependencies (cli_test ${target}) - - # Generate and set the test name. - get_filename_component (target_relative_path "${source_file}" DIRECTORY) - - if (target_relative_path) - set (test_name "${target_relative_path}/${target}") - else () - set (test_name "${target}") - endif () - add_test (NAME "${test_name}" COMMAND ${target}) - - unset (source_file) - unset (target) - unset (test_name) -endmacro () - -macro (add_cli_test test_filename) - add_app_test (${test_filename} CLI_TEST) -endmacro () - -string (TOUPPER ${PROJECT_NAME} uppercase_project_name) -set (${uppercase_project_name}_HEADER_TEST_ONLY OFF CACHE BOOL "Only build header test.") - -if (${uppercase_project_name}_HEADER_TEST_ONLY) - add_subdirectory (header) -else () - # Fetch data and add the tests. - include (data/datasources.cmake) - add_subdirectory (cli) -endif () - -message (STATUS "${FontBold}You can run `make cli-test` to build the tests and `make test` to run them.${FontReset}") - -############################################################################### -# Clang format -############################################################################### - -find_program(CLANG_FORMAT "clang-format-14") - -if (CLANG_FORMAT STREQUAL "CLANG_FORMAT-NOTFOUND") - find_program(CLANG_FORMAT "clang-format") -endif() - -if (NOT CLANG_FORMAT STREQUAL "CLANG_FORMAT-NOTFOUND") - add_custom_target (check_format ALL "find" "${CMAKE_CURRENT_SOURCE_DIR}/../src" "-name" "'*.[ch]pp'" "-exec" - ${CLANG_FORMAT} "-style=file" "-n" "-Werror" "{}" "+" - COMMENT "Checking the source-code with clang-format.") - - - add_custom_target (reformat "find" "${CMAKE_CURRENT_SOURCE_DIR}/../src" "-name" "'*.[ch]pp'" "-exec" - ${CLANG_FORMAT} "-style=file" "-i" "{}" "+" - COMMENT "Reformatting the source-code with clang-format.") -else () - message(STATUS "clang_format not found; not adding the 'check_format' and 'reformat' targets.") -endif() diff --git a/test/cli/CMakeLists.txt b/test/cli/CMakeLists.txt deleted file mode 100644 index 965c36021..000000000 --- a/test/cli/CMakeLists.txt +++ /dev/null @@ -1,100 +0,0 @@ -cmake_minimum_required (VERSION 3.8) - -add_cli_test (index_test.cpp) -target_use_datasources (index_test FILES db_nucl.fasta.gz - db_nucl_bs.fasta.gz - db_prot.fasta.gz - db_nucl_bs_bifm.fasta.gz.lba - db_nucl_bs_fm.fasta.gz.lba - db_nucl_bifm.fasta.gz.lba - db_nucl_fm.fasta.gz.lba - db_prot_bifm.fasta.gz.lba - db_prot_fm.fasta.gz.lba - db_trans_bifm.fasta.gz.lba - db_trans_fm.fasta.gz.lba) - -add_cli_test (search_test.cpp) -target_use_datasources (search_test FILES db_nucl.fasta.gz - db_nucl_bs.fasta.gz - db_prot.fasta.gz - queries_nucl.fasta.gz - queries_nucl_bs.fasta.gz - queries_prot.fasta.gz - output_blastn_bs_fm.bam - output_blastn_bs_fm.m0 - output_blastn_bs_fm.m8 - output_blastn_bs_fm.m9 - output_blastn_bs_fm.sam - output_blastn_fm.bam - output_blastn_fm.m0 - output_blastn_fm.m8 - output_blastn_fm.m9 - output_blastn_fm.sam - output_blastp_fm.bam - output_blastp_fm.m0 - output_blastp_fm.m8 - output_blastp_fm.m9 - output_blastp_fm.sam - output_blastx_fm.bam - output_blastx_fm.m0 - output_blastx_fm.m8 - output_blastx_fm.m9 - output_blastx_fm.sam - output_tblastn_fm.bam - output_tblastn_fm.m0 - output_tblastn_fm.m8 - output_tblastn_fm.m9 - output_tblastn_fm.sam - output_tblastx_fm.bam - output_tblastx_fm.m0 - output_tblastx_fm.m8 - output_tblastx_fm.m9 - output_tblastx_fm.sam - output_blastn_bs_fm_fast.m8 - output_blastn_bs_fm_fast.sam - output_blastn_fm_fast.m8 - output_blastn_fm_fast.sam - output_blastp_fm_fast.m8 - output_blastp_fm_fast.sam - output_blastx_fm_fast.m8 - output_blastx_fm_fast.sam - output_tblastn_fm_fast.m8 - output_tblastn_fm_fast.sam - output_tblastx_fm_fast.m8 - output_tblastx_fm_fast.sam - output_blastn_bs_fm_sensitive.m8 - output_blastn_bs_fm_sensitive.sam - output_blastn_fm_sensitive.m8 - output_blastn_fm_sensitive.sam - output_blastp_fm_sensitive.m8 - output_blastp_fm_sensitive.sam - output_blastx_fm_sensitive.m8 - output_blastx_fm_sensitive.sam - output_tblastn_fm_sensitive.m8 - output_tblastn_fm_sensitive.sam - output_tblastx_fm_sensitive.m8 - output_tblastx_fm_sensitive.sam - output_blastn_bs_fm_pairs_default.m8 - output_blastn_bs_fm_pairs_default.sam - output_blastn_fm_pairs_default.m8 - output_blastn_fm_pairs_default.sam - output_blastp_fm_pairs_default.m8 - output_blastp_fm_pairs_default.sam - output_blastx_fm_pairs_default.m8 - output_blastx_fm_pairs_default.sam - output_tblastn_fm_pairs_default.m8 - output_tblastn_fm_pairs_default.sam - output_tblastx_fm_pairs_default.m8 - output_tblastx_fm_pairs_default.sam - output_blastn_bs_fm_pairs_sensitive.m8 - output_blastn_bs_fm_pairs_sensitive.sam - output_blastn_fm_pairs_sensitive.m8 - output_blastn_fm_pairs_sensitive.sam - output_blastp_fm_pairs_sensitive.m8 - output_blastp_fm_pairs_sensitive.sam - output_blastx_fm_pairs_sensitive.m8 - output_blastx_fm_pairs_sensitive.sam - output_tblastn_fm_pairs_sensitive.m8 - output_tblastn_fm_pairs_sensitive.sam - output_tblastx_fm_pairs_sensitive.m8 - output_tblastx_fm_pairs_sensitive.sam) diff --git a/test/cli/cli_test.hpp b/test/cli/cli_test.hpp deleted file mode 100644 index ddd995819..000000000 --- a/test/cli/cli_test.hpp +++ /dev/null @@ -1,90 +0,0 @@ -#include - -#include // system calls -#include // ostringstream -#include // strings -#include - -#pragma once - -// Provides functions for CLI test implementation. -struct cli_test : public ::testing::Test -{ -private: - - // Holds the original work directory where Gtest has been started. - std::filesystem::path original_workdir{}; - -protected: - - // Result struct for captured streams and exit code. - struct cli_test_result - { - std::string out{}; - std::string err{}; - int exit_code{}; - }; - - // Invoke the app execution. The command line call should be given as separate parameters. - template - cli_test_result execute_app(CommandItemTypes &&... command_items) - { - cli_test_result result{}; - - // Assemble the command string and disable version check. - std::ostringstream command{}; - command << "SHARG_NO_VERSION_CHECK=1 " << BINDIR; - ((command << command_items << ' '), ...); - - // Always capture the output streams. - testing::internal::CaptureStdout(); - testing::internal::CaptureStderr(); - - // Run the command and return results. - result.exit_code = std::system(command.str().c_str()); - result.out = testing::internal::GetCapturedStdout(); - result.err = testing::internal::GetCapturedStderr(); - return result; - } - - // Generate the full path of a test input file that is provided in the data directory. - static std::filesystem::path data(std::string const & filename) - { - return std::filesystem::path{std::string{DATADIR}}.concat(filename); - } - - // Create an individual work directory for the current test. - void SetUp() override - { - // Assemble the directory name. - ::testing::TestInfo const * const info = ::testing::UnitTest::GetInstance()->current_test_info(); - std::filesystem::path const test_dir{std::string{OUTPUTDIR} + - std::string{info->test_case_name()} + - std::string{"."} + - std::string{info->name()}}; - try - { - std::filesystem::remove_all(test_dir); // delete the directory if it exists - std::filesystem::create_directories(test_dir); // create the new empty directory - original_workdir = std::filesystem::current_path(); // store original work dir path - std::filesystem::current_path(test_dir); // change the work dir - } - catch (std::exception const & exc) - { - FAIL() << "Failed to set up the test directory " << test_dir << ":\n" << exc.what(); - } - } - - // Switch back to the initial work directory. - void TearDown() override - { - try - { - std::filesystem::current_path(original_workdir); // restore the original work dir - } - catch (std::exception const & exc) - { - FAIL() << "Failed to set the work directory to " << original_workdir << ":\n" << exc.what(); - } - } -}; diff --git a/test/cli/index_test.cpp b/test/cli/index_test.cpp deleted file mode 100644 index 09d33b84e..000000000 --- a/test/cli/index_test.cpp +++ /dev/null @@ -1,182 +0,0 @@ -#include -#include - -#include "cli_test.hpp" - -struct index_test : public cli_test -{ - std::string md5_cmd; - - void determine_md5_cmd() - { - if (std::system("echo foo | md5sum > /dev/null 2>&1") == 0) - md5_cmd = "md5sum"; - else if (std::system("echo foo | md5 -r > /dev/null 2>&1") == 0) - md5_cmd = "md5 -r"; - - ASSERT_FALSE(md5_cmd.empty()); - } - - void run_index_test(std::string const & index_command, - std::string const & db_file, - std::string const & index_file, - std::string const & index_type, - std::string const & reduction, - std::string const & control_file) - { - cli_test_result result; - if (index_command == "mkindexp") - { - result = execute_app("lambda3", - index_command, - "-d", data(db_file), - "-i", index_file, - "--db-index-type", index_type, - "-r", reduction); - } - else - { - result = execute_app("lambda3", - index_command, - "-d", data(db_file), - "-i", index_file, - "--db-index-type", - index_type); - } - - ASSERT_EQ(result.exit_code, 0); - - if (md5_cmd.empty()) - determine_md5_cmd(); - - int ret = std::system((md5_cmd + " " + index_file + " > md5sum_test.txt").c_str()); - ASSERT_TRUE(ret == 0); - ret = std::system((md5_cmd + " " + (std::string) data(control_file) + " > md5sum_control.txt").c_str()); - ASSERT_TRUE(ret == 0); - - std::ifstream test_output ("md5sum_test.txt"); - std::ifstream control_output ("md5sum_control.txt"); - - std::string test_line; - std::string control_line; - - getline(test_output, test_line); - getline(control_output, control_line); - - std::string test_sum = test_line.substr(0, test_line.find(' ')); - std::string control_sum = control_line.substr(0, control_line.find(' ')); - - ASSERT_EQ(test_sum, control_sum); - } -}; - -TEST_F(index_test, no_options) -{ - cli_test_result result = execute_app("lambda3"); - std::string expected - { - "lambda3 - Lambda, the Local Aligner for Massive Biological DatA.\n" - "================================================================\n" - " lambda3 [OPTIONS] COMMAND [COMMAND-OPTIONS]\n" - " Try -h or --help for more information.\n" - }; - EXPECT_EQ(result.exit_code, 0); - EXPECT_EQ(result.out, expected); - EXPECT_EQ(result.err, std::string{}); -} - -TEST_F(index_test, mkindexn_no_options) -{ - cli_test_result result = execute_app("lambda3", "mkindexn"); - std::string expected - { - "lambda3-mkindexn - the Local Aligner for Massive Biological DatA\n" - "================================================================\n" - " lambda3 mkindexn [OPTIONS] -d DATABASE.fasta [-i INDEX.lba]\n" - " Try -h or --help for more information.\n" - }; - EXPECT_EQ(result.exit_code, 0); - EXPECT_EQ(result.out, expected); - EXPECT_EQ(result.err, std::string{}); -} - -TEST_F(index_test, mkindexp_no_options) -{ - cli_test_result result = execute_app("lambda3", "mkindexp"); - std::string expected - { - "lambda3-mkindexp - the Local Aligner for Massive Biological DatA\n" - "================================================================\n" - " lambda3 mkindexp [OPTIONS] -d DATABASE.fasta [-i INDEX.lba]\n" - " Try -h or --help for more information.\n" - }; - EXPECT_EQ(result.exit_code, 0); - EXPECT_EQ(result.out, expected); - EXPECT_EQ(result.err, std::string{}); -} - -TEST_F(index_test, mkindexbs_no_options) -{ - cli_test_result result = execute_app("lambda3", "mkindexbs"); - std::string expected - { - "lambda3-mkindexbs - the Local Aligner for Massive Biological DatA\n" - "=================================================================\n" - " lambda3 mkindexbs [OPTIONS] -d DATABASE.fasta [-i INDEX.lba]\n" - " Try -h or --help for more information.\n" - }; - EXPECT_EQ(result.exit_code, 0); - EXPECT_EQ(result.out, expected); - EXPECT_EQ(result.err, std::string{}); -} - -TEST_F(index_test, nucl_fm) -{ - run_index_test("mkindexn", "db_nucl.fasta.gz", "db_nucl_fm_test.fasta.gz.lba", "fm", "", "db_nucl_fm.fasta.gz.lba"); -} - -TEST_F(index_test, nucl_bs_fm) -{ - run_index_test("mkindexbs", "db_nucl_bs.fasta.gz", "db_nucl_bs_fm_test.fasta.gz.lba", "fm", "", - "db_nucl_bs_fm.fasta.gz.lba"); -} - -TEST_F(index_test, prot_fm) -{ - run_index_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm_test.fasta.gz.lba", "fm", "li10", - "db_prot_fm.fasta.gz.lba"); -} - -TEST_F(index_test, trans_fm) -{ - run_index_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm_test.fasta.gz.lba", "fm", "li10", - "db_trans_fm.fasta.gz.lba"); -} - -#if LAMBDA_WITH_BIFM - -TEST_F(index_test, nucl_bifm) -{ - run_index_test("mkindexn", "db_nucl.fasta.gz", "db_nucl_bifm_test.fasta.gz.lba", "bifm", "", - "db_nucl_bifm.fasta.gz.lba"); -} - -TEST_F(index_test, nucl_bs_bifm) -{ - run_index_test("mkindexbs", "db_nucl_bs.fasta.gz", "db_nucl_bs_bifm_test.fasta.gz.lba", "bifm", "", - "db_nucl_bs_bifm.fasta.gz.lba"); -} - -TEST_F(index_test, prot_bifm) -{ - run_index_test("mkindexp", "db_prot.fasta.gz", "db_prot_bifm_test.fasta.gz.lba", "bifm", "li10", - "db_prot_bifm.fasta.gz.lba"); -} - -TEST_F(index_test, trans_bifm) -{ - run_index_test("mkindexp", "db_nucl.fasta.gz", "db_trans_bifm_test.fasta.gz.lba", "bifm", "li10", - "db_trans_bifm.fasta.gz.lba"); -} - -#endif diff --git a/test/cli/search_test.cpp b/test/cli/search_test.cpp deleted file mode 100644 index 9af95afb1..000000000 --- a/test/cli/search_test.cpp +++ /dev/null @@ -1,777 +0,0 @@ -#include -#include - -#include "cli_test.hpp" - -struct search_test : public cli_test -{ - std::string md5_cmd; - - void determine_md5_cmd() - { - if (std::system("echo foo | md5sum > /dev/null 2>&1") == 0) - md5_cmd = "md5sum"; - else if (std::system("echo foo | md5 -r > /dev/null 2>&1") == 0) - md5_cmd = "md5 -r"; - - ASSERT_FALSE(md5_cmd.empty()); - } - - void run_search_test(std::string const & index_command, - std::string const & db_file, - std::string const & index_file, - std::string const & index_type, - std::string const & reduction, - std::string const & search_command, - std::string const & query_file, - std::string const & profile, - std::string const & output_file, - std::string const & output_type, - std::string const & control_file, - auto ... more_args) - { - std::string _r; - std::string _red; - if (index_command == "mkindexp") - { - _r = "-r"; - _red = reduction; - } - - std::string _t = "-t"; - std::string _threads = "1"; - if (sizeof...(more_args) > 0 && ((more_args == "-t") || ...)) - { - _t = ""; - _threads = ""; - } - - cli_test_result result_index = execute_app("lambda3", index_command, - "-d", data(db_file), - "-i", index_file, - "--db-index-type", index_type, - _r, _red); - - cli_test_result result_search = execute_app("lambda3", search_command, - "-i", index_file, - "-q", data(query_file), - _t, _threads, - "--version-to-outputfile", "0", - "-p", profile, - "-o", output_file, - more_args...); - - ASSERT_EQ(result_search.exit_code, 0); - - int ret = 0; - - if (output_type == "bam") - { - if (md5_cmd.empty()) - determine_md5_cmd(); - - ret = std::system((md5_cmd + " " + output_file + " > md5sum_test.txt").c_str()); - ASSERT_TRUE(ret == 0); - ret = std::system((md5_cmd + " " + (std::string) data(control_file) + " > md5sum_control.txt").c_str()); - ASSERT_TRUE(ret == 0); - - std::ifstream test_output ("md5sum_test.txt"); - std::ifstream control_output ("md5sum_control.txt"); - - std::string test_line; - std::string control_line; - - getline(test_output, test_line); - getline(control_output, control_line); - - std::string test_sum = test_line.substr(0, test_line.find(' ')); - std::string control_sum = control_line.substr(0, control_line.find(' ')); - - ASSERT_EQ(test_sum, control_sum); - } - else - { - std::ifstream test_output; - - if (output_type == "m9_gz") - { - ret = system(("gunzip " + output_file).c_str()); - ASSERT_TRUE(ret == 0); - test_output.open(output_file.substr(0, output_file.length() - 3)); - } - else - { - test_output.open(output_file); - } - - std::ifstream control_output (data(control_file)); - - std::string test_line; - std::string control_line; - while (!test_output.eof() && !control_output.eof()) - { - getline(test_output, test_line); - getline(control_output, control_line); - ASSERT_EQ(test_line, control_line); - } - EXPECT_TRUE(test_output.eof()); - EXPECT_TRUE(control_output.eof()); - } - } -}; - -TEST_F(search_test, searchn_no_options) -{ - cli_test_result result = execute_app("lambda3", "searchn"); - std::string expected - { - "lambda3-searchn - the Local Aligner for Massive Biological DatA\n" - "===============================================================\n" - " lambda3 searchn [OPTIONS] -q QUERY.fasta -i INDEX.lambda [-o output.m8]\n" - " Try -h or --help for more information.\n" - }; - ASSERT_EQ(result.exit_code, 0); - ASSERT_EQ(result.out, expected); - ASSERT_EQ(result.err, std::string{}); -} - -TEST_F(search_test, searchp_no_options) -{ - cli_test_result result = execute_app("lambda3", "searchp"); - std::string expected - { - "lambda3-searchp - the Local Aligner for Massive Biological DatA\n" - "===============================================================\n" - " lambda3 searchp [OPTIONS] -q QUERY.fasta -i INDEX.lambda [-o output.m8]\n" - " Try -h or --help for more information.\n" - }; - ASSERT_EQ(result.exit_code, 0); - ASSERT_EQ(result.out, expected); - ASSERT_EQ(result.err, std::string{}); -} - -TEST_F(search_test, searchbs_no_options) -{ - cli_test_result result = execute_app("lambda3", "searchbs"); - std::string expected - { - "lambda3-searchbs - the Local Aligner for Massive Biological DatA\n" - "================================================================\n" - " lambda3 searchbs [OPTIONS] -q QUERY.fasta -i INDEX.lambda [-o output.m8]\n" - " Try -h or --help for more information.\n" - }; - ASSERT_EQ(result.exit_code, 0); - ASSERT_EQ(result.out, expected); - ASSERT_EQ(result.err, std::string{}); -} - -// BLASTN - -TEST_F(search_test, blastn_fm_m0) -{ - run_search_test("mkindexn", "db_nucl.fasta.gz", "db_nucl_fm.fasta.gz.lba", "fm", "", "searchn", - "queries_nucl.fasta.gz", "none", "output_blastn_fm.m0", "m0", "output_blastn_fm.m0"); -} - -TEST_F(search_test, blastn_fm_m8) -{ - run_search_test("mkindexn", "db_nucl.fasta.gz", "db_nucl_fm.fasta.gz.lba", "fm", "", "searchn", - "queries_nucl.fasta.gz", "none", "output_blastn_fm.m8", "m8", "output_blastn_fm.m8"); -} - -TEST_F(search_test, blastn_fm_m9) -{ - run_search_test("mkindexn", "db_nucl.fasta.gz", "db_nucl_fm.fasta.gz.lba", "fm", "", "searchn", - "queries_nucl.fasta.gz", "none", "output_blastn_fm.m9", "m9", "output_blastn_fm.m9"); -} - -TEST_F(search_test, blastn_fm_m9_gz) -{ - run_search_test("mkindexn", "db_nucl.fasta.gz", "db_nucl_fm.fasta.gz.lba", "fm", "", "searchn", - "queries_nucl.fasta.gz", "none", "output_blastn_fm.m9.gz", "m9_gz", "output_blastn_fm.m9"); -} - -TEST_F(search_test, blastn_fm_sam) -{ - run_search_test("mkindexn", "db_nucl.fasta.gz", "db_nucl_fm.fasta.gz.lba", "fm", "", "searchn", - "queries_nucl.fasta.gz", "none", "output_blastn_fm.sam", "sam", "output_blastn_fm.sam"); -} - -TEST_F(search_test, blastn_fm_bam) -{ - run_search_test("mkindexn", "db_nucl.fasta.gz", "db_nucl_fm.fasta.gz.lba", "fm", "", "searchn", - "queries_nucl.fasta.gz", "none", "output_blastn_fm.bam", "bam", "output_blastn_fm.bam"); -} - -// BLASTN bisulfite mode - -TEST_F(search_test, blastn_bs_fm_m0) -{ - run_search_test("mkindexbs", "db_nucl_bs.fasta.gz", "db_nucl_bs_fm.fasta.gz.lba", "fm", "", "searchbs", - "queries_nucl_bs.fasta.gz", "none", "output_blastn_bs_fm.m0", "m0", "output_blastn_bs_fm.m0"); -} - -TEST_F(search_test, blastn_bs_fm_m8) -{ - run_search_test("mkindexbs", "db_nucl_bs.fasta.gz", "db_nucl_bs_fm.fasta.gz.lba", "fm", "", "searchbs", - "queries_nucl_bs.fasta.gz", "none", "output_blastn_bs_fm.m8", "m8", "output_blastn_bs_fm.m8"); -} - -TEST_F(search_test, blastn_bs_fm_m9) -{ - run_search_test("mkindexbs", "db_nucl_bs.fasta.gz", "db_nucl_bs_fm.fasta.gz.lba", "fm", "", "searchbs", - "queries_nucl_bs.fasta.gz", "none", "output_blastn_bs_fm.m9", "m9", "output_blastn_bs_fm.m9"); -} - -TEST_F(search_test, blastn_bs_fm_m9_gz) -{ - run_search_test("mkindexbs", "db_nucl_bs.fasta.gz", "db_nucl_bs_fm.fasta.gz.lba", "fm", "", "searchbs", - "queries_nucl_bs.fasta.gz", "none", "output_blastn_bs_fm.m9.gz", "m9_gz", "output_blastn_bs_fm.m9"); -} - -TEST_F(search_test, blastn_bs_fm_sam) -{ - run_search_test("mkindexbs", "db_nucl_bs.fasta.gz", "db_nucl_bs_fm.fasta.gz.lba", "fm", "", "searchbs", - "queries_nucl_bs.fasta.gz", "none", "output_blastn_bs_fm.sam", "sam", "output_blastn_bs_fm.sam"); -} - -TEST_F(search_test, blastn_bs_fm_bam) -{ - run_search_test("mkindexbs", "db_nucl_bs.fasta.gz", "db_nucl_bs_fm.fasta.gz.lba", "fm", "", "searchbs", - "queries_nucl_bs.fasta.gz", "none", "output_blastn_bs_fm.bam", "bam", "output_blastn_bs_fm.bam"); -} - -// BLASTP - -TEST_F(search_test, blastp_fm_m0) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "none", "output_blastp_fm.m0", "m0", "output_blastp_fm.m0"); -} - -TEST_F(search_test, blastp_fm_m8) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "none", "output_blastp_fm.m8", "m8", "output_blastp_fm.m8"); -} - -TEST_F(search_test, blastp_fm_m9) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "none", "output_blastp_fm.m9", "m9", "output_blastp_fm.m9"); -} - -TEST_F(search_test, blastp_fm_m9_gz) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "none", "output_blastp_fm.m9.gz", "m9_gz", "output_blastp_fm.m9"); -} - -TEST_F(search_test, blastp_fm_sam) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "none", "output_blastp_fm.sam", "sam", "output_blastp_fm.sam"); -} - -TEST_F(search_test, blastp_fm_bam) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "none", "output_blastp_fm.bam", "bam", "output_blastp_fm.bam"); -} - -// BLASTX - -TEST_F(search_test, blastx_fm_m0) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "none", "output_blastx_fm.m0", "m0", "output_blastx_fm.m0"); -} - -TEST_F(search_test, blastx_fm_m8) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "none", "output_blastx_fm.m8", "m8", "output_blastx_fm.m8"); -} - -TEST_F(search_test, blastx_fm_m9) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "none", "output_blastx_fm.m9", "m9", "output_blastx_fm.m9"); -} - -TEST_F(search_test, blastx_fm_m9_gz) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "none", "output_blastx_fm.m9.gz", "m9_gz", "output_blastx_fm.m9"); -} - -TEST_F(search_test, blastx_fm_sam) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "none", "output_blastx_fm.sam", "sam", "output_blastx_fm.sam"); -} - -TEST_F(search_test, blastx_fm_bam) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "none", "output_blastx_fm.bam", "bam", "output_blastx_fm.bam"); -} - -// TBLASTN - -TEST_F(search_test, tblastn_fm_m0) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "none", "output_tblastn_fm.m0", "m0", "output_tblastn_fm.m0"); -} - -TEST_F(search_test, tblastn_fm_m8) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "none", "output_tblastn_fm.m8", "m8", "output_tblastn_fm.m8"); -} - -TEST_F(search_test, tblastn_fm_m9) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "none", "output_tblastn_fm.m9", "m9", "output_tblastn_fm.m9"); -} - -TEST_F(search_test, tblastn_fm_m9_gz) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "none", "output_tblastn_fm.m9.gz", "m9_gz", "output_tblastn_fm.m9"); -} - -TEST_F(search_test, tblastn_fm_sam) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "none", "output_tblastn_fm.sam", "sam", "output_tblastn_fm.sam"); -} - -TEST_F(search_test, tblastn_fm_bam) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "none", "output_tblastn_fm.bam", "bam", "output_tblastn_fm.bam"); -} - -// TBLASTX - -TEST_F(search_test, tblastx_fm_m0) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "none", "output_tblastx_fm.m0", "m0", "output_tblastx_fm.m0"); -} - -TEST_F(search_test, tblastx_fm_m8) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "none", "output_tblastx_fm.m8", "m8", "output_tblastx_fm.m8"); -} - -TEST_F(search_test, tblastx_fm_m9) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "none", "output_tblastx_fm.m9", "m9", "output_tblastx_fm.m9"); -} - -TEST_F(search_test, tblastx_fm_m9_gz) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "none", "output_tblastx_fm.m9.gz", "m9_gz", "output_tblastx_fm.m9"); -} - -TEST_F(search_test, tblastx_fm_sam) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "none", "output_tblastx_fm.sam", "sam", "output_tblastx_fm.sam"); -} - -TEST_F(search_test, tblastx_fm_bam) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_nucl_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "none", "output_tblastx_fm.bam", "bam", "output_tblastx_fm.bam"); -} - -// Search with bi-directional index - -#if LAMBDA_WITH_BIFM - -// TEST_F(search_test, blastn_bifm_m8) -// { -// run_search_test("mkindexn", "db_nucl.fasta.gz", "db_nucl_bifm.fasta.gz.lba", "bifm", "", "searchn", -// "queries_nucl.fasta.gz", "none", "output_blastn_bifm.m8", "m8", "output_blastn_fm.m8"); -// } -// -// TEST_F(search_test, blastn_bifm_sam) -// { -// run_search_test("mkindexn", "db_nucl.fasta.gz", "db_nucl_bifm.fasta.gz.lba", "bifm", "", "searchn", -// "queries_nucl.fasta.gz", "none", "output_blastn_bifm.sam", "sam", "output_blastn_fm.sam"); -// } - -TEST_F(search_test, blastn_bs_bifm_m8) -{ - run_search_test("mkindexbs", "db_nucl_bs.fasta.gz", "db_nucl_bs_bifm.fasta.gz.lba", "bifm", "", "searchbs", - "queries_nucl_bs.fasta.gz", "none", "output_blastn_bs_bifm.m8", "m8", "output_blastn_bs_fm.m8"); -} - -TEST_F(search_test, blastn_bs_bifm_sam) -{ - run_search_test("mkindexbs", "db_nucl_bs.fasta.gz", "db_nucl_bs_bifm.fasta.gz.lba", "bifm", "", "searchbs", - "queries_nucl_bs.fasta.gz", "none", "output_blastn_bs_bifm.sam", "sam", "output_blastn_bs_fm.sam"); -} - -TEST_F(search_test, blastp_bifm_m8) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_bifm.fasta.gz.lba", "bifm", "li10", "searchp", - "queries_prot.fasta.gz", "none", "output_blastp_bifm.m8", "m8", "output_blastp_fm.m8"); -} - -TEST_F(search_test, blastp_bifm_sam) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_bifm.fasta.gz.lba", "bifm", "li10", "searchp", - "queries_prot.fasta.gz", "none", "output_blastp_bifm.sam", "sam", "output_blastp_fm.sam"); -} - -TEST_F(search_test, blastx_bifm_m8) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_bifm.fasta.gz.lba", "bifm", "li10", "searchp", - "queries_nucl.fasta.gz", "none", "output_blastx_bifm.m8", "m8", "output_blastx_fm.m8"); -} - -TEST_F(search_test, blastx_bifm_sam) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_bifm.fasta.gz.lba", "bifm", "li10", "searchp", - "queries_nucl.fasta.gz", "none", "output_blastx_bifm.sam", "sam", "output_blastx_fm.sam"); -} - -TEST_F(search_test, tblastn_bifm_m8) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_bifm.fasta.gz.lba", "bifm", "li10", "searchp", - "queries_prot.fasta.gz", "none", "output_tblastn_bifm.m8", "m8", "output_tblastn_fm.m8"); -} - -TEST_F(search_test, tblastn_bifm_sam) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_bifm.fasta.gz.lba", "bifm", "li10", "searchp", - "queries_prot.fasta.gz", "none", "output_tblastn_bifm.sam", "sam", "output_tblastn_fm.sam"); -} - -TEST_F(search_test, tblastx_bifm_m8) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_bifm.fasta.gz.lba", "bifm", "li10", "searchp", - "queries_nucl.fasta.gz", "none", "output_tblastx_bifm.m8", "m8", "output_tblastx_fm.m8"); -} - -TEST_F(search_test, tblastx_bifm_sam) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_bifm.fasta.gz.lba", "bifm", "li10", "searchp", - "queries_nucl.fasta.gz", "none", "output_tblastx_bifm.sam", "sam", "output_tblastx_fm.sam"); -} - -#endif - -// Fast mode - -TEST_F(search_test, blastn_fm_fast_m8) -{ - run_search_test("mkindexn", "db_nucl.fasta.gz", "db_nucl_fm.fasta.gz.lba", "fm", "", "searchn", - "queries_nucl.fasta.gz", "fast", "output_blastn_fm_fast.m8", "m8", "output_blastn_fm_fast.m8"); -} - -TEST_F(search_test, blastn_fm_fast_sam) -{ - run_search_test("mkindexn", "db_nucl.fasta.gz", "db_nucl_fm.fasta.gz.lba", "fm", "", "searchn", - "queries_nucl.fasta.gz", "fast", "output_blastn_fm_fast.sam", "sam", "output_blastn_fm_fast.sam"); -} - -TEST_F(search_test, blastn_bs_fm_fast_m8) -{ - run_search_test("mkindexbs", "db_nucl_bs.fasta.gz", "db_nucl_bs_fm.fasta.gz.lba", "fm", "", "searchbs", - "queries_nucl_bs.fasta.gz", "fast", "output_blastn_bs_fm_fast.m8", "m8", "output_blastn_bs_fm_fast.m8"); -} - -TEST_F(search_test, blastn_bs_fm_fast_sam) -{ - run_search_test("mkindexbs", "db_nucl_bs.fasta.gz", "db_nucl_bs_fm.fasta.gz.lba", "fm", "", "searchbs", - "queries_nucl_bs.fasta.gz", "fast", "output_blastn_bs_fm_fast.sam", "sam", "output_blastn_bs_fm_fast.sam"); -} - -TEST_F(search_test, blastp_fm_fast_m8) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "fast", "output_blastp_fm_fast.m8", "m8", "output_blastp_fm_fast.m8"); -} - -TEST_F(search_test, blastp_fm_fast_sam) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "fast", "output_blastp_fm_fast.sam", "sam", "output_blastp_fm_fast.sam"); -} - -TEST_F(search_test, blastx_fm_fast_m8) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "fast", "output_blastx_fm_fast.m8", "m8", "output_blastx_fm_fast.m8"); -} - -TEST_F(search_test, blastx_fm_fast_sam) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "fast", "output_blastx_fm_fast.sam", "sam", "output_blastx_fm_fast.sam"); -} - -TEST_F(search_test, tblastn_fm_fast_m8) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "fast", "output_tblastn_fm_fast.m8", "m8", "output_tblastn_fm_fast.m8"); -} - -TEST_F(search_test, tblastn_fm_fast_sam) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "fast", "output_tblastn_fm_fast.sam", "sam", "output_tblastn_fm_fast.sam"); -} - -TEST_F(search_test, tblastx_fm_fast_m8) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "fast", "output_tblastx_fm_fast.m8", "m8", "output_tblastx_fm_fast.m8"); -} - -TEST_F(search_test, tblastx_fm_fast_sam) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "fast", "output_tblastx_fm_fast.sam", "sam", "output_tblastx_fm_fast.sam"); -} - -// Sensitive mode - -TEST_F(search_test, blastn_fm_sensitive_m8) -{ - run_search_test("mkindexn", "db_nucl.fasta.gz", "db_nucl_fm.fasta.gz.lba", "fm", "", "searchn", - "queries_nucl.fasta.gz", "sensitive", "output_blastn_fm_sensitive.m8", "m8", "output_blastn_fm_sensitive.m8"); -} - -TEST_F(search_test, blastn_fm_sensitive_sam) -{ - run_search_test("mkindexn", "db_nucl.fasta.gz", "db_nucl_fm.fasta.gz.lba", "fm", "", "searchn", - "queries_nucl.fasta.gz", "sensitive", "output_blastn_fm_sensitive.sam", "sam", "output_blastn_fm_sensitive.sam"); -} - -TEST_F(search_test, blastn_bs_fm_sensitive_m8) -{ - run_search_test("mkindexbs", "db_nucl_bs.fasta.gz", "db_nucl_bs_fm.fasta.gz.lba", "fm", "", "searchbs", - "queries_nucl_bs.fasta.gz", "sensitive", "output_blastn_bs_fm_sensitive.m8", "m8", "output_blastn_bs_fm_sensitive.m8"); -} - -TEST_F(search_test, blastn_bs_fm_sensitive_sam) -{ - run_search_test("mkindexbs", "db_nucl_bs.fasta.gz", "db_nucl_bs_fm.fasta.gz.lba", "fm", "", "searchbs", - "queries_nucl_bs.fasta.gz", "sensitive", "output_blastn_bs_fm_sensitive.sam", "sam", "output_blastn_bs_fm_sensitive.sam"); -} - -TEST_F(search_test, blastp_fm_sensitive_m8) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "sensitive", "output_blastp_fm_sensitive.m8", "m8", "output_blastp_fm_sensitive.m8"); -} - -TEST_F(search_test, blastp_fm_sensitive_sam) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "sensitive", "output_blastp_fm_sensitive.sam", "sam", "output_blastp_fm_sensitive.sam"); -} - -TEST_F(search_test, blastx_fm_sensitive_m8) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "sensitive", "output_blastx_fm_sensitive.m8", "m8", "output_blastx_fm_sensitive.m8"); -} - -TEST_F(search_test, blastx_fm_sensitive_sam) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "sensitive", "output_blastx_fm_sensitive.sam", "sam", "output_blastx_fm_sensitive.sam"); -} - -TEST_F(search_test, tblastn_fm_sensitive_m8) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "sensitive", "output_tblastn_fm_sensitive.m8", "m8", "output_tblastn_fm_sensitive.m8"); -} - -TEST_F(search_test, tblastn_fm_sensitive_sam) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "sensitive", "output_tblastn_fm_sensitive.sam", "sam", "output_tblastn_fm_sensitive.sam"); -} - -TEST_F(search_test, tblastx_fm_sensitive_m8) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "sensitive", "output_tblastx_fm_sensitive.m8", "m8", "output_tblastx_fm_sensitive.m8"); -} - -TEST_F(search_test, tblastx_fm_sensitive_sam) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "sensitive", "output_tblastx_fm_sensitive.sam", "sam", "output_tblastx_fm_sensitive.sam"); -} - -// pairs default mode - -TEST_F(search_test, blastn_fm_pairs_default_m8) -{ - run_search_test("mkindexn", "db_nucl.fasta.gz", "db_nucl_fm.fasta.gz.lba", "fm", "", "searchn", - "queries_nucl.fasta.gz", "pairs-default", "output_blastn_fm_pairs_default.m8", "m8", "output_blastn_fm_pairs_default.m8"); -} - -TEST_F(search_test, blastn_fm_pairs_default_sam) -{ - run_search_test("mkindexn", "db_nucl.fasta.gz", "db_nucl_fm.fasta.gz.lba", "fm", "", "searchn", - "queries_nucl.fasta.gz", "pairs-default", "output_blastn_fm_pairs_default.sam", "sam", "output_blastn_fm_pairs_default.sam"); -} - -TEST_F(search_test, blastn_bs_fm_pairs_default_m8) -{ - run_search_test("mkindexbs", "db_nucl_bs.fasta.gz", "db_nucl_bs_fm.fasta.gz.lba", "fm", "", "searchbs", - "queries_nucl_bs.fasta.gz", "pairs-default", "output_blastn_bs_fm_pairs_default.m8", "m8", "output_blastn_bs_fm_pairs_default.m8"); -} - -TEST_F(search_test, blastn_bs_fm_pairs_default_sam) -{ - run_search_test("mkindexbs", "db_nucl_bs.fasta.gz", "db_nucl_bs_fm.fasta.gz.lba", "fm", "", "searchbs", - "queries_nucl_bs.fasta.gz", "pairs-default", "output_blastn_bs_fm_pairs_default.sam", "sam", "output_blastn_bs_fm_pairs_default.sam"); -} - -TEST_F(search_test, blastp_fm_pairs_default_m8) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "pairs-default", "output_blastp_fm_pairs_default.m8", "m8", "output_blastp_fm_pairs_default.m8"); -} - -TEST_F(search_test, blastp_fm_pairs_default_sam) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "pairs-default", "output_blastp_fm_pairs_default.sam", "sam", "output_blastp_fm_pairs_default.sam"); -} - -TEST_F(search_test, blastx_fm_pairs_default_m8) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "pairs-default", "output_blastx_fm_pairs_default.m8", "m8", "output_blastx_fm_pairs_default.m8"); -} - -TEST_F(search_test, blastx_fm_pairs_default_sam) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "pairs-default", "output_blastx_fm_pairs_default.sam", "sam", "output_blastx_fm_pairs_default.sam"); -} - -TEST_F(search_test, tblastn_fm_pairs_default_m8) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "pairs-default", "output_tblastn_fm_pairs_default.m8", "m8", "output_tblastn_fm_pairs_default.m8"); -} - -TEST_F(search_test, tblastn_fm_pairs_default_sam) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "pairs-default", "output_tblastn_fm_pairs_default.sam", "sam", "output_tblastn_fm_pairs_default.sam"); -} - -TEST_F(search_test, tblastx_fm_pairs_default_m8) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "pairs-default", "output_tblastx_fm_pairs_default.m8", "m8", "output_tblastx_fm_pairs_default.m8"); -} - -TEST_F(search_test, tblastx_fm_pairs_default_sam) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "pairs-default", "output_tblastx_fm_pairs_default.sam", "sam", "output_tblastx_fm_pairs_default.sam"); -} - -// pairs sensitive mode - -TEST_F(search_test, blastn_fm_pairs_sensitive_m8) -{ - run_search_test("mkindexn", "db_nucl.fasta.gz", "db_nucl_fm.fasta.gz.lba", "fm", "", "searchn", - "queries_nucl.fasta.gz", "pairs-sensitive", "output_blastn_fm_pairs_sensitive.m8", "m8", "output_blastn_fm_pairs_sensitive.m8"); -} - -TEST_F(search_test, blastn_fm_pairs_sensitive_sam) -{ - run_search_test("mkindexn", "db_nucl.fasta.gz", "db_nucl_fm.fasta.gz.lba", "fm", "", "searchn", - "queries_nucl.fasta.gz", "pairs-sensitive", "output_blastn_fm_pairs_sensitive.sam", "sam", "output_blastn_fm_pairs_sensitive.sam"); -} - -TEST_F(search_test, blastn_bs_fm_pairs_sensitive_m8) -{ - run_search_test("mkindexbs", "db_nucl_bs.fasta.gz", "db_nucl_bs_fm.fasta.gz.lba", "fm", "", "searchbs", - "queries_nucl_bs.fasta.gz", "pairs-sensitive", "output_blastn_bs_fm_pairs_sensitive.m8", "m8", "output_blastn_bs_fm_pairs_sensitive.m8"); -} - -TEST_F(search_test, blastn_bs_fm_pairs_sensitive_sam) -{ - run_search_test("mkindexbs", "db_nucl_bs.fasta.gz", "db_nucl_bs_fm.fasta.gz.lba", "fm", "", "searchbs", - "queries_nucl_bs.fasta.gz", "pairs-sensitive", "output_blastn_bs_fm_pairs_sensitive.sam", "sam", "output_blastn_bs_fm_pairs_sensitive.sam"); -} - -TEST_F(search_test, blastp_fm_pairs_sensitive_m8) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "pairs-sensitive", "output_blastp_fm_pairs_sensitive.m8", "m8", "output_blastp_fm_pairs_sensitive.m8"); -} - -TEST_F(search_test, blastp_fm_pairs_sensitive_sam) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "pairs-sensitive", "output_blastp_fm_pairs_sensitive.sam", "sam", "output_blastp_fm_pairs_sensitive.sam"); -} - -TEST_F(search_test, blastx_fm_pairs_sensitive_m8) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "pairs-sensitive", "output_blastx_fm_pairs_sensitive.m8", "m8", "output_blastx_fm_pairs_sensitive.m8"); -} - -TEST_F(search_test, blastx_fm_pairs_sensitive_sam) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "pairs-sensitive", "output_blastx_fm_pairs_sensitive.sam", "sam", "output_blastx_fm_pairs_sensitive.sam"); -} - -TEST_F(search_test, tblastn_fm_pairs_sensitive_m8) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "pairs-sensitive", "output_tblastn_fm_pairs_sensitive.m8", "m8", "output_tblastn_fm_pairs_sensitive.m8"); -} - -TEST_F(search_test, tblastn_fm_pairs_sensitive_sam) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_prot.fasta.gz", "pairs-sensitive", "output_tblastn_fm_pairs_sensitive.sam", "sam", "output_tblastn_fm_pairs_sensitive.sam"); -} - -TEST_F(search_test, tblastx_fm_pairs_sensitive_m8) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "pairs-sensitive", "output_tblastx_fm_pairs_sensitive.m8", "m8", "output_tblastx_fm_pairs_sensitive.m8"); -} - -TEST_F(search_test, tblastx_fm_pairs_sensitive_sam) -{ - run_search_test("mkindexp", "db_nucl.fasta.gz", "db_trans_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "pairs-sensitive", "output_tblastx_fm_pairs_sensitive.sam", "sam", "output_tblastx_fm_pairs_sensitive.sam"); -} - -// special options - -TEST_F(search_test, lazy_loading) -{ - run_search_test("mkindexp", "db_prot.fasta.gz", "db_prot_fm.fasta.gz.lba", "fm", "li10", "searchp", - "queries_nucl.fasta.gz", "none", "output_blastx_fm_lazy.m8", "m8", "output_blastx_fm.m8", - "--lazy-query", "1", "-t", "2"); -} diff --git a/test/cmake/app_datasources.cmake b/test/cmake/app_datasources.cmake deleted file mode 100644 index 76bb655b2..000000000 --- a/test/cmake/app_datasources.cmake +++ /dev/null @@ -1,92 +0,0 @@ -include (ExternalProject) - -# Example call: -# -# ```cmake -# declare_datasource ( -# FILE pdb100d.ent.gz # build/data/pdb100d.ent.gz -# URL ftp://ftp.wwpdb.org/pub/pdb/data/structures/divided/pdb/00/pdb100d.ent.gz # 16KiloByte -# URL_HASH SHA256=c2b8f884568b07f58519966e256e2f3aa440508e8013bd10e0ee338e138e62a0) -# ``` -# -# Options: -# -# declare_datasource (FILE URL [...] [URL_HASH =] [