kaptive.db.models¶
Data models and custom exception classes for Kaptive database representation.
This module provides data models, structured metadata schemas, and exception classes used by
Database and DatabaseManager
to encapsulate surface antigen reference database specifications, phenotype definitions,
and vectorized phenotype matching containers.
Classes:
-
DatabaseError–Custom exception for database loading, validation, and format errors.
-
DatabaseMetadata–Strict schema for reference database metadata with attributes and validation.
-
Phenotype–Single phenotype rule mapping loci and gene requirements to a serotype identifier.
-
Phenotypes–Structure-of-Arrays (SoA) batch container for vectorized phenotype evaluation.
DatabaseError
¶
flowchart TD
kaptive.db.models.DatabaseError[DatabaseError]
click kaptive.db.models.DatabaseError href "" "kaptive.db.models.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.
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.models.Phenotypes[Phenotypes]
kaptive.core.collections.BatchedContainer[BatchedContainer]
kaptive.core.collections.BatchedContainer --> kaptive.db.models.Phenotypes
click kaptive.db.models.Phenotypes href "" "kaptive.db.models.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.