kaptive.core.alignment¶
High-performance Structure-of-Arrays alignment and CIGAR data structures.
This module provides optimized representations for sequence alignments and CIGAR operation
encodings. Vectorized containers such as Alignments and
Cigars store alignment fields in flat NumPy arrays, enabling
fast bulk filtering, interval conversions via Intervals, and
strand manipulations using Strand.
Classes:
-
Alignment–A lightweight, read-only view of a single alignment record's data.
-
Alignments–A high-performance, vectorized batch of alignment records.
-
CigarOp–BAM CIGAR operation encodings as a Python Enum.
-
Cigars–A high-performance, batched container for CIGAR data using a flat memory layout.
Functions:
-
parse_cigar_string–Fast Numba parser converting a CIGAR byte-string to a BAM-encoded uint32 array.
Alignment
¶
flowchart TD
kaptive.core.alignment.Alignment[Alignment]
click kaptive.core.alignment.Alignment href "" "kaptive.core.alignment.Alignment"
A lightweight, read-only view of a single alignment record's data.
This NamedTuple provides a convenient interface for accessing the data of a single alignment
within an Alignments collection.
Attributes:
-
idx(int) –Original index within the source
Alignments. -
q_name(str) –Query sequence name.
-
q_length(int) –Total query sequence length.
-
q_start(int) –Start position on the query sequence (0-based, inclusive).
-
q_end(int) –End position on the query sequence (0-based, exclusive).
-
t_name(str) –Target sequence name.
-
t_length(int) –Total target sequence length.
-
t_start(int) –Start position on the target sequence (0-based, inclusive).
-
t_end(int) –End position on the target sequence (0-based, exclusive).
-
strand(Strand) –Alignment orientation (
Strand.FORWARDorStrand.REVERSE). -
length(int) –Alignment block length.
-
match(int) –Number of matching bases.
-
mismatch(int) –Number of mismatching bases.
-
score(int) –Alignment score.
-
quality(int) –Mapping quality score (MAPQ).
-
cigar(NDArray[uint32]) –1D NumPy array of BAM-encoded CIGAR operations.
-
is_primary(bool) –True if primary alignment.
-
is_supplementary(bool) –True if supplementary alignment.
-
is_spliced(bool) –True if spliced alignment.
-
divergence(float) –Estimated sequence divergence.
-
cs(bytes | None) –Optional cs tag byte string.
-
md(bytes | None) –Optional MD tag byte string.
Alignments
dataclass
¶
Alignments(q_name_ids: NDArray[int32], q_names_dict: tuple[str, ...], q_lengths: NDArray[int32], q_starts: NDArray[int32], q_ends: NDArray[int32], t_name_ids: NDArray[int32], t_names_dict: tuple[str, ...], t_lengths: NDArray[int32], t_starts: NDArray[int32], t_ends: NDArray[int32], strands: NDArray[int8], lengths: NDArray[int32], matches: NDArray[int32], mismatches: NDArray[int32], scores: NDArray[int32], qualities: NDArray[uint8], cigars: Cigars, is_primary: NDArray[bool_], is_supplementary: NDArray[bool_], is_spliced: NDArray[bool_], divergence: NDArray[float64], cs: NDArray[object_], md: NDArray[object_])
flowchart TD
kaptive.core.alignment.Alignments[Alignments]
kaptive.core.collections.BatchedContainer[BatchedContainer]
kaptive.core.collections.BatchedContainer --> kaptive.core.alignment.Alignments
click kaptive.core.alignment.Alignments href "" "kaptive.core.alignment.Alignments"
click kaptive.core.collections.BatchedContainer href "" "kaptive.core.collections.BatchedContainer"
A high-performance, vectorized batch of alignment records.
This class stores all data for a collection of alignments in a Structure-of-Arrays (SoA) layout using NumPy arrays.
Attributes:
-
q_name_ids(NDArray[int32]) –Integer indices into
q_names_dict. -
q_names_dict(tuple[str, ...]) –Unique query sequence names dictionary.
-
q_lengths(NDArray[int32]) –Total query sequence lengths.
-
q_starts(NDArray[int32]) –Alignment start positions on query.
-
q_ends(NDArray[int32]) –Alignment end positions on query.
-
t_name_ids(NDArray[int32]) –Integer indices into
t_names_dict. -
t_names_dict(tuple[str, ...]) –Unique target sequence names dictionary.
-
t_lengths(NDArray[int32]) –Total target sequence lengths.
-
t_starts(NDArray[int32]) –Alignment start positions on target.
-
t_ends(NDArray[int32]) –Alignment end positions on target.
-
strands(NDArray[int8]) –Strand orientations (+1 or -1).
-
lengths(NDArray[int32]) –Alignment block lengths.
-
matches(NDArray[int32]) –Number of matching bases.
-
mismatches(NDArray[int32]) –Number of mismatching bases.
-
scores(NDArray[int32]) –Alignment scores.
-
qualities(NDArray[uint8]) –Mapping quality scores (MAPQ).
-
cigars(Cigars) –Batched
Cigarscontainer. -
is_primary(NDArray[bool_]) –Boolean mask of primary alignments.
-
is_supplementary(NDArray[bool_]) –Boolean mask of supplementary alignments.
-
is_spliced(NDArray[bool_]) –Boolean mask of spliced alignments.
-
divergence(NDArray[float64]) –Sequence divergence estimates.
-
cs(NDArray[object_]) –Array of cs tags.
-
md(NDArray[object_]) –Array of MD tags.
Methods:
-
__getitem__–Access alignment records by index, slice, or boolean array mask.
-
__len__–Return the number of alignments in the batch.
-
best–Return an Alignments batch containing only the best alignment per query or target.
-
concat–Concatenate multiple Alignments objects into a single larger batch.
-
cull_overlaps–Greedily cull alignments that overlap significantly with higher-scoring alignments.
-
empty–Create an empty Alignments instance.
-
from_mapping_iterators–Construct an Alignments batch from mapping iterators.
-
from_records–Construct an Alignments batch from an iterable of Alignment record objects.
-
is_partial–Identify alignments that hang over either edge of the target contig.
-
is_partial_left–Identify alignments that hang over the left edge of the target contig.
-
is_partial_right–Identify alignments that hang over the right edge of the target contig.
-
swap_sides–Return a new Alignments batch with query and target roles swapped.
-
to_intervals–Convert alignment coordinates into an Intervals collection.
q_aln_lens
property
¶
Query alignment span lengths.
Returns:
-
NDArray[int32]–npt.NDArray[np.int32]: Alignment spans calculated as
q_ends - q_starts.
q_covs
property
¶
Query alignment coverage fractions.
Returns:
-
NDArray[float64]–npt.NDArray[np.float64]: Coverage ratios computed as
q_aln_lens / q_lengths.
q_names
property
¶
Array of query sequence names for each alignment.
Returns:
-
NDArray[object_]–npt.NDArray[np.object_]: 1D object array of decoded query name strings.
t_aln_lens
property
¶
Target alignment span lengths.
Returns:
-
NDArray[int32]–npt.NDArray[np.int32]: Alignment spans calculated as
t_ends - t_starts.
t_covs
property
¶
Target alignment coverage fractions.
Returns:
-
NDArray[float64]–npt.NDArray[np.float64]: Coverage ratios computed as
t_aln_lens / t_lengths.
t_names
property
¶
Array of target sequence names for each alignment.
Returns:
-
NDArray[object_]–npt.NDArray[np.object_]: 1D object array of decoded target name strings.
__getitem__
¶
Access alignment records by index, slice, or boolean array mask.
Parameters:
Returns:
-
Alignment | Alignments–Alignment | Alignments: A scalar
Alignmentrecord view if an integer is passed, or a new filteredAlignmentsbatch.
Raises:
-
IndexError–If an integer index is out of range.
Source code in src/kaptive/core/alignment.py
__len__
¶
__len__() -> int
best
¶
best(by_query: bool = True) -> Alignments
Return an Alignments batch containing only the best alignment per query or target.
Selection ranks by alignment score, matches, and mapping quality.
Parameters:
-
(by_query¶bool, default:True) –If True, selects the best alignment per query sequence; if False, selects the best per target sequence. Defaults to True.
Returns:
-
Alignments(Alignments) –Filtered
Alignmentsbatch.
Source code in src/kaptive/core/alignment.py
concat
classmethod
¶
concat(batches: Iterable[Alignments]) -> Self
Concatenate multiple Alignments objects into a single larger batch.
Parameters:
-
(batches¶Iterable[Alignments]) –Iterable of
Alignmentsbatches.
Returns:
-
Alignments(Self) –Combined
Alignmentsbatch.
Raises:
-
ValueError–If
batchesis empty or if batch fields cannot be concatenated.
Source code in src/kaptive/core/alignment.py
cull_overlaps
¶
cull_overlaps(max_overlap_fraction: float = 0.1, group_by: ndarray | None = None, priority_mask: ndarray | None = None, by_query: bool = True) -> Alignments
Greedily cull alignments that overlap significantly with higher-scoring alignments.
Parameters:
-
(max_overlap_fraction¶float, default:0.1) –Maximum allowable overlap as a fraction of alignment length. Defaults to 0.1.
-
(group_by¶ndarray | None, default:None) –Optional integer array for grouping alignments. Overlaps are checked only within the same group. Defaults to None.
-
(priority_mask¶ndarray | None, default:None) –Optional boolean mask giving priority score boosts. Defaults to None.
-
(by_query¶bool, default:True) –If True, checks overlaps in query coordinates; if False, target coordinates. Defaults to True.
Returns:
-
Alignments(Alignments) –Filtered, non-overlapping
Alignmentsbatch.
Source code in src/kaptive/core/alignment.py
empty
classmethod
¶
empty() -> Alignments
Create an empty Alignments instance.
Returns:
-
Alignments(Alignments) –Empty
Alignmentsbatch.
Source code in src/kaptive/core/alignment.py
from_mapping_iterators
classmethod
¶
Construct an Alignments batch from mapping iterators.
Parameters:
-
(queries¶list[tuple[str, int]]) –List of query tuples
(query_name, query_length). -
(iterators¶Iterable[Any]) –Iterable of mapping hit iterators (
rammappy.align.MappingIterator).
Returns:
-
Alignments(Self) –Vectorized
Alignmentsbatch.
Source code in src/kaptive/core/alignment.py
391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 | |
from_records
classmethod
¶
from_records(records: Iterable[Alignment]) -> Alignments
Construct an Alignments batch from an iterable of Alignment record objects.
Parameters:
Returns:
-
Alignments(Alignments) –Newly constructed
Alignmentsbatch.
Source code in src/kaptive/core/alignment.py
is_partial
¶
is_partial(edge_tolerance: int = 0) -> NDArray[bool_]
Identify alignments that hang over either edge of the target contig.
Parameters:
Returns:
-
NDArray[bool_]–npt.NDArray[np.bool_]: Boolean mask of partial alignments.
Source code in src/kaptive/core/alignment.py
is_partial_left
¶
is_partial_left(edge_tolerance: int = 0) -> NDArray[bool_]
Identify alignments that hang over the left edge of the target contig.
Parameters:
Returns:
-
NDArray[bool_]–npt.NDArray[np.bool_]: Boolean mask of partial left alignments.
Source code in src/kaptive/core/alignment.py
is_partial_right
¶
is_partial_right(edge_tolerance: int = 0) -> NDArray[bool_]
Identify alignments that hang over the right edge of the target contig.
Parameters:
Returns:
-
NDArray[bool_]–npt.NDArray[np.bool_]: Boolean mask of partial right alignments.
Source code in src/kaptive/core/alignment.py
swap_sides
¶
swap_sides() -> Alignments
Return a new Alignments batch with query and target roles swapped.
Returns:
-
Alignments(Alignments) –Swapped
Alignmentsbatch.
Source code in src/kaptive/core/alignment.py
to_intervals
¶
Convert alignment coordinates into an Intervals collection.
Parameters:
-
(by_query¶bool, default:False) –If True, uses query coordinates (
q_starts,q_ends); if False, uses target coordinates (t_starts,t_ends). Defaults to False.
Returns:
Source code in src/kaptive/core/alignment.py
CigarOp
¶
flowchart TD
kaptive.core.alignment.CigarOp[CigarOp]
click kaptive.core.alignment.CigarOp href "" "kaptive.core.alignment.CigarOp"
BAM CIGAR operation encodings as a Python Enum.
This class provides a standardized, integer-based representation for CIGAR (Concise Idiosyncratic
Gapped Alignment Report) operations, which describe how an alignment is constructed from pieces
of the query and target sequences. Using an IntEnum allows for both readable access (e.g., CigarOp.M)
and efficient integer-based comparisons in performance-critical code.
The values correspond to the official BAM specification.
Attributes:
-
M(0) –Alignment match (can be a sequence match or mismatch).
-
I(1) –Insertion to the reference.
-
D(2) –Deletion from the reference.
-
N(3) –Skipped region from the reference (e.g., intron).
-
S(4) –Soft clipping (clipped sequences present in the sequence record).
-
H(5) –Hard clipping (clipped sequences NOT present in the sequence record).
-
P(6) –Padding (silent deletion from a padded reference).
-
EQ(7) –Sequence match (explicitly a match).
-
X(8) –Sequence mismatch (explicitly a mismatch).
-
B(9) –Backwards compatibility operation.
Cigars
dataclass
¶
flowchart TD
kaptive.core.alignment.Cigars[Cigars]
kaptive.core.collections.RaggedArrayContainer[RaggedArrayContainer]
kaptive.core.collections.BatchedContainer[BatchedContainer]
kaptive.core.collections.RaggedArrayContainer --> kaptive.core.alignment.Cigars
kaptive.core.collections.BatchedContainer --> kaptive.core.collections.RaggedArrayContainer
click kaptive.core.alignment.Cigars href "" "kaptive.core.alignment.Cigars"
click kaptive.core.collections.RaggedArrayContainer href "" "kaptive.core.collections.RaggedArrayContainer"
click kaptive.core.collections.BatchedContainer href "" "kaptive.core.collections.BatchedContainer"
A high-performance, batched container for CIGAR data using a flat memory layout.
Instead of storing CIGAR strings or lists of tuples for each alignment, this class concatenates all
CIGAR operations into a single, large NumPy array (data). This "ragged array" is managed by offsets
and lengths arrays, which define the slice of the data array corresponding to each individual alignment's
CIGAR sequence.
Each CIGAR operation is encoded into a single 32-bit unsigned integer, following the BAM specification:
- The upper 28 bits store the length of the operation.
- The lower 4 bits store the operation type (corresponding to CigarOp values).
Attributes:
-
data(NDArray[uint32]) –A 1D array containing all concatenated, BAM-encoded CIGAR operations.
-
offsets(NDArray[int32]) –A 1D array where
offsets[i]gives the starting index indatafor the i-th alignment's CIGAR sequence. -
lengths(NDArray[int32]) –A 1D array where
lengths[i]gives the number of CIGAR operations for the i-th alignment.
Methods:
-
__getitem__–Access CIGAR data by index, slice, or boolean mask.
-
__len__–Return the number of CIGAR sequences in the batch.
-
concat–Concatenate multiple Cigars objects into a single, larger batch.
-
empty–Create an empty Cigars instance.
-
from_lists–Construct a Cigars instance from a list of individual CIGAR NumPy arrays.
-
swap_sides–Return a new Cigars batch with Insertion (I) and Deletion (D) operations swapped.
__getitem__
¶
Access CIGAR data by index, slice, or boolean mask.
- If
itemis an integer, returns a NumPy array of encoded CIGAR operations for that alignment. - If
itemis a slice or mask, returns a new, smallerCigarscontaining only the selected CIGARs.
Parameters:
Returns:
-
NDArray[uint32] | Cigars–npt.NDArray[np.uint32] | Cigars: A single CIGAR array or a new
Cigarsbatch.
Raises:
-
IndexError–If an integer index is out of range.
Source code in src/kaptive/core/alignment.py
__len__
¶
__len__() -> int
Return the number of CIGAR sequences in the batch.
Returns:
-
int(int) –Number of CIGAR sequences.
concat
classmethod
¶
Concatenate multiple Cigars objects into a single, larger batch.
Parameters:
Returns:
Source code in src/kaptive/core/alignment.py
empty
classmethod
¶
empty() -> Cigars
Create an empty Cigars instance.
Returns:
Source code in src/kaptive/core/alignment.py
from_lists
classmethod
¶
from_lists(cigar_lists: list[NDArray[uint32]]) -> Cigars
Construct a Cigars instance from a list of individual CIGAR NumPy arrays.
Parameters:
Returns:
Source code in src/kaptive/core/alignment.py
swap_sides
¶
swap_sides() -> Cigars
Return a new Cigars batch with Insertion (I) and Deletion (D) operations swapped.
This is used when swapping the query and target roles of an alignment.
Returns:
Source code in src/kaptive/core/alignment.py
parse_cigar_string
¶
parse_cigar_string(cigar_bytes: bytes) -> NDArray[uint32]
Fast Numba parser converting a CIGAR byte-string to a BAM-encoded uint32 array.
Parameters:
Returns:
-
NDArray[uint32]–npt.NDArray[np.uint32]: 1D array of BAM-encoded 32-bit CIGAR operations.