kaptive.core.seq¶
Biological sequence data structures, SoA containers, and translation utilities.
This module provides high-performance data structures for storing, manipulating, and
translating biological sequences (DNA, RNA, protein). Sequences are stored either as individual
immutable SeqRecord instances or as contiguous, flat arrays in
Sequences Structure-of-Arrays (SoA) containers.
Key Classes
SeqRecord: Immutable container for a single sequence record.Sequences: Memory-efficient, Numba-accelerated SoA container.BacterialTranslationTable: NCBI Translation Table 11 translator.
Classes:
-
BacterialTranslationTable–NCBI Translation Table 11 utilities for bacterial codon translation and complementation.
-
SeqRecord–A simple, immutable container for a single biological sequence.
-
Sequences–A high-performance SoA container for biological sequences.
BacterialTranslationTable
¶
NCBI Translation Table 11 utilities for bacterial codon translation and complementation.
Provides pre-computed character map and codon lookup tables for fast 3-base codon to amino acid conversion, reverse-complementation mapping, and start/stop codon validation.
Methods:
-
is_coding–Check if a byte sequence starts with a valid bacterial start codon and ends with a stop codon.
-
translate–Translate a nucleotide sequence array or byte string to amino acid byte values.
is_coding
classmethod
¶
Check if a byte sequence starts with a valid bacterial start codon and ends with a stop codon.
Parameters:
Returns:
-
bool(bool) –True if sequence length >= 3 and starts/ends with valid bacterial start/stop codons.
Source code in src/kaptive/core/seq.py
translate
classmethod
¶
translate(seq: bytes | bytearray | memoryview | NDArray[uint8], to_stop: bool = False) -> NDArray[uint8]
Translate a nucleotide sequence array or byte string to amino acid byte values.
Parameters:
-
(seq¶bytes | bytearray | memoryview | NDArray[uint8]) –Input nucleotide sequence.
-
(to_stop¶bool, default:False) –If True, truncates translation at the first stop codon ('*'). Defaults to False.
Returns:
-
NDArray[uint8]–npt.NDArray[np.uint8]: 1D array of ASCII uint8 values representing translated amino acids.
Source code in src/kaptive/core/seq.py
SeqRecord
dataclass
¶
A simple, immutable container for a single biological sequence.
This class pairs a string identifier with sequence data stored as immutable bytes. It provides basic functionality for length checking, FASTA formatting, and sub-sequence extraction.
Attributes:
-
id(str) –Unique identifier or name of the sequence.
-
seq(bytes) –Raw sequence data (e.g. DNA, RNA, or protein).
Methods:
-
__len__–Return the length of the sequence in bytes.
-
extract–Extract a sub-sequence based on coordinates and orientation.
-
to_fasta–Format the sequence as a FASTA record byte string.
extract
¶
Extract a sub-sequence based on coordinates and orientation.
If strand is negative (e.g. Strand),
the extracted sub-sequence is automatically reverse-complemented.
Parameters:
-
(start¶int | IntervalLike) –0-based start coordinate, or an
IntervalLikeobject (providing start, end, and strand). -
(end¶int | None, default:None) –0-based end coordinate (exclusive). If
startis an interval, this must be None. Defaults to None. -
(strand¶Strand, default:UNSTRANDED) –Orientation of the extraction. Defaults to
Strand.
Returns:
-
bytes(bytes) –Extracted (and potentially reverse-complemented) sub-sequence bytes.
Source code in src/kaptive/core/seq.py
Sequences
dataclass
¶
Sequences(ids: tuple[str, ...], seqs: NDArray[uint8], offsets: NDArray[int32], lengths: NDArray[int32])
flowchart TD
kaptive.core.seq.Sequences[Sequences]
kaptive.core.collections.RaggedArrayContainer[RaggedArrayContainer]
kaptive.core.collections.BatchedContainer[BatchedContainer]
kaptive.core.collections.RaggedArrayContainer --> kaptive.core.seq.Sequences
kaptive.core.collections.BatchedContainer --> kaptive.core.collections.RaggedArrayContainer
click kaptive.core.seq.Sequences href "" "kaptive.core.seq.Sequences"
click kaptive.core.collections.RaggedArrayContainer href "" "kaptive.core.collections.RaggedArrayContainer"
click kaptive.core.collections.BatchedContainer href "" "kaptive.core.collections.BatchedContainer"
A high-performance SoA container for biological sequences.
Stores multiple sequences in a flat, contiguous memory layout using a 1D NumPy array
of unsigned 8-bit integers (np.uint8). Individual sequences are accessed via parallel arrays
of offsets and lengths.
Attributes:
-
ids(tuple[str, ...]) –String identifiers for each sequence.
-
seqs(NDArray[uint8]) –Single flat 1D array containing all sequence byte data concatenated.
-
offsets(NDArray[int32]) –1D array of start indices in
seqs. -
lengths(NDArray[int32]) –1D array of sequence lengths.
Methods:
-
__getitem__–Access sequences by index, slice, or boolean mask.
-
__iter__–Iterate over the batch, yielding a SeqRecord for each sequence.
-
__len__–Return the total number of sequences in the batch.
-
concat–Concatenate multiple Sequences containers into a single larger collection.
-
empty–Create an empty Sequences object with zero-length arrays.
-
extract–Vectorized sub-sequence extraction from the batch.
-
extract_intervals–Wrapper around extract taking an Intervals collection.
-
from_bytes–Construct Sequences from a list of byte strings.
-
from_dict–Deserialize a Sequences object from a dictionary representation.
-
from_records–Construct Sequences from a list of SeqRecord objects.
-
to_dict–Convert sequence batch to a dictionary representation suitable for serialization.
-
to_fasta–Format the entire batch as a single FASTA byte string.
-
translate–Vectorized translation of nucleotide sequences into protein sequences.
-
unique–Return a new Sequences container containing only unique sequences.
internal_stops
property
¶
Vectorized check for internal stop codons in protein sequences.
Scans each sequence for the stop codon character ('*') before the final position using a Numba kernel.
Returns:
-
ndarray–np.ndarray: A 1D boolean array where True indicates presence of an internal stop.
__getitem__
¶
Access sequences by index, slice, or boolean mask.
Parameters:
Returns:
Raises:
-
IndexError–If an integer index is out of bounds.
Source code in src/kaptive/core/seq.py
__iter__
¶
Iterate over the batch, yielding a SeqRecord for each sequence.
Yields:
-
SeqRecord(SeqRecord) –Scalar record for each sequence in the batch.
Source code in src/kaptive/core/seq.py
__len__
¶
__len__() -> int
Return the total number of sequences in the batch.
Returns:
-
int(int) –Number of sequence records in the container.
concat
classmethod
¶
Concatenate multiple Sequences containers into a single larger collection.
Parameters:
Returns:
-
Sequences(Sequences) –A combined sequences container.
Source code in src/kaptive/core/seq.py
empty
classmethod
¶
empty() -> Sequences
Create an empty Sequences object with zero-length arrays.
Returns:
-
Sequences(Sequences) –An empty sequences container.
Source code in src/kaptive/core/seq.py
extract
¶
extract(indices: NDArray[int32], starts: NDArray[int32], ends: NDArray[int32], strands: NDArray[int8], new_ids: tuple[str, ...] | None = None) -> Sequences
Vectorized sub-sequence extraction from the batch.
Handles coordinates and reverse-complementation across multiple sequences in parallel using Numba.
Parameters:
-
(indices¶NDArray[int32]) –1D array specifying parent sequence index for each extraction.
-
(starts¶NDArray[int32]) –0-based start coordinates relative to parent sequence.
-
(ends¶NDArray[int32]) –0-based end coordinates relative to parent sequence.
-
(strands¶NDArray[int8]) –Strand orientations (1 for forward, -1 for reverse-complement).
-
(new_ids¶tuple[str, ...] | None, default:None) –Identifiers for extracted sequences. If None, auto-generates names.
Returns:
-
Sequences(Sequences) –New collection of extracted sub-sequences.
Source code in src/kaptive/core/seq.py
extract_intervals
¶
extract_intervals(indices: NDArray[integer], intervals: Intervals, new_ids: tuple[str, ...] | None = None) -> Sequences
Wrapper around extract taking an Intervals collection.
Parameters:
-
(indices¶NDArray[integer]) –Target sequence indices for each interval.
-
(intervals¶Intervals) –Interval collection containing coordinates and strands.
-
(new_ids¶tuple[str, ...] | None, default:None) –New sequence identifiers. Defaults to None.
Returns:
-
Sequences(Sequences) –New collection of extracted sub-sequences.
Source code in src/kaptive/core/seq.py
from_bytes
classmethod
¶
Construct Sequences from a list of byte strings.
Parameters:
-
(seqs¶list[bytes]) –List of raw sequence byte strings.
-
(ids¶tuple[str, ...] | None, default:None) –Sequence identifiers. Defaults to string integer indices ("0", "1", ...).
Returns:
-
Sequences(Sequences) –Newly constructed sequences container.
Source code in src/kaptive/core/seq.py
from_dict
classmethod
¶
Deserialize a Sequences object from a dictionary representation.
Parameters:
-
(data¶dict[str, Any]) –Dictionary containing 'ids', ASCII string 'seqs', 'offsets', and 'lengths'.
Returns:
-
Sequences(Sequences) –Deserialized sequence collection.
Source code in src/kaptive/core/seq.py
from_records
classmethod
¶
Construct Sequences from a list of SeqRecord objects.
Parameters:
Returns:
-
Sequences(Sequences) –Newly constructed sequences container.
Source code in src/kaptive/core/seq.py
to_dict
¶
Convert sequence batch to a dictionary representation suitable for serialization.
Returns:
-
dict[str, Any]–dict[str, Any]: Dictionary containing 'ids', ASCII string 'seqs', 'offsets', and 'lengths'.
Source code in src/kaptive/core/seq.py
to_fasta
¶
to_fasta(use_indices: bool = False) -> bytes
Format the entire batch as a single FASTA byte string.
Parameters:
-
(use_indices¶bool, default:False) –If True, uses 0-based integer index as FASTA header (
>0,>1, ...) instead of stringids. Defaults to False.
Returns:
-
bytes(bytes) –Complete FASTA-formatted byte string containing all sequences.
Source code in src/kaptive/core/seq.py
translate
¶
Vectorized translation of nucleotide sequences into protein sequences.
Translates sequences according to NCBI Translation Table 11 (Bacterial, Archaeal, and Plant Plastid Code)
via BacterialTranslationTable.
Parameters:
-
(frames¶NDArray[int8] | None, default:None) –Reading frame offsets (0, 1, or 2) per sequence. Defaults to frame 0 for all.
-
(to_stop¶bool, default:False) –If True, truncates translation at the first stop codon (*). Defaults to False.
Returns:
-
Sequences(Sequences) –New collection containing translated protein sequences.
Source code in src/kaptive/core/seq.py
unique
¶
unique() -> Sequences
Return a new Sequences container containing only unique sequences.
Uses a Numba-accelerated 64-bit FNV-1a hash to identify unique sequences while preserving first-occurrence order.
Returns:
-
Sequences(Sequences) –A new container with duplicate sequences removed.