Skip to content

kaptive.core.pairwise

Pairwise sequence alignment algorithms and containers.

This module provides high-performance pairwise sequence alignment capabilities using a parallelized, banded Smith-Waterman-Gotoh dynamic programming algorithm with affine gap penalties. Alignment results are stored in memory-efficient Structure-of-Arrays (SoA) containers (PairwiseAlignments) or scalar records (PairwiseAlignment).

Key Classes

Classes:

  • PairwiseAligner –

    A high-performance, batched pairwise sequence aligner.

  • PairwiseAlignment –

    A lightweight, immutable container for the results of a single pairwise sequence alignment.

  • PairwiseAlignments –

    A high-performance SoA container for the results of multiple pairwise alignments.

PairwiseAligner dataclass

PairwiseAligner(gap_open: int = 11, gap_extend: int = 1, k: int = 20)

A high-performance, batched pairwise sequence aligner.

Uses a parallelized, banded Smith-Waterman-Gotoh algorithm to align pairs of sequences.

Attributes:

  • gap_open (int) –

    Penalty for opening a new gap. Defaults to 11.

  • gap_extend (int) –

    Penalty for extending an existing gap. Defaults to 1.

  • k (int) –

    Bandwidth parameter (2*k+1 diagonals). Defaults to 20.

Methods:

  • __call__ –

    Perform pairwise alignment of query and target sequences.

  • align_seeds –

    Convenience method to extract and align specific sequence pairs mapped by seeds.

__call__

Perform pairwise alignment of query and target sequences.

Parameters:

  • queries

    (Sequences) –

    Collection of query sequences.

  • targets

    (Sequences) –

    Collection of target sequences (must match query batch size).

  • seeds

    (Seeds | None, default: None ) –

    Optional alignment seeds guiding diagonal alignment.

Returns:

  • PairwiseAlignments ( PairwiseAlignments ) –

    Alignment scores, statistics, and coordinates for each sequence pair.

Raises:

  • ValueError –

    If query and target batches have different numbers of sequences.

Source code in src/kaptive/core/pairwise.py
def __call__(self, queries: Sequences, targets: Sequences, seeds: Seeds | None = None) -> PairwiseAlignments:
    r"""Perform pairwise alignment of query and target sequences.

    Args:
        queries (Sequences): Collection of query sequences.
        targets (Sequences): Collection of target sequences (must match query batch size).
        seeds (Seeds | None): Optional alignment seeds guiding diagonal alignment.

    Returns:
        PairwiseAlignments: Alignment scores, statistics, and coordinates for each sequence pair.

    Raises:
        ValueError: If query and target batches have different numbers of sequences.
    """
    if len(queries.offsets) != len(targets.offsets):
        raise ValueError("Query and target batches must have the same number of sequences.")

    n = len(queries.offsets)
    if n == 0:
        return PairwiseAlignments.empty()

    # Handle the unified routing
    if seeds is not None:
        is_seeded = True
        offsets_arr = seeds.offsets
    else:
        is_seeded = False
        offsets_arr = np.zeros(n, dtype=np.int32)

    out_scores = np.empty(n, dtype=np.int32)
    out_matches = np.empty(n, dtype=np.int32)
    out_mismatches = np.empty(n, dtype=np.int32)
    out_gaps = np.empty(n, dtype=np.int32)
    out_q_starts = np.empty(n, dtype=np.int32)
    out_q_ends = np.empty(n, dtype=np.int32)
    out_t_starts = np.empty(n, dtype=np.int32)
    out_t_ends = np.empty(n, dtype=np.int32)

    _batched_banded_gotoh(
        queries.seqs,
        queries.offsets,
        queries.lengths,
        targets.seqs,
        targets.offsets,
        targets.lengths,
        _blosum62_matrix(),
        self.k,
        self.gap_open,
        self.gap_extend,
        is_seeded,
        offsets_arr,
        out_scores,
        out_matches,
        out_mismatches,
        out_gaps,
        out_q_starts,
        out_q_ends,
        out_t_starts,
        out_t_ends,
    )

    return PairwiseAlignments(
        out_scores,
        out_matches,
        out_mismatches,
        out_gaps,
        out_q_starts,
        out_q_ends,
        out_t_starts,
        out_t_ends,
    )

align_seeds

Convenience method to extract and align specific sequence pairs mapped by seeds.

Parameters:

  • queries

    (Sequences) –

    Full collection of query sequences.

  • targets

    (Sequences) –

    Full collection of target sequences.

  • seeds

    (Seeds) –

    Seed collection mapping specific query sequences to target sequences.

Returns:

  • PairwiseAlignments ( PairwiseAlignments ) –

    Alignment results parallel to the provided seeds.

Source code in src/kaptive/core/pairwise.py
def align_seeds(self, queries: Sequences, targets: Sequences, seeds: Seeds) -> PairwiseAlignments:
    r"""Convenience method to extract and align specific sequence pairs mapped by seeds.

    Args:
        queries (Sequences): Full collection of query sequences.
        targets (Sequences): Full collection of target sequences.
        seeds (Seeds): Seed collection mapping specific query sequences to target sequences.

    Returns:
        PairwiseAlignments: Alignment results parallel to the provided seeds.
    """
    paired_queries, paired_targets = seeds.extract_sequences(queries, targets)
    return self(paired_queries, paired_targets, seeds)

PairwiseAlignment dataclass

PairwiseAlignment(score: int, matches: int, mismatches: int, gaps: int, q_start: int, q_end: int, t_start: int, t_end: int)

A lightweight, immutable container for the results of a single pairwise sequence alignment.

This class holds summary statistics and coordinates for an alignment between a single query and target sequence. It is typically produced by indexing into a PairwiseAlignments collection.

Attributes:

  • score (int) –

    Final alignment score calculated using BLOSUM62 and gap penalties.

  • matches (int) –

    Total number of matching bases.

  • mismatches (int) –

    Total number of mismatched bases.

  • gaps (int) –

    Total number of gap characters (insertions or deletions).

  • q_start (int) –

    0-based start coordinate on query sequence (inclusive).

  • q_end (int) –

    0-based end coordinate on query sequence (exclusive).

  • t_start (int) –

    0-based start coordinate on target sequence (inclusive).

  • t_end (int) –

    0-based end coordinate on target sequence (exclusive).

pident property

pident: float

Calculate the percent identity of the aligned region.

Percent identity is defined as (matches / (matches + mismatches + gaps)) * 100.0.

Returns:

  • float ( float ) –

    Percent identity value between 0.0 and 100.0, or 0.0 if alignment length is zero.

PairwiseAlignments dataclass

PairwiseAlignments(scores: NDArray[int32], matches: NDArray[int32], mismatches: NDArray[int32], gaps: NDArray[int32], q_starts: NDArray[int32], q_ends: NDArray[int32], t_starts: NDArray[int32], t_ends: NDArray[int32])

              flowchart TD
              kaptive.core.pairwise.PairwiseAlignments[PairwiseAlignments]
              kaptive.core.collections.BatchedContainer[BatchedContainer]

                              kaptive.core.collections.BatchedContainer --> kaptive.core.pairwise.PairwiseAlignments
                


              click kaptive.core.pairwise.PairwiseAlignments href "" "kaptive.core.pairwise.PairwiseAlignments"
              click kaptive.core.collections.BatchedContainer href "" "kaptive.core.collections.BatchedContainer"
            

A high-performance SoA container for the results of multiple pairwise alignments.

This class stores alignment statistics in a Structure-of-Arrays (SoA) layout using 1D NumPy arrays.

Attributes:

  • scores (NDArray[int32]) –

    1D array of alignment scores.

  • matches (NDArray[int32]) –

    1D array of match counts.

  • mismatches (NDArray[int32]) –

    1D array of mismatch counts.

  • gaps (NDArray[int32]) –

    1D array of gap counts.

  • q_starts (NDArray[int32]) –

    1D array of query start coordinates.

  • q_ends (NDArray[int32]) –

    1D array of query end coordinates.

  • t_starts (NDArray[int32]) –

    1D array of target start coordinates.

  • t_ends (NDArray[int32]) –

    1D array of target end coordinates.

Methods:

  • __getitem__ –

    Access alignment results by index, slice, or boolean array mask.

  • __len__ –

    Return the number of alignments in the batch.

  • concat –

    Concatenate multiple PairwiseAlignments collections into a single batch.

  • empty –

    Create an empty PairwiseAlignments collection with zero-length int32 arrays.

  • from_dict –

    Deserialize a PairwiseAlignments batch from a dictionary of array-like data.

  • to_dict –

    Convert the alignment batch to a dictionary of NumPy arrays for serialization.

pidents property

pidents: NDArray[float64]

Calculate percent identity for all alignments in the batch in a vectorized manner.

Returns:

  • NDArray[float64] –

    npt.NDArray[np.float64]: 1D array of percent identity values.

__getitem__

Access alignment results by index, slice, or boolean array mask.

Parameters:

  • item

    (Any) –

    Integer index, slice, or boolean/integer array.

Returns:

Raises:

  • IndexError –

    If integer index is out of range.

Source code in src/kaptive/core/pairwise.py
def __getitem__(self, item: Any) -> PairwiseAlignment | PairwiseAlignments:
    r"""Access alignment results by index, slice, or boolean array mask.

    Args:
        item (Any): Integer index, slice, or boolean/integer array.

    Returns:
        PairwiseAlignment | PairwiseAlignments: Scalar record or sliced batch collection.

    Raises:
        IndexError: If integer index is out of range.
    """
    if isinstance(item, (int, np.integer)):
        if item < 0:
            item += len(self)
        if item < 0 or item >= len(self):
            raise IndexError("Batch index out of range")
        return PairwiseAlignment(
            score=int(self.scores[item]),
            matches=int(self.matches[item]),
            mismatches=int(self.mismatches[item]),
            gaps=int(self.gaps[item]),
            q_start=int(self.q_starts[item]),
            q_end=int(self.q_ends[item]),
            t_start=int(self.t_starts[item]),
            t_end=int(self.t_ends[item]),
        )
    return PairwiseAlignments(
        scores=self.scores[item],
        matches=self.matches[item],
        mismatches=self.mismatches[item],
        gaps=self.gaps[item],
        q_starts=self.q_starts[item],
        q_ends=self.q_ends[item],
        t_starts=self.t_starts[item],
        t_ends=self.t_ends[item],
    )

__len__

__len__() -> int

Return the number of alignments in the batch.

Returns:

  • int ( int ) –

    Total count of alignments.

Source code in src/kaptive/core/pairwise.py
def __len__(self) -> int:
    r"""Return the number of alignments in the batch.

    Returns:
        int: Total count of alignments.
    """
    return len(self.scores)

concat classmethod

concat(batches: Iterable[Self]) -> Self

Concatenate multiple PairwiseAlignments collections into a single batch.

Parameters:

Returns:

  • PairwiseAlignments ( Self ) –

    Single concatenated alignment collection.

Source code in src/kaptive/core/pairwise.py
@classmethod
def concat(cls, batches: Iterable[Self]) -> Self:  # type: ignore
    r"""Concatenate multiple PairwiseAlignments collections into a single batch.

    Args:
        batches (Iterable[PairwiseAlignments]): Iterable of alignment collections.

    Returns:
        PairwiseAlignments: Single concatenated alignment collection.
    """
    batches_list = list(batches)
    if not batches_list:
        return cls.empty()  # type: ignore
    return cls(
        scores=np.concatenate([b.scores for b in batches_list]),
        matches=np.concatenate([b.matches for b in batches_list]),
        mismatches=np.concatenate([b.mismatches for b in batches_list]),
        gaps=np.concatenate([b.gaps for b in batches_list]),
        q_starts=np.concatenate([b.q_starts for b in batches_list]),
        q_ends=np.concatenate([b.q_ends for b in batches_list]),
        t_starts=np.concatenate([b.t_starts for b in batches_list]),
        t_ends=np.concatenate([b.t_ends for b in batches_list]),
    )

empty classmethod

empty() -> PairwiseAlignments

Create an empty PairwiseAlignments collection with zero-length int32 arrays.

Returns:

Source code in src/kaptive/core/pairwise.py
@classmethod
def empty(cls) -> PairwiseAlignments:
    r"""Create an empty PairwiseAlignments collection with zero-length int32 arrays.

    Returns:
        PairwiseAlignments: Empty alignment collection.
    """
    return cls(
        np.empty(0, dtype=np.int32),
        np.empty(0, dtype=np.int32),
        np.empty(0, dtype=np.int32),
        np.empty(0, dtype=np.int32),
        np.empty(0, dtype=np.int32),
        np.empty(0, dtype=np.int32),
        np.empty(0, dtype=np.int32),
        np.empty(0, dtype=np.int32),
    )

from_dict classmethod

from_dict(d: dict[str, Any]) -> PairwiseAlignments

Deserialize a PairwiseAlignments batch from a dictionary of array-like data.

Parameters:

  • d

    (dict[str, Any]) –

    Dictionary containing alignment field arrays.

Returns:

  • PairwiseAlignments ( PairwiseAlignments ) –

    Deserialized pairwise alignments container.

Source code in src/kaptive/core/pairwise.py
@classmethod
def from_dict(cls, d: dict[str, Any]) -> PairwiseAlignments:
    r"""Deserialize a PairwiseAlignments batch from a dictionary of array-like data.

    Args:
        d (dict[str, Any]): Dictionary containing alignment field arrays.

    Returns:
        PairwiseAlignments: Deserialized pairwise alignments container.
    """
    return cls(
        np.array(d["scores"], dtype=np.int32),
        np.array(d["matches"], dtype=np.int32),
        np.array(d["mismatches"], dtype=np.int32),
        np.array(d["gaps"], dtype=np.int32),
        np.array(d["q_starts"], dtype=np.int32),
        np.array(d["q_ends"], dtype=np.int32),
        np.array(d["t_starts"], dtype=np.int32),
        np.array(d["t_ends"], dtype=np.int32),
    )

to_dict

to_dict() -> dict[str, NDArray[int32]]

Convert the alignment batch to a dictionary of NumPy arrays for serialization.

Returns:

  • dict[str, NDArray[int32]] –

    dict[str, npt.NDArray[np.int32]]: Dictionary mapping attribute names to arrays.

Source code in src/kaptive/core/pairwise.py
def to_dict(self) -> dict[str, npt.NDArray[np.int32]]:
    r"""Convert the alignment batch to a dictionary of NumPy arrays for serialization.

    Returns:
        dict[str, npt.NDArray[np.int32]]: Dictionary mapping attribute names to arrays.
    """
    return {
        "scores": self.scores,
        "matches": self.matches,
        "mismatches": self.mismatches,
        "gaps": self.gaps,
        "q_starts": self.q_starts,
        "q_ends": self.q_ends,
        "t_starts": self.t_starts,
        "t_ends": self.t_ends,
    }