kaptive.serotyping¶
Surface antigen serotyping and locus matching engine.
The kaptive.serotyping sub-package implements surface polysaccharide locus
typing (such as Klebsiella K and O loci, Acinetobacter K and OC loci) by matching
assembly contigs against reference locus databases, scoring gene presence,
and evaluating locus integrity.
Exports:
- Serotyper: Main serotyping execution engine
(
Serotyper). - SerotypingProblem: Problem definition pairing a genome assembly with a database
(
SerotypingProblem). - SerotypingResult: Comprehensive outcome of locus typing and gene scoring
(
SerotypingResult). - GeneState: Enumeration of gene call integrity states
(
GeneState). - GeneHits: Container for mapped gene alignment records
(
GeneHits). - LocusPieces: Container for assembly locus fragment matches
(
LocusPieces). - ReportRow: Base container for structured output report serialization
(
ReportRow). - KaptiveRow: Standard Kaptive TSV report format row
(
KaptiveRow). - Pha4geRow: PHA4GE-compliant tabular report format row
(
Pha4geRow).
Modules:
-
cliβCommand line interface commands and exporter for serotyping.
-
coreβCore engine for in silico serotyping of bacterial genome assemblies.
-
ioβI/O formatting and TSV report generation for in silico serotyping results.
-
modelsβData models and container classes for serotyping analysis.
Classes:
-
GeneHitsβA high-performance SoA container for classified gene alignments.
-
GeneStateβMutually exclusive states for locus genes found in a genome assembly.
-
KaptiveRowβReport row representation matching the classic Kaptive TSV output format.
-
LocusPiecesβA high-performance SoA container for bounding coordinates of locus fragments.
-
Pha4geRowβReport row representation adhering to Public Health Alliance for Genomic Epidemiology (PHA4GE) standards.
-
ReportRowβAbstract base class for tabular in silico serotyping report rows.
-
SerotyperβHigh-performance in silico serotyping engine for bacterial genome assemblies.
-
SerotypingProblemβSymbolic problems with the serotype call used for report formatting.
-
SerotypingResultβEfficient, immutable container representing an in silico serotyping call.
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.GeneHits[GeneHits]
kaptive.core.collections.BatchedContainer[BatchedContainer]
kaptive.core.collections.BatchedContainer --> kaptive.serotyping.GeneHits
click kaptive.serotyping.GeneHits href "" "kaptive.serotyping.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.GeneState[GeneState]
click kaptive.serotyping.GeneState href "" "kaptive.serotyping.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.
KaptiveRow
dataclass
¶
KaptiveRow(Kaptive_version: bytes, Database_name: bytes, Database_version: bytes, Assembly: bytes, Best_match_locus: bytes, Best_match_type: bytes, Match_confidence: bytes, Problems: bytes, Identity: bytes, Coverage: bytes, Length_discrepancy: bytes, Expected_genes_in_locus: bytes, Expected_genes_in_locus_details: bytes, Missing_expected_genes: bytes, Other_genes_in_locus: bytes, Other_genes_in_locus_details: bytes, Expected_genes_outside_locus: bytes, Expected_genes_outside_locus_details: bytes, Other_genes_outside_locus: bytes, Other_genes_outside_locus_details: bytes, Truncated_genes_details: bytes, Extra_genes_details: bytes)
flowchart TD
kaptive.serotyping.KaptiveRow[KaptiveRow]
kaptive.serotyping.io.ReportRow[ReportRow]
kaptive.serotyping.io.ReportRow --> kaptive.serotyping.KaptiveRow
click kaptive.serotyping.KaptiveRow href "" "kaptive.serotyping.KaptiveRow"
click kaptive.serotyping.io.ReportRow href "" "kaptive.serotyping.io.ReportRow"
Report row representation matching the classic Kaptive TSV output format.
Encapsulates all summary statistics, locus match calls, problem flags, gene details, and coverage metrics for a single genome assembly in tab-separated binary format compatible with traditional Kaptive output parsers.
Attributes:
-
Kaptive_version(bytes) βThe version of Kaptive used to perform serotyping.
-
Database_name(bytes) βName of the reference database used for serotyping.
-
Database_version(bytes) βVersion of the reference database used.
-
Assembly(bytes) βIdentifier/filename of the analyzed genome assembly.
-
Best_match_locus(bytes) βBest matching reference locus type identifier.
-
Best_match_type(bytes) βPredicted serotype/phenotype call for the genome.
-
Match_confidence(bytes) βConfidence classification (
b"Typeable"orb"Untypeable"). -
Problems(bytes) βSymbolic character flags representing
SerotypingProblemlocus match issues (?,+,-,*,!). -
Identity(bytes) βMean percentage amino acid identity across intact expected locus genes.
-
Coverage(bytes) βPercentage coverage of the best matching reference locus by assembly contigs.
-
Length_discrepancy(bytes) βDifference in base pairs between assembly locus length and reference locus length (or
"n/a"). -
Expected_genes_in_locus(bytes) βCount and fraction of expected locus genes found inside locus boundary.
-
Expected_genes_in_locus_details(bytes) βDetailed identity and coverage specs for expected genes inside locus.
-
Missing_expected_genes(bytes) βSemicolon-separated names of expected genes not found.
-
Other_genes_in_locus(bytes) βCount of unexpected genes from other loci found inside locus boundary.
-
Other_genes_in_locus_details(bytes) βDetailed specs for unexpected genes inside locus.
-
Expected_genes_outside_locus(bytes) βCount and fraction of expected locus genes found outside locus boundary.
-
Expected_genes_outside_locus_details(bytes) βDetailed specs for expected genes found outside locus.
-
Other_genes_outside_locus(bytes) βCount of unexpected genes found outside locus boundary.
-
Other_genes_outside_locus_details(bytes) βDetailed specs for unexpected genes found outside locus.
-
Truncated_genes_details(bytes) βDetailed specs for truncated or partial genes.
-
Extra_genes_details(bytes) βDetailed specs for allowed extra database genes.
Note
Numbers beside gene names indicate percentage identity and percentage coverage of the gene in the genome.
Warning
You may sometimes see two copies of the same gene in the Expected_genes_in_locus_details column.
These represent parts of the same gene split over contig boundaries.
Methods:
-
__bytes__βSerialize the report row fields into a tab-separated binary TSV row.
-
from_resultβConstruct a classic
KaptiveRowfrom a serotyping result. -
headerβGenerate backwards-compatible column header bytes for classic Kaptive reports.
__bytes__
¶
__bytes__() -> bytes
Serialize the report row fields into a tab-separated binary TSV row.
Returns:
-
bytes(bytes) βTab-separated field values ending with a newline (
b"\n").
Source code in src/kaptive/serotyping/io.py
from_result
classmethod
¶
from_result(result: SerotypingResult) -> KaptiveRow
Construct a classic KaptiveRow from a serotyping result.
Calculates gene counts, percentage coverages, identity metrics, and problem symbol codes, formatting all fields into UTF-8 encoded bytes for backwards-compatible TSV output.
Parameters:
-
(result¶SerotypingResult) βThe serotyping call result. See
SerotypingResult.
Returns:
-
KaptiveRow(KaptiveRow) βFormatted report row object.
Source code in src/kaptive/serotyping/io.py
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 | |
header
classmethod
¶
header() -> bytes
Generate backwards-compatible column header bytes for classic Kaptive reports.
Replaces internal field name underscores with spaces and _details with , details to maintain exact
compatibility with legacy Kaptive TSV headers.
Returns:
-
bytes(bytes) βTab-separated legacy header line ending with a newline (
b"\n").
Source code in src/kaptive/serotyping/io.py
LocusPieces
dataclass
¶
LocusPieces(ctg_indices: NDArray[uint32], starts: NDArray[int32], ends: NDArray[int32], strands: NDArray[int8])
flowchart TD
kaptive.serotyping.LocusPieces[LocusPieces]
kaptive.core.collections.BatchedContainer[BatchedContainer]
kaptive.core.collections.BatchedContainer --> kaptive.serotyping.LocusPieces
click kaptive.serotyping.LocusPieces href "" "kaptive.serotyping.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
Pha4geRow
dataclass
¶
Pha4geRow(*, sample: bytes, genotyping_method: bytes = b'In silico serotyping', genotyping_schema_taxon: bytes, genotyping_database_name: bytes, genotyping_database_version: bytes, genotyping_schema_name: bytes = b'Kaptive', genotyping_software_name: bytes = b'Kaptive', genotyping_software_version: bytes, genotype: bytes, genotype_predicted_phenotype: bytes, genotype_confidence_value: bytes, genotyping_details: bytes, genotyping_method_url: bytes = b'https://github.com/klebgenomics/Kaptive')
flowchart TD
kaptive.serotyping.Pha4geRow[Pha4geRow]
kaptive.serotyping.io.ReportRow[ReportRow]
kaptive.serotyping.io.ReportRow --> kaptive.serotyping.Pha4geRow
click kaptive.serotyping.Pha4geRow href "" "kaptive.serotyping.Pha4geRow"
click kaptive.serotyping.io.ReportRow href "" "kaptive.serotyping.io.ReportRow"
Report row representation adhering to Public Health Alliance for Genomic Epidemiology (PHA4GE) standards.
Encapsulates sample metadata, taxonomy, software versioning, genotype calls, and confidence values in tab-separated binary format standardized for public health surveillance data exchange.
For more information on the rationale and specifics of the PHA4GE genotyping specification, please see: https://github.com/pha4ge/genotyping-specification
Attributes:
-
sample(bytes) βSample identifier taken from genome assembly filename.
-
genotyping_method(bytes) βGenotyping methodology string (default
b"In silico serotyping"). -
genotyping_schema_taxon(bytes) βNCBITaxon formatted organism species string and taxon ID.
-
genotyping_database_name(bytes) βName of reference database used for serotyping.
-
genotyping_database_version(bytes) βVersion of reference database used.
-
genotyping_schema_name(bytes) βSchema name (default
b"Kaptive"). -
genotyping_software_name(bytes) βSoftware name (default
b"Kaptive"). -
genotyping_software_version(bytes) βKaptive software version used for analysis.
-
genotype(bytes) βBest matching locus type identifier call.
-
genotype_predicted_phenotype(bytes) βPredicted surface antigen phenotype/serotype string.
-
genotype_confidence_value(bytes) βConfidence assessment (
b"Typeable"orb"Untypeable"). -
genotyping_details(bytes) βHuman-readable descriptions of any locus match problems detected.
-
genotyping_method_url(bytes) βRepository URL for methodology documentation.
Methods:
-
__bytes__βSerialize the report row fields into a tab-separated binary TSV row.
-
from_resultβConstruct a standardized
Pha4geRowfrom a serotyping result. -
headerβGenerate the TSV header row as UTF-8 encoded bytes.
__bytes__
¶
__bytes__() -> bytes
Serialize the report row fields into a tab-separated binary TSV row.
Returns:
-
bytes(bytes) βTab-separated field values ending with a newline (
b"\n").
Source code in src/kaptive/serotyping/io.py
from_result
classmethod
¶
from_result(result: SerotypingResult) -> Pha4geRow
Construct a standardized Pha4geRow from a serotyping result.
Transforms numeric taxon IDs and problem flags into human-readable PHA4GE-compliant strings and binary bytes.
Parameters:
-
(result¶SerotypingResult) βThe serotyping call result. See
SerotypingResult.
Returns:
-
Pha4geRow(Pha4geRow) βFormatted PHA4GE report row object.
Source code in src/kaptive/serotyping/io.py
ReportRow
dataclass
¶
flowchart TD
kaptive.serotyping.ReportRow[ReportRow]
click kaptive.serotyping.ReportRow href "" "kaptive.serotyping.ReportRow"
Abstract base class for tabular in silico serotyping report rows.
Provides a uniform interface and binary serialization methods (__bytes__ and header) for converting
SerotypingResult instances into tab-separated (TSV) outputs.
Attributes documented in subclass docstrings correspond directly to TSV report column headers.
Methods:
-
__bytes__βSerialize the report row fields into a tab-separated binary TSV row.
-
from_resultβConstruct a report row instance from a serotyping result.
-
headerβGenerate the TSV header row as UTF-8 encoded bytes.
__bytes__
¶
__bytes__() -> bytes
Serialize the report row fields into a tab-separated binary TSV row.
Returns:
-
bytes(bytes) βTab-separated field values ending with a newline (
b"\n").
Source code in src/kaptive/serotyping/io.py
from_result
abstractmethod
classmethod
¶
from_result(result: SerotypingResult) -> Self
Construct a report row instance from a serotyping result.
Parameters:
-
(result¶SerotypingResult) βThe serotyping analysis result to format. See
SerotypingResult.
Returns:
Source code in src/kaptive/serotyping/io.py
Serotyper
¶
Serotyper(db: Database, max_other_genes: int = 1, min_completeness: float = 0.5, allow_below_threshold: bool = False, preset: Preset | None = None, scoring_metric: str = 'scores', min_gene_coverage: float = 0.2, partial_edge_tolerance: int = 5)
High-performance in silico serotyping engine for bacterial genome assemblies.
The Serotyper utilizes a reference database
(Database) containing surface antigen locus definitions, reference gene sequences,
and phenotypic rules to evaluate input assemblies (GenomeAssembly).
It executes a four-phase serotyping pipeline:
- Mapping & Scoring: Maps reference genes to assembly contigs using
rammappy, culls overlapping hits, and ranks candidate loci based on gene coverage and locus completeness. - Locus Reconstruction: Clusters gene hits spatially to bound locus regions into
LocusPiecesand identifies missing or unexpected genes inside/outside locus boundaries. - Gene State & Identity Evaluation: Translates gene alignments, performs protein-level pairwise alignment
with
PairwiseAligner, assesses frame shifts and truncations, and assignsGeneState(NORMAL, PARTIAL, TRUNCATED, NOVEL). - Phenotype & Confidence Scoring: Applies phenotypic rules (e.g. active/inactive gene clusters) and determines overall serotype typeability.
Attributes:
-
max_other_genes(int) βMaximum allowed unexpected genes inside locus before classifying sample as untypeable.
-
min_completeness(float) βMinimum locus completeness fraction required for typeability call.
-
allow_below_threshold(bool) βWhether to permit genes falling below identity threshold while remaining typeable.
-
preset(Preset | None) βCustom
rammappyalignment preset, if specified. -
scoring_metric(str) βScoring metric used for locus scoring (default
"scores"). -
min_gene_coverage(float) βMinimum query coverage fraction required for gene alignments to be considered valid.
-
partial_edge_tolerance(int) βBase pair distance tolerance from contig boundaries for identifying partial genes.
Parameters:
-
(db¶Database) βThe reference surface antigen database containing loci, genes, and phenotype definitions. See
Database. -
(max_other_genes¶int, default:1) βMaximum allowed unexpected genes inside the locus boundary before flagging as untypeable. Defaults to
1. -
(min_completeness¶float, default:0.5) βMinimum proportion of expected locus genes required to consider the call typeable. Defaults to
0.5. -
(allow_below_threshold¶bool, default:False) βIf
False, any gene inside the locus falling below the identity threshold makes the result untypeable. Defaults toFalse. -
(preset¶Preset | None, default:None) βOptional
rammappymapping preset. Defaults toNone. -
(scoring_metric¶str, default:'scores') βScoring metric used for candidate locus ranking. Defaults to
"scores". -
(min_gene_coverage¶float, default:0.2) βMinimum gene alignment query coverage fraction (0.0 to 1.0) for valid scoring. Defaults to
0.20. -
(partial_edge_tolerance¶int, default:5) βDistance tolerance in base pairs from contig edges to classify a hit as partial. Defaults to
5.
Methods:
-
__call__βPerform in silico serotyping on a target bacterial genome assembly.
Source code in src/kaptive/serotyping/core.py
__call__
¶
__call__(genome: GenomeAssembly | str | Path) -> SerotypingResult | None
Perform in silico serotyping on a target bacterial genome assembly.
Maps reference locus genes against the provided genome assembly, ranks candidate loci, reconstructs locus boundaries, evaluates gene integrity and amino acid identity, and resolves the predicted serotype phenotype.
Parameters:
-
(genome¶GenomeAssembly | str | Path) βTarget genome assembly as a
GenomeAssemblyinstance or filesystem path (strorPath) to a FASTA file.
Returns:
-
SerotypingResult | NoneβSerotypingResult | None: Complete serotyping analysis result containing best matching locus, predicted phenotype, gene hit classifications, spatial locus pieces, and confidence metrics. See
SerotypingResult.
Raises:
-
FileNotFoundErrorβIf
genomeis passed as a file path that does not exist on disk. -
ValueErrorβIf the genome assembly contains no valid contigs or sequence data cannot be parsed.
Source code in src/kaptive/serotyping/core.py
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 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 475 476 477 478 479 480 481 482 483 484 485 486 | |
SerotypingProblem
¶
flowchart TD
kaptive.serotyping.SerotypingProblem[SerotypingProblem]
click kaptive.serotyping.SerotypingProblem href "" "kaptive.serotyping.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: