Kalign Multiple Sequence Alignment

repository·main·Indexed 41 days ago

https://github.com/timolassmann/kalign

A high-performance multiple sequence alignment (MSA) tool for protein, DNA, and RNA biological sequences. It features a progressive alignment approach with multi-threading support and four mode presets (fast, default, recall, and accurate) to balance speed and precision. The project provides a C/C++ engine, a command-line interface, and a Python wrapper (kalign-python v3.6.0) with integrations for Biopython and scikit-bio.

Tokens
4.5K
Snippets
20
Records
20
Agent score
49%

What's inside Kalign

  1. Understand Kalign alignment modes

    main

    Kalign provides four optimized modes for alignment. Explicit parameters (like ensemble or gap_open) will override these defaults.

    ModePython ConstantCLI FlagDescription
    fastkalign.MODE_FAST--mode fastSingle run, fastest.
    defaultkalign.MODE_DEFAULT--mode defaultSingle run with consistency anchors. Best general-purpose.
    recallkalign.MODE_RECALL--mode recallEnsemble, optimized for recall.
    accuratekalign.MODE_ACCURATE--mode accurateEnsemble, highest precision.

    Use mode="accurate" or set ensemble=5 to achieve high-precision ensemble alignments.

    import kalign
    
    # Using constants
    aligned = kalign.align(sequences, mode=kalign.MODE_ACCURATE)
  2. Configure Kalign alignment modes

    main

    Kalign provides four mode presets to balance speed and accuracy:

    • fast: Single run, fastest.
    • default: Single run with consistency anchors (default).
    • recall: Ensemble mode, optimized for recall.
    • accurate: Ensemble mode, highest precision.
    kalign --mode accurate -i sequences.fa -o aligned.fa
  3. Use Ensemble mode and confidence scores

    main

    Ensemble mode runs multiple alignments with varied parameters and combines them via POAR (Pairs of Aligned Residues) consensus. This is best used by setting mode="accurate" or specifying an ensemble count (e.g., 3-5).

    Confidence Scores:

    • Column confidence: Average agreement across ensemble runs [0..1]. Accessible via result.column_confidence.
    • Residue confidence: Per-sequence, per-position agreement [0..1]. Accessible via result.residue_confidence.

    POAR Save/Load Pattern: To avoid re-running expensive ensemble alignments when experimenting with consensus thresholds, save the POAR table.

    1. Save POAR: kalign.align_file_to_file(..., ensemble=5, save_poar="consensus.poar")
    2. Load POAR: kalign.align_file_to_file(..., load_poar="consensus.poar", min_support=3)
    import kalign
    
    # Run ensemble and access confidence
    result = kalign.align_from_file("proteins.fasta", ensemble=5)
    print(result.column_confidence[:10])   # e.g. [0.93, 0.87, 1.0, ...]
    print(result.residue_confidence[0][:10])  # e.g. [0.95, 0.90, 1.0, ...]
  4. Install kalign-python

    main

    Install the core package using pip:

    pip install kalign-python

    For ecosystem integration, you can install optional dependencies:

    • Biopython integration (for fmt="biopython" and I/O helpers): pip install kalign-python[biopython]
    • scikit-bio integration (for fmt="skbio"): pip install kalign-python[skbio]
    • I/O helpers (requires Biopython): pip install kalign-python[io]
    • Downstream analysis (pandas + matplotlib): pip install kalign-python[analysis]
    • All features: pip install kalign-python[all]
    pip install kalign-python
  5. Install Kalign from source

    main

    To build Kalign from source, you need a C compiler (GCC or Clang) and CMake 3.18+.

    By default, Kalign uses a built-in thread pool for parallelization (requires pthreads). If you prefer to use OpenMP instead, configure CMake with -DUSE_OPENMP=ON -DUSE_THREADPOOL=OFF.

    # Standard build
    mkdir build && cd build
    cmake ..
    make
    make test
    make install
    
    # Build with OpenMP instead of built-in thread pool
    cmake -DUSE_OPENMP=ON -DUSE_THREADPOOL=OFF ..
  6. Use Kalign CLI for sequence alignment

    main

    Kalign is used to align protein, DNA, and RNA sequences. The basic syntax is kalign -i <input> -o <output>.

    Kalign supports reading from stdin by using -i - and can combine multiple input files by providing them as positional arguments.

    # Align sequences (default mode)
    kalign -i sequences.fa -o aligned.fa
    
    # Fast mode
    kalign --mode fast -i sequences.fa -o aligned.fa
    
    # Accurate mode (ensemble)
    kalign --mode accurate -i sequences.fa -o aligned.fa
    
    # Read from stdin
    cat input.fa | kalign -i - -o aligned.fa
    
    # Combine multiple input files
    kalign seqsA.fa seqsB.fa -o combined.fa
  7. Use kalign.align() for sequence alignment

    main

    The kalign.align() function performs multiple sequence alignment on a list of strings.

    Parameters:

    • sequences (list of str): The sequences to align.
    • mode (str, optional): One of "fast", "default", "recall", or "accurate". Defaults to None ("default").
    • seq_type (str, optional): "auto" (default), "dna", "rna", "protein", "divergent", or "internal".
    • gap_open (float, optional): Positive float for gap opening penalty.
    • gap_extend (float, optional): Positive float for gap extension penalty.
    • terminal_gap_extend (float, optional): Penalty for gaps at the ends.
    • n_threads (int, optional): Number of threads to use.
    • refine (str, optional): Refinement mode: "none" (default), "all", "confident", or "inline".
    • ensemble (int, optional): Number of ensemble runs (0 = off, try 3-5).
    • min_support (float, optional): Explicit consensus threshold (0 = auto).
    • fmt (str, optional): Output format: "plain" (default), "biopython", or "skbio".
    • ids (list of str, optional): Sequence identifiers (required for biopython/skbio output).

    Returns: A list of aligned strings (if fmt="plain"), a Bio.Align.MultipleSeqAlignment (if fmt="biopython"), or a skbio.TabularMSA (if fmt="skbio").

    import kalign
    
    sequences = [
        "ATCGATCGATCG",
        "ATCGTCGATCG",
        "ATCGATCATCG"
    ]
    
    # Default mode
    aligned = kalign.align(sequences)
    
    # Fast mode
    aligned = kalign.align(sequences, mode="fast")
    
    # Accurate mode
    aligned = kalign.align(sequences, mode="accurate")
  8. Link Kalign into a C/C++ project

    main

    You can integrate Kalign into your C/C++ projects using CMake.

    # Option 1: Using find_package
    find_package(kalign)
    target_link_libraries(<target> kalign::kalign)
    
    # Option 2: Using add_subdirectory
    add_subdirectory(<path>/kalign EXCLUDE_FROM_ALL)
    target_link_libraries(<target> kalign::kalign)
  9. Align sequences from a file with kalign.align_from_file()

    main

    Use kalign.align_from_file() to align sequences directly from FASTA, MSF, or Clustal files. It returns an AlignedSequences object containing .names and .sequences.

    Key Parameters:

    • input_file (str): Path to the input file.
    • seq_type (str): Sequence type (e.g., "protein").
    • mode (str): Alignment mode ("fast", "default", "recall", "accurate").
    • ensemble (int): Number of ensemble runs.
    • min_support (float): Consensus threshold.
    • save_poar (str): Path to save the POAR consensus table.
    • load_poar (str): Path to load a pre-computed POAR table.
    • refine (str): Refinement mode.
    import kalign
    
    # Basic usage
    result = kalign.align_from_file("sequences.fasta", seq_type="protein")
    for name, seq in zip(result.names, result.sequences):
        print(f"{name}: {seq}")
    
    # Advanced usage with ensemble and POAR
    result = kalign.align_from_file(
        "input.fasta",
        mode="accurate",
        ensemble=5,
        min_support=0,
        save_poar="consensus.poar"
    )
  10. Write alignments to files with kalign.write_alignment()

    main

    Write aligned sequences to a file in various formats.

    Parameters:

    • aligned: The alignment object/sequences to write.
    • output_file (str): Destination path.
    • format (str): Supported formats are "fasta", "clustal", "stockholm", and "phylip". (Note: non-FASTA formats require Biopython).
    • ids (list of str, optional): Sequence identifiers.
    • column_confidence (array, optional): Per-column confidence scores.
    • residue_confidence (array, optional): Per-residue confidence scores.
    import kalign
    
    # Basic FASTA write
    kalign.write_alignment(aligned, "output.fasta", format="fasta", ids=ids)
    
    # Stockholm write with confidence
    kalign.write_alignment(
        result.sequences, "output.sto", format="stockholm",
        ids=result.names,
        column_confidence=result.column_confidence,
        residue_confidence=result.residue_confidence,
    )