kaptive.db.core¶
Core in-memory representation of Kaptive antigen reference databases.
This module defines the Database class, which maintains
all locus sequences, gene coordinates, protein translations, phenotypic logic rules,
and search indexes in a memory-efficient Structure-of-Arrays (SoA) layout.
Classes:
Database
dataclass
¶
Database(metadata: DatabaseMetadata, loci: Sequences, serotypes: tuple[str, ...], locus_gene_offsets: NDArray[uint32], locus_gene_lengths: NDArray[uint32], gene_intervals: Intervals, genes: Sequences, translations: Sequences, extra_genes: NDArray[bool_], gene_locus_indices: NDArray[uint16], cluster_keys: tuple[str, ...], gene_cluster_ids: NDArray[uint16], description_keys: tuple[str, ...], gene_description_ids: NDArray[uint16], gene_positions: NDArray[uint16], phenotypes: Phenotypes, loci_sketches: FracMinHashIndex)
Optimized representation of a Kaptive antigen database in memory using Structure-of-Arrays (SoA).
This class eschews traditional object hierarchies (e.g., Locus -> Gene -> Sequence) in favor of flat, parallel arrays (Structure of Arrays). This layout provides significant performance benefits:
- Memory Locality: Data of the same type (e.g., all gene cluster IDs) is stored contiguously, drastically reducing cache misses during iterative alignment.
- Vectorization: NumPy arrays allow operations to be performed on thousands of genes simultaneously without Python loop overhead.
- Fast Lookups: Vocabularies convert strings into integer IDs (
gene_cluster_ids). Comparing integers is orders of magnitude faster than string comparison.
The database manages two main entities: Loci (full locus sequences) and Genes (individual coding sequences). Mappings between these entities are maintained via indices and slices rather than object references.
Attributes:
-
metadata(DatabaseMetadata) –Strict, validated metadata schema associated with the database (
DatabaseMetadata). -
loci(Sequences) –Vectorized batch of locus nucleotide sequences and IDs (
Sequences). Length isN_loci. -
serotypes(tuple[str, ...]) –Tuple of length
N_locimapping each locus index to its serotype name. -
locus_gene_offsets(NDArray[uint32]) –1D array of length
N_locicontaining global gene start indices. -
locus_gene_lengths(NDArray[uint32]) –1D array of length
N_locicontaining gene counts per locus. -
gene_intervals(Intervals) –Vectorized batch of gene coordinates relative to parent loci (
Intervals). Length isN_genes. -
genes(Sequences) –Vectorized batch of gene nucleotide sequences (
Sequences). Length isN_genes. -
translations(Sequences) –Vectorized batch of translated protein sequences (
Sequences). Length isN_genes. -
extra_genes(NDArray[bool_]) –Boolean mask of length
N_genesindicating extra genes without synteny. -
gene_locus_indices(NDArray[uint16]) –1D array of length
N_genesmapping gene back to locus index. -
cluster_keys(tuple[str, ...]) –Vocabulary of unique gene cluster names.
-
gene_cluster_ids(NDArray[uint16]) –1D array of length
N_genesstoring cluster integer IDs. -
description_keys(tuple[str, ...]) –Vocabulary of unique gene product descriptions.
-
gene_description_ids(NDArray[uint16]) –1D array of length
N_genesstoring product description IDs. -
gene_positions(NDArray[uint16]) –1D array of length
N_genesstoring expected gene position (1-indexed). -
phenotypes(Phenotypes) –Vectorized batch dictating serotype assignment logic (
Phenotypes). -
loci_sketches(FracMinHashIndex) –Precomputed FracMinHash sketches for locus containment testing (
FracMinHashIndex).
See Also
Methods:
-
from_genbank–Compiles a Database object by parsing a legacy GenBank format file and its associated TOML metadata.
-
from_pickle–Loads a pre-compiled Database object from a serialized pickle file.
-
get_locus_data–Extracts locus data including protein sequences, coordinate backbone, gene states, and product descriptions for a specific locus.
-
load–Loads a Database from a file path (GenBank or Pickle).
cluster_vocab
property
¶
description_vocab
property
¶
max_locus_length
property
¶
max_locus_length: int
Length of the longest locus sequence in the database.
Useful for pre-allocating memory buffers of sufficient size when aligning against the database.
Returns:
-
int(int) –The maximum sequence length among all loci, or 0 if the database contains no loci.
from_genbank
classmethod
¶
Compiles a Database object by parsing a legacy GenBank format file and its associated TOML metadata.
This is an expensive compilation step that converts the nested, string-heavy GenBank structure into the flat, integer-based SoA layout defined by this class.
The method performs the following tasks:
- Iterates through loci in the
.gbkfile, extracting sequence data. - Parses CDS (Coding Sequence) features to extract gene coordinates, clusters, and descriptions.
- Builds the string-to-integer vocabularies (
cluster_vocab,description_vocab). - Constructs the flat numpy arrays (e.g.,
gene_cluster_ids,gene_positions). - Creates
SequencesandIntervalsobjects for vectorized sequence operations. - Translates all extracted gene nucleotide sequences into protein sequences.
- Loads and validates metadata from a companion
.tomlfile (which must have the same name as the.gbkfile). - Parses complex phenotype logic from the metadata.
Parameters:
-
(file¶str | Path) –The path to the
.gbkdatabase file. A companion.tomlfile must exist in the same directory.
Returns:
-
Database(Database) –The newly compiled, optimized Database object.
Raises:
-
DatabaseError–If loci lack required qualifiers ('note', 'locus'), or if the associated
.tomlmetadata file is missing.
Source code in src/kaptive/db/core.py
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 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 | |
from_pickle
classmethod
¶
Loads a pre-compiled Database object from a serialized pickle file.
Parameters:
Returns:
Raises:
-
FileNotFoundError–If the file does not exist.
See Also
Source code in src/kaptive/db/core.py
get_locus_data
¶
get_locus_data(locus_name: str) -> LocusData
Extracts locus data including protein sequences, coordinate backbone, gene states, and product descriptions for a specific locus.
Parameters:
Returns:
-
LocusData(LocusData) –Container object populated with locus proteins, coordinate backbone, gene states, and product descriptions (
LocusData).
Raises:
-
ValueError–If
locus_nameis not present inself.loci.ids.
See Also
Source code in src/kaptive/db/core.py
load
classmethod
¶
Loads a Database from a file path (GenBank or Pickle).
Factory entry point that delegates loading based on file extension:
1. If .gbk file path is provided, invokes from_genbank.
2. If .pkl file path is provided, invokes from_pickle.
Parameters:
Returns:
Raises:
-
DatabaseError–If file extension is unsupported.
-
FileNotFoundError–If the file does not exist.