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: