kaptive.db¶
Kaptive reference database management and data models.
The kaptive.db sub-package handles downloading, loading, validating, and
managing Kaptive reference databases containing locus sequences, gene metadata,
and serotype phenotype definitions.
Exports:
- Database: Core reference database containing indexed locus sequences
(
Database). - DatabaseManager: Remote database downloading and local directory management
(
DatabaseManager). - DatabaseMetadata: Metadata container for database versioning and locus definitions
(
DatabaseMetadata). - DatabaseError: Base exception for database formatting and loading failures
(
DatabaseError). - Phenotype: Single locus phenotype definition
(
Phenotype). - Phenotypes: Collection container for locus phenotype mapping records
(
Phenotypes).
Modules:
-
cli–Command-line interface commands for managing and querying Kaptive reference databases.
-
core–Core in-memory representation of Kaptive antigen reference databases.
-
manager–Database management module for downloading, compiling, and managing Kaptive databases.
-
models–Data models and custom exception classes for Kaptive database representation.
Classes:
-
Database–Optimized representation of a Kaptive antigen database in memory using Structure-of-Arrays (SoA).
-
DatabaseError–Exception raised for database loading, metadata validation, or format errors.
-
DatabaseManager–Class for managing Kaptive databases both on the user's disk and in curator GitHub repositories.
-
DatabaseMetadata–Strict schema for Database metadata with dependency-free validation and ergonomic attribute access.
-
Phenotype–Single locus phenotype rule mapping loci and gene requirements to a serotype identifier.
-
Phenotypes–Structure-of-Arrays (SoA) container for vectorized phenotype evaluation.
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.
See Also
Source code in src/kaptive/db/core.py
DatabaseError
¶
flowchart TD
kaptive.db.DatabaseError[DatabaseError]
click kaptive.db.DatabaseError href "" "kaptive.db.DatabaseError"
Exception raised for database loading, metadata validation, or format errors.
This exception is raised when database metadata is invalid, required files are missing,
or reference database files fail validation in DatabaseMetadata,
Database, or DatabaseManager.
DatabaseManager
¶
Class for managing Kaptive databases both on the user's disk and in curator GitHub repositories.
This class provides a comprehensive mechanism for downloading, compiling, and managing Kaptive databases.
Databases are maintained as source files (GenBank and TOML) in Git repositories. The
DatabaseManager fetches these files, compiles them into optimized, flat
Database objects (using a Structure-of-Arrays layout for vectorized operations),
and stores them locally as serialized pickle files (.pkl) alongside .json metadata sidecars in the user's
local directory (defaults to ~/.kaptive or $KAPTIVE_DB_DIR).
The manager handles:
- Installation: Fetching a known database from its remote repository
(
install), or a custom database from any GitHub repository (add), compiling it, and caching the result locally. - Updates: Checking the local compiled database against the remote repository's version (specified in
the TOML metadata) and downloading/recompiling if a newer version exists
(
update). - Storage & Retrieval: Saving (
save) and loading (load) these compiled.pklfiles efficiently. - Lifecycle Management: Uninstalling specific databases
(
uninstall) or completely resetting the local cache (reset).
Attributes:
-
_KNOWN(dict[str, tuple[str, str, str]]) –Internal lookup mapping of officially supported database keywords to tuples of
(repository_owner, repository_name, database_base_name). -
_DB_DIR(Path) –Local cache directory path where
.pkldatabase files and.jsonmetadata sidecars are stored.
Methods:
-
add–Add or update a database directly from a specified remote Git repository.
-
get–Load a Database from a file path or resolve and load it by keyword.
-
install–Install known, officially supported databases by keyword.
-
installed–Return a list of keywords for all currently installed databases.
-
known–Return a list of keywords for all currently known, officially supported databases.
-
load–Load a locally installed, compiled database using its keyword.
-
reset–Remove all installed databases by deleting their compiled files from the local directory.
-
save–Serialize and save a compiled Database object and its metadata to local storage.
-
uninstall–Uninstall a specific database by removing its compiled local
.pkland.jsonfiles. -
update–Update installed databases by checking against their remote GitHub repositories.
add
classmethod
¶
add(owner: str, repo_name: str, db_name: str, branch: str = 'main', local_meta: DatabaseMetadata | None = None) -> Database | None
Add or update a database directly from a specified remote Git repository.
This is the primary method for adding custom or official databases from GitHub. The procedure:
- Constructs raw GitHub URL endpoints for the repository's
.tomlmetadata and.gbkGenBank files. - Downloads and parses the remote TOML metadata to extract version information.
- Compares the remote version against local metadata (if available). If up-to-date, skips remaining steps and
returns
None. - Downloads the raw GenBank file content over HTTP.
- Writes source files into a temporary directory and compiles them using
from_genbank. - Serializes and caches the compiled
Databaseobject into the local storage directory.
Parameters:
-
(owner¶str) –Owner or organization of the GitHub repository (e.g.,
'klebgenomics'). -
(repo_name¶str) –Name of the GitHub repository (e.g.,
'KpSC_surface_antigen_loci'). -
(db_name¶str) –Base name of the database files in the repository (e.g.,
'Klebsiella_pneumoniae_Species_Complex_K'). -
(branch¶str, default:'main') –Git branch name to fetch from. Defaults to
'main'. -
(local_meta¶DatabaseMetadata | None, default:None) –Pre-loaded metadata of local database installation. Defaults to
None.
Returns:
-
Database | None–Database | None: The newly compiled
Databaseobject if installed or updated, orNoneif the local version was already up-to-date.
Raises:
-
DatabaseError–If repository files are not found, network issues occur, or file compilation fails.
See Also
Source code in src/kaptive/db/manager.py
get
classmethod
¶
get(file_or_keyword: str | Path) -> Database
Load a Database from a file path or resolve and load it by keyword.
If file_or_keyword points to an existing file, it is loaded directly.
Otherwise, it is treated as a keyword. If the keyword is not installed locally,
it will be automatically downloaded and installed.
Parameters:
Returns:
Source code in src/kaptive/db/manager.py
install
classmethod
¶
Install known, officially supported databases by keyword.
Looks up the repository details (owner, repo, database name) associated with the provided keyword(s)
in the internal registry (_KNOWN) and delegates file retrieval
and compilation to add. If 'all' or a list of keywords is
supplied, fetching is performed concurrently via a thread pool executor.
Parameters:
-
(kwd¶str | list[str]) –The keyword(s) of the known database(s) to install (e.g.,
'kpsc_k',['kpsc_k', 'ab_k'], or'all').
Returns:
Raises:
-
DatabaseError–If any keyword is not recognized in the list of known databases, or if network/parsing errors occur.
See Also
Source code in src/kaptive/db/manager.py
installed
classmethod
¶
Return a list of keywords for all currently installed databases.
Scans the local storage directory for .pkl files and extracts their keywords from the file stems.
Returns:
-
list[str]–list[str]: A list of database keywords corresponding to installed
.pkldatabase files. Returns an empty list if no databases are installed or if the storage directory does not exist.
See Also
Source code in src/kaptive/db/manager.py
known
classmethod
¶
Return a list of keywords for all currently known, officially supported databases.
These databases can be installed directly by providing their keyword to
install.
Returns:
-
list[str]–list[str]: A list of known database keywords (e.g.,
['kpsc_k', 'kpsc_o', 'kosc_k', ...]).
See Also
Source code in src/kaptive/db/manager.py
load
classmethod
¶
Load a locally installed, compiled database using its keyword.
Reads and unpickles the serialized .pkl database file from the local cache directory.
Parameters:
Returns:
Raises:
-
DatabaseError–If the specified database is not installed locally.
See Also
Source code in src/kaptive/db/manager.py
reset
classmethod
¶
Remove all installed databases by deleting their compiled files from the local directory.
This clears the user's ~/.kaptive cache directory of any .pkl database files and .json metadata
sidecar files, effectively uninstalling all downloaded and compiled databases.
Returns:
-
None–None
See Also
Source code in src/kaptive/db/manager.py
save
classmethod
¶
Serialize and save a compiled Database object and its metadata to local storage.
Saves the database as a .pkl file named {keyword}.pkl in the local cache directory (_DB_DIR).
Also writes a companion {keyword}.json file containing the serialized metadata for fast version checking.
Parameters:
Returns:
-
int(int) –The total number of bytes written to the
.pkldatabase file.
See Also
Source code in src/kaptive/db/manager.py
uninstall
classmethod
¶
Uninstall a specific database by removing its compiled local .pkl and .json files.
Parameters:
Returns:
-
None–None
Raises:
-
DatabaseError–If the specified database is not currently installed locally.
See Also
Source code in src/kaptive/db/manager.py
update
classmethod
¶
Update installed databases by checking against their remote GitHub repositories.
Extracts local metadata to determine the source repository and version, then checks the remote GitHub
repository for a newer version. If a newer version is available, the source files (.gbk and .toml)
are fetched, compiled into a new Database object, and saved to disk. When
updating multiple databases or "all", remote fetches are executed concurrently using a thread pool executor.
Parameters:
-
(kwd¶str | list[str], default:'all') –The keyword(s) of the database to update (e.g.,
'kpsc_k',['kpsc_k', 'ab_k'], or'all'). Defaults to"all", which updates all currently installed databases.
Yields:
-
Database(Database) –The newly compiled
Databaseobject for each database that required an update. Databases that are already up-to-date yield nothing.
Raises:
-
DatabaseError–If a requested database is not installed locally, or if network/parsing failures occur during update.
See Also
installed,
add,
DatabaseManager,
Database,
DatabaseMetadata,
DatabaseError
Source code in src/kaptive/db/manager.py
DatabaseMetadata
dataclass
¶
DatabaseMetadata(name: str, keyword: str, genbank: str, organism: str, taxon: int, antigen: str, pathway: str, version: str, id_threshold: float, doi: list[str], owner: str, repo: str, branch: str, contact: dict, phenotype_logic: dict, antigenic_units: dict)
Strict schema for Database metadata with dependency-free validation and ergonomic attribute access.
Represents the metadata associated with a Kaptive reference database, including organism details,
locus pathway classifications, repository location, curator contact details, and phenotype logic rules.
Used by Database and DatabaseManager.
Attributes:
-
name(str) –The name of the database, e.g. 'Klebsiella pneumoniae Species Complex K'.
-
keyword(str) –The database keyword, e.g. 'kpsc_k'.
-
genbank(str) –The name of the main database file, e.g. 'Klebsiella_pneumoniae_Species_Complex_K.gbk'.
-
organism(str) –The name of the database organism, e.g. 'Klebsiella pneumoniae Species Complex'.
-
taxon(int) –The NCBI Taxonomy ID of the database organism, e.g. 3390273.
-
antigen(str) –The name of the database antigen, e.g. 'Capsular polysaccharide'.
-
pathway(str) –The name of the database antigen synthesis pathway, e.g. 'Wzx/Wzy-dependent'.
-
version(str) –The version of the database, e.g. '3.2.1'.
-
id_threshold(float) –The identity threshold of the database, e.g. 82.5.
-
doi(list[str]) –A list of DOIs associated with the database, e.g. ['TBD'].
-
owner(str) –The owner of the database Github repo, e.g. 'klebgenomics'.
-
repo(str) –The name of the database Github repo, e.g. 'KpSC_surface_antigen_loci'.
-
branch(str) –The branch of the database Github repo, e.g. 'main'.
-
contact(dict) –The details of the database curators, e.g. {'Kelly Wyres': 'kaptive.typing@gmail.com'}.
-
phenotype_logic(dict) –Phenotype logic rules defining required loci and genes.
-
antigenic_units(dict) –Antigenic unit mappings.
Methods:
-
from_dict–Instantiates a
DatabaseMetadataobject from a dictionary.
parsed_version
property
¶
Parses the semantic version string into a tuple of integers for numeric comparison.
Extracts numeric digit sequences from the DatabaseMetadata
attribute and converts them into a tuple of integers (e.g., '3.2.1' becomes (3, 2, 1)).
Returns:
-
tuple[int, ...]–tuple[int, ...]: A tuple of extracted integer components representing the database version.
from_dict
classmethod
¶
from_dict(data: dict) -> DatabaseMetadata
Instantiates a DatabaseMetadata object from a dictionary.
Validates required fields, casts numeric types, and sets default fallback dictionaries for phenotype logic and antigenic units.
Parameters:
Returns:
-
DatabaseMetadata(DatabaseMetadata) –Validated
DatabaseMetadatainstance.
Raises:
-
DatabaseError–If
datais not a dict, missing required keys, or contains invalid attribute types.
Source code in src/kaptive/db/models.py
Phenotype
dataclass
¶
Phenotype(id: str, loci: set[str], extra_genes: set[str], inactive_genes: set[str], priority: int = 50, as_suffix: bool = False)
Single locus phenotype rule mapping loci and gene requirements to a serotype identifier.
Defines criteria for assigning a specific phenotype (e.g., K-type or O-type serotype)
based on identified reference loci, required extra genes, and forbidden inactive genes.
Processed by Database into vectorized Phenotypes
batches.
Attributes:
-
id(str) –Unique phenotype or serotype identifier string.
-
loci(set[str]) –Locus names in the database to which this phenotype applies.
-
extra_genes(set[str]) –Set of gene cluster names that must all be present for this phenotype match.
-
inactive_genes(set[str]) –Set of gene cluster names that must not be inactivated for this phenotype match.
-
priority(int) –Sorting priority when resolving multiple matching phenotypes. Defaults to
50. -
as_suffix(bool) –Whether to append this phenotype identifier as a suffix to matching phenotypes. Defaults to
False.
Phenotypes
dataclass
¶
Phenotypes(ids: NDArray[bytes_], locus_masks: NDArray[bool_], extra_masks: NDArray[int8], inactive_masks: NDArray[int8], extra_counts: NDArray[int8], priorities: NDArray[int8], as_suffix: NDArray[bool_])
flowchart TD
kaptive.db.Phenotypes[Phenotypes]
kaptive.core.collections.BatchedContainer[BatchedContainer]
kaptive.core.collections.BatchedContainer --> kaptive.db.Phenotypes
click kaptive.db.Phenotypes href "" "kaptive.db.Phenotypes"
click kaptive.core.collections.BatchedContainer href "" "kaptive.core.collections.BatchedContainer"
Structure-of-Arrays (SoA) container for vectorized phenotype evaluation.
Encapsulates boolean matrix masks and priority arrays across a batch of Phenotype
definitions for high-performance vectorized evaluation during serotyping. Inherits from
BatchedContainer.
Attributes:
-
ids(NDArray[bytes_]) –1D byte string array (e.g.
S32) of phenotype identifier strings. -
locus_masks(NDArray[bool_]) –2D boolean array of shape
(N, num_loci)indicating locus requirements. -
extra_masks(NDArray[int8]) –2D integer array of shape
(N, num_extra_genes)for required extra genes. -
inactive_masks(NDArray[int8]) –2D integer array of shape
(N, num_inactive_genes)for forbidden inactive genes. -
extra_counts(NDArray[int8]) –1D integer array storing the sum of extra required genes per phenotype.
-
priorities(NDArray[int8]) –1D integer array of shape
(N,)indicating resolution priority values. -
as_suffix(NDArray[bool_]) –1D boolean array of shape
(N,)indicating if phenotype is used as a suffix.
Methods:
-
__getitem__–Slices or masks the
Phenotypescontainer batch along the primary dimension. -
__len__–Returns the number of phenotype records in the container batch.
-
concat–Concatenates multiple
Phenotypesbatch containers into a singlePhenotypesinstance. -
empty–Constructs an empty
Phenotypesbatch container. -
from_dict–Reconstructs a
Phenotypesbatch container from a dictionary of array data. -
to_dict–Converts the
Phenotypescontainer attributes into a dictionary representation.
__getitem__
¶
Slices or masks the Phenotypes container batch along the primary dimension.
Parameters:
-
(item¶int | slice | NDArray | list) –Slice object, boolean mask array, or list of indices to select.
Returns:
-
Any | Phenotypes–Any | Phenotypes: A new
Phenotypescontainer containing the selected subset of records.
Raises:
-
NotImplementedError–If a single integer index is provided, as scalar indexing is not supported on SoA containers.
Source code in src/kaptive/db/models.py
__len__
¶
__len__() -> int
Returns the number of phenotype records in the container batch.
Returns:
-
int(int) –Number of phenotype records.
concat
classmethod
¶
Concatenates multiple Phenotypes batch containers into a single Phenotypes instance.
Parameters:
-
(batches¶Iterable[Phenotypes]) –An iterable of
Phenotypescontainer batches to concatenate.
Returns:
-
Phenotypes(Self) –A single combined
Phenotypesbatch container. Returns an empty container ifbatchesis empty.
Source code in src/kaptive/db/models.py
empty
classmethod
¶
empty() -> Phenotypes
Constructs an empty Phenotypes batch container.
Returns:
-
Phenotypes(Phenotypes) –An empty
Phenotypesinstance with 0 elements and 2D empty arrays.
Source code in src/kaptive/db/models.py
from_dict
classmethod
¶
from_dict(data: dict) -> Phenotypes
Reconstructs a Phenotypes batch container from a dictionary of array data.
Parameters:
-
(data¶dict) –Dictionary containing array and tuple entries corresponding to
Phenotypesattributes.
Returns:
-
Phenotypes(Phenotypes) –Reconstructed
Phenotypescontainer instance.
Source code in src/kaptive/db/models.py
to_dict
¶
to_dict() -> dict
Converts the Phenotypes container attributes into a dictionary representation.
Returns:
-
dict(dict) –Dictionary mapping attribute names (
ids,locus_masks,extra_masks,inactive_masks,priorities,as_suffix) to their stored values/arrays.