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.