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.
-
read_tsv–Parse an iterable of TSV byte lines into report row instances.
__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
| Python | |
|---|---|
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 | |
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
read_tsv
classmethod
¶
Parse an iterable of TSV byte lines into report row instances.
Parameters:
Yields:
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.
-
read_tsv–Parse an iterable of TSV byte lines into report row instances.
__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
header
classmethod
¶
header() -> bytes
Generate the TSV header row as UTF-8 encoded bytes.
Returns:
-
bytes(bytes) –Tab-separated column header line ending with a newline (
b"\n").
Source code in src/kaptive/serotyping/io.py
read_tsv
classmethod
¶
Parse an iterable of TSV byte lines into report row instances.
Parameters:
Yields:
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.
-
read_tsv–Parse an iterable of TSV byte lines into report row instances.
__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
header
classmethod
¶
header() -> bytes
Generate the TSV header row as UTF-8 encoded bytes.
Returns:
-
bytes(bytes) –Tab-separated column header line ending with a newline (
b"\n").
Source code in src/kaptive/serotyping/io.py
read_tsv
classmethod
¶
Parse an iterable of TSV byte lines into report row instances.
Parameters:
Yields:
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
| Python | |
|---|---|
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: