kaptive.serotyping.models¶
Data models and container classes for serotyping analysis.
This module provides enumerations for gene classification states and serotyping quality problems, along with high-performance Structure-of-Arrays (SoA) containers and data models for storing gene alignment hits, locus fragments, and complete serotyping analysis results.
Classes:
-
[`GeneState`][kaptive.serotyping.models.GeneState]βEnumeration of mutually exclusive gene classification states.
-
[`SerotypingProblem`][kaptive.serotyping.models.SerotypingProblem]βBitflag enumeration of quality problems.
-
[`GeneHits`][kaptive.serotyping.models.GeneHits]βSoA container storing classified gene alignments.
-
[`LocusPieces`][kaptive.serotyping.models.LocusPieces]βSoA container storing bounding coordinates.
-
[`SerotypingResult`][kaptive.serotyping.models.SerotypingResult]βComplete immutable serotyping result record.
GeneHits
dataclass
¶
GeneHits(gene_indices: NDArray[int32], q_starts: NDArray[int32], q_ends: NDArray[int32], t_indices: NDArray[uint32], t_starts: NDArray[int32], t_ends: NDArray[int32], strands: NDArray[int8], is_expected: NDArray[bool_], is_inside: NDArray[bool_], is_extra: NDArray[bool_], expected_positions: NDArray[int32], expected_strands: NDArray[int8], gene_ids: NDArray[bytes_], cluster_names: NDArray[bytes_], product_descriptions: NDArray[bytes_], coverages: NDArray[float32])
flowchart TD
kaptive.serotyping.models.GeneHits[GeneHits]
kaptive.core.collections.BatchedContainer[BatchedContainer]
kaptive.core.collections.BatchedContainer --> kaptive.serotyping.models.GeneHits
click kaptive.serotyping.models.GeneHits href "" "kaptive.serotyping.models.GeneHits"
click kaptive.core.collections.BatchedContainer href "" "kaptive.core.collections.BatchedContainer"
A high-performance SoA container for classified gene alignments.
Encapsulates parallel NumPy arrays and metadata tuples for gene alignments, enabling
synchronized vectorised filtering and dynamic interval calculations. Inherits from
BatchedContainer.
Attributes:
-
gene_indices(NDArray[int32]) βGlobal database gene indices.
-
q_starts(NDArray[int32]) βAlignment start positions on query contigs (0-indexed).
-
q_ends(NDArray[int32]) βAlignment end positions on query contigs (0-indexed).
-
t_indices(NDArray[uint32]) βTarget contig indices in genome assembly.
-
t_starts(NDArray[int32]) βAlignment start positions on database reference genes.
-
t_ends(NDArray[int32]) βAlignment end positions on database reference genes.
-
strands(NDArray[int8]) βAlignment strand orientations (+1 or -1).
-
is_expected(NDArray[bool_]) βBoolean mask indicating expected locus genes.
-
is_inside(NDArray[bool_]) βBoolean mask indicating hits within locus boundaries.
-
is_extra(NDArray[bool_]) βBoolean mask indicating extra allowed genes.
-
expected_positions(NDArray[int32]) βExpected relative gene order positions.
-
expected_strands(NDArray[int8]) βExpected strand orientations (+1 or -1).
-
gene_ids(NDArray[bytes_]) β1D byte string array (
S32) of gene identifier strings. -
cluster_names(NDArray[bytes_]) β1D byte string array (
S10) of gene cluster or family names. -
product_descriptions(NDArray[bytes_]) β1D byte string array (
S64) of functional gene product annotations. -
coverages(NDArray[float32]) βGene alignment coverage proportions.
Methods:
-
__getitem__βSlice or boolean-mask all parallel array fields simultaneously.
-
__len__βReturn total number of gene hit alignments in container.
-
concatβConcatenate multiple
GeneHitsbatches into a single container. -
emptyβCreate an empty
GeneHitscontainer with zero-length arrays and empty tuples. -
from_dictβReconstruct a
GeneHitscontainer from a deserialized dictionary. -
to_dictβConvert SoA array fields to a dictionary for JSON serialization.
frames
property
¶
Calculate reading frame offsets for query alignments.
Returns:
-
NDArray[int32]βnpt.NDArray[np.int32]: Reading frame offsets calculated as
(-q_starts) % 3.
query_lengths
property
¶
Calculate alignment spans on query assembly contigs.
Returns:
-
NDArray[int32]βnpt.NDArray[np.int32]: Alignment spans calculated as
q_ends - q_starts.
target_lengths
property
¶
Calculate alignment spans on database target references.
Returns:
-
NDArray[int32]βnpt.NDArray[np.int32]: Alignment spans calculated as
t_ends - t_starts.
__getitem__
¶
Slice or boolean-mask all parallel array fields simultaneously.
Parameters:
Returns:
Source code in src/kaptive/serotyping/models.py
__len__
¶
__len__() -> int
Return total number of gene hit alignments in container.
Returns:
-
int(int) βNumber of elements in parallel arrays.
concat
classmethod
¶
Concatenate multiple GeneHits batches into a single container.
Parameters:
Returns:
Source code in src/kaptive/serotyping/models.py
empty
classmethod
¶
empty() -> GeneHits
Create an empty GeneHits container with zero-length arrays and empty tuples.
Returns:
Source code in src/kaptive/serotyping/models.py
from_dict
classmethod
¶
Reconstruct a GeneHits container from a deserialized dictionary.
Parameters:
Returns:
Source code in src/kaptive/serotyping/models.py
to_dict
¶
Convert SoA array fields to a dictionary for JSON serialization.
Returns:
-
dict[str, Any]βdict[str, Any]: Dictionary mapping field names to NumPy arrays and metadata tuples.
Source code in src/kaptive/serotyping/models.py
GeneState
¶
flowchart TD
kaptive.serotyping.models.GeneState[GeneState]
click kaptive.serotyping.models.GeneState href "" "kaptive.serotyping.models.GeneState"
Mutually exclusive states for locus genes found in a genome assembly.
Attributes:
-
NORMAL(int) βThe gene was found intact as expected.
-
PARTIAL(int) βThe gene was broken up over a contig edge.
-
TRUNCATED(int) βThe gene does not form a complete amino acid sequence.
-
NOVEL(int) βThe gene translation diverges significantly from the closest reference.
LocusPieces
dataclass
¶
LocusPieces(ctg_indices: NDArray[uint32], starts: NDArray[int32], ends: NDArray[int32], strands: NDArray[int8])
flowchart TD
kaptive.serotyping.models.LocusPieces[LocusPieces]
kaptive.core.collections.BatchedContainer[BatchedContainer]
kaptive.core.collections.BatchedContainer --> kaptive.serotyping.models.LocusPieces
click kaptive.serotyping.models.LocusPieces href "" "kaptive.serotyping.models.LocusPieces"
click kaptive.core.collections.BatchedContainer href "" "kaptive.core.collections.BatchedContainer"
A high-performance SoA container for bounding coordinates of locus fragments.
Stores contig indices, coordinate spans, and strand directions for locus pieces when a locus
is fragmented across multiple contigs.
Inherits from BatchedContainer.
Attributes:
-
ctg_indices(NDArray[uint32]) βTarget contig indices in assembly.
-
starts(NDArray[int32]) βLocus fragment start coordinates (0-indexed).
-
ends(NDArray[int32]) βLocus fragment end coordinates (0-indexed).
-
strands(NDArray[int8]) βLocus fragment strand orientations (+1 or -1).
Methods:
-
__getitem__βSlice or array-mask all parallel fields of locus pieces simultaneously.
-
__len__βReturn total number of locus pieces in container.
-
concatβConcatenate multiple
LocusPiecesbatches into a single container. -
emptyβCreate an empty
LocusPiecescontainer with zero-length arrays. -
from_dictβReconstruct a
LocusPiecescontainer from a deserialized dictionary. -
to_dictβConvert array fields to a dictionary for JSON serialization.
__getitem__
¶
Slice or array-mask all parallel fields of locus pieces simultaneously.
Parameters:
Returns:
-
LocusPieces(Any | LocusPieces) βA sliced
LocusPiecesinstance.
Raises:
-
NotImplementedErrorβIf single integer key access is attempted.
Source code in src/kaptive/serotyping/models.py
__len__
¶
__len__() -> int
Return total number of locus pieces in container.
Returns:
-
int(int) βNumber of fragment elements.
concat
classmethod
¶
Concatenate multiple LocusPieces batches into a single container.
Parameters:
-
(batches¶Iterable[LocusPieces]) βAn iterable of
LocusPiecesinstances.
Returns:
-
LocusPieces(Self) βCombined
LocusPiecescontainer.
Source code in src/kaptive/serotyping/models.py
empty
classmethod
¶
empty() -> LocusPieces
Create an empty LocusPieces container with zero-length arrays.
Returns:
-
LocusPieces(LocusPieces) βAn empty
LocusPiecesinstance.
Source code in src/kaptive/serotyping/models.py
from_dict
classmethod
¶
from_dict(data: dict[str, Any]) -> LocusPieces
Reconstruct a LocusPieces container from a deserialized dictionary.
Parameters:
Returns:
-
LocusPieces(LocusPieces) βReconstructed
LocusPiecesinstance.
Source code in src/kaptive/serotyping/models.py
to_dict
¶
Convert array fields to a dictionary for JSON serialization.
Returns:
Source code in src/kaptive/serotyping/models.py
SerotypingProblem
¶
flowchart TD
kaptive.serotyping.models.SerotypingProblem[SerotypingProblem]
click kaptive.serotyping.models.SerotypingProblem href "" "kaptive.serotyping.models.SerotypingProblem"
Symbolic problems with the serotype call used for report formatting.
Bitflag values represent distinct issues detected during locus assembly analysis and can be combined bitwise.
Attributes:
-
NONE(int) βNo problems detected in the serotype call.
-
FRAGMENTED(int) βLocus is broken up into multiple pieces across contigs (Symbol:
?). -
UNEXPECTED_GENES(int) βUnexpected genes from non-target loci present inside locus boundary (Symbol:
+). -
MISSING_GENES(int) βExpected genes from target locus missing inside locus boundary (Symbol:
-). -
NOVEL_GENES(int) βGenes inside locus boundary falling below identity threshold (Symbol:
*). -
TRUNCATED_GENES(int) βGenes inside locus boundary that are truncated or partial (Symbol:
!). -
SYMBOLS(ClassVar[tuple[bytes, ...]]) βPrecomputed lookup table mapping integer bitflag combinations to symbol byte strings.
Methods:
-
to_symbolsβRender the bitflag combination into formatted symbol bytes for TSV reporting.
SerotypingResult
dataclass
¶
SerotypingResult(kaptive_version: str, database_name: str, database_version: str, database_organism: str, database_taxon: int, genome: str, best_locus_idx: int, best_locus_name: str, best_locus_score: float, best_locus_completeness: float, locus_pieces: LocusPieces, length_discrepancy: float, locus_seqs: Sequences, gene_hits: GeneHits, gene_states: NDArray[int8], gene_seqs: Sequences, translations: Sequences, percent_identity: float, percent_coverage: float, protein_identities: NDArray[float32], phenotype: str, typeable: bool, missing_expected_genes: tuple[str, ...])
Efficient, immutable container representing an in silico serotyping call.
Designed to be lightweight for JSON serialization and database storage while retaining full
information needed to inspect and reconstruct alignment details. Houses nested SoA containers
(LocusPieces and GeneHits)
and sequence objects (Sequences) for downstream processing.
Attributes:
-
kaptive_version(str) βVersion of Kaptive software that produced result.
-
database_name(str) βName of target locus reference database.
-
database_version(str) βVersion tag of reference database.
-
database_organism(str) βTarget organism description in database.
-
database_taxon(int) βNCBI taxonomy ID of database.
-
genome(str) βSample genome assembly identifier or filename.
-
best_locus_idx(int) βIndex of best-matching locus in database.
-
best_locus_name(str) βIdentifier name of best-matching locus.
-
best_locus_score(float) βAlignment score for best-matching locus.
-
best_locus_completeness(float) βProportion of expected genes found in locus (0.0 to 1.0).
-
locus_pieces(LocusPieces) βLocus piece bounding coordinates container.
-
length_discrepancy(float) βLength discrepancy relative to reference locus.
-
locus_seqs(Sequences) βSequences of identified locus region fragments.
-
gene_hits(GeneHits) βHigh-performance SoA container for gene alignment hits.
-
gene_states(NDArray[int8]) βGene classification state array matching
GeneStatevalues. -
gene_seqs(Sequences) βExtracted nucleotide sequences of locus genes.
-
translations(Sequences) βTranslated amino acid sequences of locus genes.
-
percent_identity(float) βOverall nucleotide identity percentage across locus.
-
percent_coverage(float) βOverall reference coverage percentage.
-
protein_identities(NDArray[float32]) βPer-gene protein identity percentages.
-
phenotype(str) βInferred serotype phenotype description.
-
typeable(bool) βFlag indicating if confidence criteria for serotype call were met.
-
missing_expected_genes(tuple[str, ...]) βIdentifiers of missing expected locus genes.
Methods:
-
from_dictβReconstruct a
SerotypingResultinstance from a deserialized dictionary. -
to_dictβConvert serotyping result into a dictionary suitable for JSON serialization.
-
to_locus_dataβConvert result into a
LocusDatacontainer for comparative multi-locus visualization.
from_dict
classmethod
¶
from_dict(data: dict[str, Any]) -> SerotypingResult
Reconstruct a SerotypingResult instance from a deserialized dictionary.
Parameters:
Returns:
-
SerotypingResult(SerotypingResult) βReconstructed
SerotypingResultinstance.
Source code in src/kaptive/serotyping/models.py
to_dict
¶
Convert serotyping result into a dictionary suitable for JSON serialization.
Returns:
-
dict[str, Any]βdict[str, Any]: Lightweight dictionary containing primitive types, lists, and nested dictionaries.
Source code in src/kaptive/serotyping/models.py
to_locus_data
¶
to_locus_data() -> LocusData
Convert result into a LocusData container for comparative multi-locus visualization.
Extracts translations, locus backbone intervals, locus pieces, contig indices, gene states, and functional product descriptions for non-extra inside genes.
Returns: