API Reference¶
This section provides the complete API documentation for seroepi, parsed directly from the docstrings.
seroepi.accessors ¶
Module to handle epidemiological, geospatial and genotypic operations on isolate datasets in the form of Pandas DataFrames.
EpiAccessor ¶
Pandas accessor for epidemiological analysis on isolate datasets.
Provides methods for generating epidemic curves, calculating prevalence, diversity, and incidence, and identifying transmission clusters.
Source code in src/seroepi/accessors.py
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 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 | |
cluster_cols
property
¶
Returns columns suitable for cluster adjustment (e.g., transmission clusters and ST).
genotypes
property
¶
Compiles a list of all genetic variables (Core + Accessory traits).
has_spatial
property
¶
Checks if the dataset contains valid spatial coordinates (latitude and longitude).
has_temporal
property
¶
Checks if the dataset contains valid temporal data (any 'temporal_' column).
metadata_columns
property
¶
Returns the raw names of user-uploaded clinical/metadata columns.
spatial
property
¶
Returns the core spatial coordinates (latitude, longitude).
Raises:
| Type | Description |
|---|---|
ValueError
|
If spatial columns are missing. |
stratify_cols
property
¶
Returns columns suitable for stratification (excluding QC, metadata, and high-cardinality/internal cols).
temporal
property
¶
Returns a DataFrame of all temporal columns, with the prefix removed.
temporal_resolution
property
¶
Returns a DataFrame of all temporal resolution columns.
ui_metadata_columns
property
¶
Returns clean metadata names (without 'meta_' prefix) for UI display.
aggregate_diversity ¶
aggregate_diversity(stratify_by: list[str], trait_col: str = None, cluster_col: str = None, negative_indicator: Union[str, list[str]] = '-', pad_zeros: bool = False) -> pd.DataFrame
Aggregates data to calculate counts for diversity analysis (e.g., Shannon index).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stratify_by
|
list[str]
|
Columns to group by. |
required |
trait_col
|
str
|
The locus or trait to measure diversity for. |
None
|
cluster_col
|
str
|
Optional cluster column to adjust for. |
None
|
negative_indicator
|
Union[str, list[str]]
|
Value(s) to exclude from diversity counts. |
'-'
|
pad_zeros
|
bool
|
If True, pads missing combinations of strata with zero counts. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A DataFrame with 'variant_count' and 'n_total'. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If compositional diversity is requested without enough strata. |
Source code in src/seroepi/accessors.py
aggregate_incidence ¶
aggregate_incidence(stratify_by: list[str], trait_col: str = None, freq: Union[str, TemporalResolution] = TemporalResolution.MONTH, cluster_col: str = None, negative_indicator: Union[str, list[str]] = '-', pad_zeros: bool = False, temporal_col: str = None) -> pd.DataFrame
Aggregates data for time-series incidence analysis.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stratify_by
|
list[str]
|
Columns to group by. |
required |
trait_col
|
str
|
The marker to measure incidence for. |
None
|
freq
|
Union[str, TemporalResolution]
|
Time frequency for binning (e.g., TimeResolution.MONTH, 'ME'). Defaults to TimeResolution.MONTH. |
MONTH
|
cluster_col
|
str
|
Optional cluster column to adjust for. |
None
|
negative_indicator
|
Union[str, list[str]]
|
Value(s) representing absence. |
'-'
|
pad_zeros
|
bool
|
If True, pads missing combinations of strata. If False, maintains unbroken time grids only for observed strata combinations. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A DataFrame with 'variant_count', 'total_sequenced', and binned dates. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If temporal data is missing or inappropriate strata provided. |
Source code in src/seroepi/accessors.py
531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 | |
aggregate_prevalence ¶
aggregate_prevalence(stratify_by: list[str], trait_col: str = None, cluster_col: str = None, negative_indicator: Union[str, list[str]] = '-', pad_zeros: bool = False) -> pd.DataFrame
Aggregates data to calculate event counts and denominators for prevalence.
Supports both trait prevalence (presence/absence of a marker) and compositional prevalence (distribution of variants within a locus).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stratify_by
|
list[str]
|
Columns to group by (e.g., ['spatial']). |
required |
trait_col
|
str
|
The column containing the trait/marker to measure.
If None, compositional prevalence is calculated for the last
column in |
None
|
cluster_col
|
str
|
Column containing cluster IDs to adjust for (e.g., nosocomial outbreaks). |
None
|
negative_indicator
|
Union[str, list[str]]
|
Value(s) representing the absence of a trait. Defaults to '-'. |
'-'
|
pad_zeros
|
bool
|
If True, pads missing combinations of strata with zero counts. Essential for spatial/hierarchical models. If False, only includes observed combinations for efficiency. Defaults to False. |
False
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
An aggregated DataFrame with 'event' and 'n' columns. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If compositional prevalence is requested without enough strata. |
Source code in src/seroepi/accessors.py
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 | |
epidemic_curve ¶
epidemic_curve(freq: Union[str, TemporalResolution] = TemporalResolution.WEEK, stratify_by: str = None, temporal_col: str = None) -> pd.DataFrame
Generates a time-series DataFrame for plotting epidemic curves.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
freq
|
Union[str, TemporalResolution]
|
Time frequency for resampling (e.g., TimeResolution.MONTH, 'ME', 'YE'). Defaults to TimeResolution.WEEK. |
WEEK
|
stratify_by
|
str
|
Column name to group by before resampling. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A DataFrame with counts of isolates per time interval. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If temporal data is not available. |
Source code in src/seroepi/accessors.py
transmission_clusters ¶
transmission_clusters(clone_col: str, spatial_threshold_km: float = 10.0, temporal_threshold_days: int = 20, temporal_col: str = None, network: TransmissionDistances = None) -> pd.Series
Extracts and formats categorical cluster labels from the transmission network.
Source code in src/seroepi/accessors.py
transmission_network ¶
transmission_network(clone_col: str, spatial_threshold_km: float = 10.0, temporal_threshold_days: int = 20, temporal_col: str = None) -> TransmissionDistances
Builds a sparse adjacency graph of transmission links.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
clone_col
|
str
|
Column containing clone IDs (e.g., 'ST' or a custom cluster). |
required |
spatial_threshold_km
|
float
|
Maximum distance in kilometers. Defaults to 10.0. |
10.0
|
temporal_threshold_days
|
int
|
Maximum time difference in days. Defaults to 20. |
20
|
Returns:
| Type | Description |
|---|---|
TransmissionDistances
|
A TransmissionDistances object representing the outbreak network. |
Raises:
| Type | Description |
|---|---|
KeyError
|
If required columns ('latitude', 'longitude', 'date') are missing. |
Source code in src/seroepi/accessors.py
GenoAccessor ¶
Pandas accessor for genetic and trait-based operations.
Provides methods for filtering determinants, checking for trait patterns, and sorting loci.
Examples:
>>> import pandas as pd
>>> import seroepi.accessors
>>> df = pd.DataFrame({'amr_blaKPC': [True, False], 'vir_ybt': [True, True]})
>>> amr_matrix = df.geno.amr
Source code in src/seroepi/accessors.py
736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 | |
amr
property
¶
Returns the AMR determinant matrix with the prefix removed from names.
genotype
property
¶
Returns the Core Genotype matrix with the prefix removed from names.
phenotype
property
¶
Returns the Phenotype matrix with the prefix removed from names.
virulence
property
¶
Returns the Virulence marker matrix with the prefix removed from names.
has_all ¶
Checks if isolates possess ALL of the specified traits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
traits
|
list[str]
|
List of trait names. |
required |
domain
|
Union[str, Domain]
|
Domain prefix (e.g., Domain.VIRULENCE). Defaults to Domain.VIRULENCE. |
VIRULENCE
|
Returns:
| Type | Description |
|---|---|
Series
|
A boolean Series. |
Source code in src/seroepi/accessors.py
has_any ¶
Checks if isolates possess ANY of the specified traits.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
traits
|
list[str]
|
List of trait names (without prefix). |
required |
domain
|
Union[str, Domain]
|
The domain prefix (e.g., Domain.AMR, Domain.VIRULENCE). Defaults to Domain.AMR. |
AMR
|
Returns:
| Type | Description |
|---|---|
Series
|
A boolean Series indicating presence of any specified trait. |
Source code in src/seroepi/accessors.py
has_gene ¶
Searches for a specific gene within a comma-separated column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
gene_col
|
str
|
Column name containing gene lists. |
required |
gene_name
|
str
|
The specific gene to find. |
required |
Returns:
| Type | Description |
|---|---|
Series
|
A boolean Series. |
Source code in src/seroepi/accessors.py
sort_loci ¶
Sorts the DataFrame numerically by locus (e.g., K2 before K10).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
locus_col
|
str
|
Column containing locus names. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
A sorted copy of the DataFrame. |
Source code in src/seroepi/accessors.py
GeoAccessor ¶
Pandas accessor for geographical operations on isolate datasets.
Provides methods for standardizing location names, imputing missing coordinates using a gazetteer, and performing reverse geocoding.
Attributes:
| Name | Type | Description |
|---|---|---|
gazetteer |
DataFrame
|
A DataFrame containing centroid coordinates and metadata for countries. |
Source code in src/seroepi/accessors.py
18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 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 | |
gazetteer
property
¶
Returns the internal gazetteer used for coordinate imputation.
spatial
property
¶
Returns a DataFrame of all spatial columns, with the prefix removed.
spatial_resolution
property
¶
Returns a DataFrame of all spatial resolution columns.
reverse_geocode ¶
reverse_geocode(geojson_path: Union[str, Path] = None, target_spatial_name: str = 'Country') -> pd.DataFrame
Performs reverse geocoding to determine spatial locality from coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
geojson_path
|
Union[str, Path]
|
Optional path to a GeoJSON file containing boundary polygons. Defaults to the built-in world_boundaries.geojson. |
None
|
target_spatial_name
|
str
|
The name to append to the spatial domain prefix. |
'Country'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A new DataFrame with updated 'spatial' information. |
Source code in src/seroepi/accessors.py
standardize_and_impute ¶
Standardizes spatial names and imputes missing coordinates.
Uses the internal gazetteer to find centroids for countries when exact latitude and longitude are missing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
spatial_col
|
str
|
Optional specific spatial column to impute by. Defaults to the first mapped spatial column. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A new DataFrame with imputed coordinates and spatial resolution metadata. |
Source code in src/seroepi/accessors.py
QCAccessor ¶
Pandas accessor for quality control operations.
Provides methods for filtering assemblies based on metrics like N50 and contig count.
Examples:
>>> import pandas as pd
>>> import seroepi.accessors
>>> df = pd.DataFrame({'qc_N50': [50000, 5000]})
>>> clean_df = df.qc.filter_assemblies(min_n50=10000)
Source code in src/seroepi/accessors.py
filter_assemblies ¶
filter_assemblies(min_n50: int = 10000, max_contigs: int = 500, require_species: str = None) -> pd.DataFrame
Filters genomes based on quality thresholds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min_n50
|
int
|
Minimum N50 value. Defaults to 10000. |
10000
|
max_contigs
|
int
|
Maximum number of contigs. Defaults to 500. |
500
|
require_species
|
str
|
Optional species name to filter for. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A filtered copy of the DataFrame. |
Source code in src/seroepi/accessors.py
report ¶
Generates a summary report of dataset quality.
Returns:
| Type | Description |
|---|---|
Series
|
A Series containing summary metrics (e.g., Total Warnings, Median N50). |
Source code in src/seroepi/accessors.py
seroepi.formulation ¶
Module for abstracting a vaccine _formulation using trait prevalence and stability.
BaseFormulationDesigner ¶
Bases: ModelledMixin, ABC
Abstract base class for _formulation designers.
Designers are responsible for evaluating prevalence estimates and generating a vaccine _formulation with stability metrics.
Attributes:
| Name | Type | Description |
|---|---|---|
valency |
The target valency (number of targets) for the vaccine. |
|
n_jobs |
The number of CPU cores to use for processing (-1 for all). |
|
formulation_ |
Optional[Formulation]
|
The resulting Formulation object after fitting. |
Source code in src/seroepi/formulation.py
__init__ ¶
Initializes the designer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
valency
|
int
|
The target valency. Defaults to 6. |
6
|
n_jobs
|
int
|
Number of concurrent workers. Defaults to -1 (all available). |
-1
|
Source code in src/seroepi/formulation.py
fit ¶
fit(*args, progress_callback: Optional[Callable[[int, int], None]] = None, **kwargs) -> BaseFormulationDesigner
Calculates the formulation and stores it in self.formulation
predict ¶
Uses the fitted _formulation to predict vaccine coverage on a given DataFrame. Returns only the rows that are covered by the designed _formulation.
Source code in src/seroepi/formulation.py
CVFormulationDesigner ¶
Bases: BaseFormulationDesigner
Rigorous _formulation design using true Leave-One-Out (LOO) cross-validation.
This method retrains the model for each LOO permutation, which is more computationally expensive but necessary for complex models.
Source code in src/seroepi/formulation.py
fit ¶
fit(estimator: BaseEstimator, agg_df: DataFrame, loo_col: str, progress_callback: Optional[Callable[[int, int], None]] = None) -> CVFormulationDesigner
Evaluates an estimator using LOO cross-validation to design a _formulation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
BaseEstimator
|
The estimator instance to use. |
required |
agg_df
|
DataFrame
|
The aggregated data for the estimator. |
required |
loo_col
|
str
|
The column name to use for Leave-One-Out cross-validation. |
required |
Returns:
| Type | Description |
|---|---|
CVFormulationDesigner
|
The fitted designer instance. |
Source code in src/seroepi/formulation.py
Formulation
dataclass
¶
Represents a proposed vaccine _formulation based on target prevalence and stability.
This class holds the results of a _formulation design process, including rankings, stability metrics from cross-validation, and permutation history.
Attributes:
| Name | Type | Description |
|---|---|---|
trait |
str
|
The trait type (e.g., 'K_locus'). |
max_valency |
int
|
The maximum number of targets in the _formulation. |
rankings |
DataFrame
|
A DataFrame containing the definitive ranking of targets (Trait, Rank, Prevalence, Cumulative Coverage). |
stability_metrics |
DataFrame
|
A DataFrame containing metrics from LOO stability analysis (e.g., Mean LOO Rank, Rank Variance, Probability in Top N). |
permutation_history |
DataFrame
|
A DataFrame containing the full history of ranks across all LOO permutations. |
Examples:
>>> import pandas as pd
>>> from seroepi.formulation import Formulation
>>> rankings = pd.DataFrame({'trait': ['K1', 'K2'], 'estimate': [0.5, 0.3]})
>>> _formulation = Formulation(
... trait='K_locus',
... max_valency=2,
... rankings=rankings,
... stability_metrics=pd.DataFrame(),
... permutation_history=pd.DataFrame()
... )
>>> print(_formulation.get_formulation())
['K1', 'K2']
Source code in src/seroepi/formulation.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 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 | |
evaluate_longevity ¶
Evaluates the formulation against a time-series incidence forecast to determine its historical and projected longevity.
Returns a DataFrame tracking the absolute case burden and the percentage of that burden covered by this formulation over time.
Source code in src/seroepi/formulation.py
from_custom
classmethod
¶
Creates a custom Formulation from a user-defined list of targets. Calculates the baseline coverage for these specific targets.
Source code in src/seroepi/formulation.py
get_formulation ¶
Returns the top N targets for the proposed vaccine.
Returns:
| Type | Description |
|---|---|
list[str]
|
A list of target names. |
load
classmethod
¶
Loads a serialized Formulation from disk.
Source code in src/seroepi/formulation.py
save ¶
PostHocFormulationDesigner ¶
Bases: BaseFormulationDesigner
Fast formulation design using post-hoc estimation.
This method computes stability exactly for Frequentist estimates where retraining is not required for Leave-One-Out (LOO) analysis. For complex modelled estimates (e.g., Bayesian, Spatial), it can be used as a fast, linear approximation of stability (ignoring non-linear shrinkage and spatial correlation).
Source code in src/seroepi/formulation.py
fit ¶
fit(result: PrevalenceEstimates, loo_col: str, progress_callback: Optional[Callable[[int, int], None]] = None) -> PostHocFormulationDesigner
Evaluates prevalence results to design a _formulation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result
|
PrevalenceEstimates
|
The prevalence estimates to evaluate. |
required |
loo_col
|
str
|
The column name to use for Leave-One-Out cross-validation. |
required |
Returns:
| Type | Description |
|---|---|
PostHocFormulationDesigner
|
The fitted designer instance. |
Source code in src/seroepi/formulation.py
seroepi.estimators ¶
Module for estimating trait prevalence, diversity and incidence among isolates.
AlphaDiversityEstimates
dataclass
¶
Bases: Estimates
Container for Alpha Diversity results.
Attributes:
| Name | Type | Description |
|---|---|---|
metrics |
list[str]
|
List of diversity metrics calculated (e.g., ['shannon', 'simpson']). |
Source code in src/seroepi/estimators/_base.py
AlphaDiversityEstimator ¶
Bases: BaseEstimator[AlphaDiversityEstimates]
Source code in src/seroepi/estimators/_core.py
BaseEstimator ¶
Bases: ABC, Generic[T_Result]
The universal contract for all seroepi statistical models.
All prevalence, diversity, and incidence estimators must inherit from this
class and implement the calculate method.
Source code in src/seroepi/estimators/_base.py
calculate
abstractmethod
¶
Executes the estimator's logic on the provided DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
The input DataFrame (usually aggregated). |
required |
Returns:
| Type | Description |
|---|---|
T_Result
|
An Estimates object (e.g., PrevalenceEstimates). |
Source code in src/seroepi/estimators/_base.py
BayesianIncidenceEstimator ¶
Bases: ModelledMixin, BayesianMixin, BaseEstimator[IncidenceEstimates]
Bayesian Structural Time Series (BSTS) for incidence forecasting.
Uses a Gaussian Random Walk with drift to model latent log-incidence, and a Negative Binomial likelihood to handle overdispersed clinical count data.
Source code in src/seroepi/estimators/_modelled.py
787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 | |
fit ¶
Pivots the count data into a matrix and fits the BSTS model.
Source code in src/seroepi/estimators/_modelled.py
predict ¶
Forecasts future incidence counts using the fitted posterior samples.
Source code in src/seroepi/estimators/_modelled.py
893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 | |
BayesianMixin ¶
Shared inference logic for NumPyro-based Bayesian estimators.
Source code in src/seroepi/estimators/_modelled.py
123 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 | |
diagnostics ¶
Returns MCMC diagnostics (R-hat, ESS) as a formatted DataFrame.
Source code in src/seroepi/estimators/_modelled.py
BayesianPrevalenceEstimator ¶
Bases: ModelledMixin, BayesianMixin, BaseEstimator[PrevalenceEstimates]
Bayesian hierarchical model for prevalence estimation.
This estimator uses MCMC or SVI to fit a binomial model with random effects for groups and fixed effects for targets. It handles overdispersion and provides credible intervals.
Examples:
>>> from seroepi.estimators import BayesianPrevalenceEstimator
>>> estimator = BayesianPrevalenceEstimator(method='mcmc')
>>> # result = estimator.calculate(agg_df)
Source code in src/seroepi/estimators/_modelled.py
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 | |
__init__ ¶
__init__(method: BayesianInferenceMethod = BayesianInferenceMethod.MCMC, num_samples: int = 1500, num_chains: int = 4, num_warmup: int = 1000, svi_steps: int = 3000, target_event: str = 'event', target_n: str = 'n', seed: int = 42)
Initializes the BayesianPrevalenceEstimator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
BayesianInferenceMethod
|
Inference method ('mcmc' or 'svi'). Defaults to 'mcmc'. |
MCMC
|
num_samples
|
int
|
Number of posterior samples to draw. Defaults to 1500. |
1500
|
num_chains
|
int
|
Number of MCMC chains. Defaults to 4. |
4
|
num_warmup
|
int
|
Number of warmup steps for MCMC. Defaults to 1000. |
1000
|
svi_steps
|
int
|
Number of optimization steps for SVI. Defaults to 3000. |
3000
|
target_event
|
str
|
Column name for event counts. Defaults to 'event'. |
'event'
|
target_n
|
str
|
Column name for total counts (denominators). Defaults to 'n'. |
'n'
|
seed
|
int
|
Random seed for reproducibility. Defaults to 42. |
42
|
Source code in src/seroepi/estimators/_modelled.py
fit ¶
Parses data, fits encoders, and runs inference to get posterior samples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agg_df
|
DataFrame
|
The aggregated DataFrame. |
required |
Returns:
| Type | Description |
|---|---|
BayesianPrevalenceEstimator
|
The fitted estimator instance. |
Source code in src/seroepi/estimators/_modelled.py
predict ¶
Uses the fitted samples and encoders to calculate prevalence bounds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
agg_df
|
DataFrame
|
The DataFrame to generate predictions for. |
required |
Returns:
| Type | Description |
|---|---|
PrevalenceEstimates
|
A PrevalenceEstimates object. |
Source code in src/seroepi/estimators/_modelled.py
BetaDiversityEstimates
dataclass
¶
Bases: Estimates
Container for Beta Diversity results (distance matrices).
Attributes:
| Name | Type | Description |
|---|---|---|
metric |
str
|
The distance metric used (e.g., 'braycurtis'). |
Source code in src/seroepi/estimators/_base.py
BetaDiversityEstimator ¶
Bases: BaseEstimator[BetaDiversityEstimates]
Source code in src/seroepi/estimators/_core.py
__init__ ¶
Calculates between-group dissimilarity. Common metrics: 'braycurtis' (abundance-weighted), 'jaccard' (presence/absence).
Source code in src/seroepi/estimators/_core.py
Estimates
dataclass
¶
Base container for statistical estimates.
Attributes:
| Name | Type | Description |
|---|---|---|
data |
DataFrame
|
A DataFrame containing the estimates and original strata. |
stratified_by |
list[str]
|
List of columns used for stratification. |
adjusted_for |
Optional[str]
|
Column name used for cluster adjustment, if any. |
trait |
str
|
The trait variable for which estimates were calculated. |
Source code in src/seroepi/estimators/_base.py
GLMIncidenceEstimator ¶
Bases: ModelledMixin, BaseEstimator[IncidenceEstimates]
Negative Binomial GLM for time-series incidence estimation.
Fits a Negative Binomial model to count data over time, optionally adjusting for sequencing volume (relative incidence).
Examples:
>>> from seroepi.estimators import GLMIncidenceEstimator
>>> estimator = GLMIncidenceEstimator(use_relative_incidence=True)
>>> # result = estimator.calculate(inc_df)
Source code in src/seroepi/estimators/_modelled.py
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 | |
__init__ ¶
Initializes the GLMIncidenceEstimator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
use_relative_incidence
|
bool
|
If True, models cases adjusting for total sequencing volume (offset). If False, models absolute counts. |
True
|
forecast_horizon
|
int
|
Number of future time steps to project. Defaults to 0. |
0
|
Source code in src/seroepi/estimators/_modelled.py
fit ¶
Fits the Negative Binomial GLM to each stratum.
Source code in src/seroepi/estimators/_modelled.py
predict ¶
Extracts Incidence Rate Ratios (IRR) and forecasts trends.
Source code in src/seroepi/estimators/_modelled.py
681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 | |
GLMPrevalenceEstimator ¶
Bases: ModelledMixin, BaseEstimator[PrevalenceEstimates]
Frequentist binomial GLM for prevalence estimation.
Uses statsmodels to fit a Generalized Linear Model with a binomial family and logit link.
Source code in src/seroepi/estimators/_modelled.py
__init__ ¶
Initializes the GLMPrevalenceEstimator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_event
|
str
|
Column name for event counts. Defaults to 'event'. |
'event'
|
target_n
|
str
|
Column name for total counts. Defaults to 'n'. |
'n'
|
Source code in src/seroepi/estimators/_modelled.py
fit ¶
Fits the binomial GLM.
Source code in src/seroepi/estimators/_modelled.py
predict ¶
Generates predictions and confidence intervals.
Source code in src/seroepi/estimators/_modelled.py
IncidenceEstimates
dataclass
¶
Bases: Estimates
Container for time-series incidence results.
Attributes:
| Name | Type | Description |
|---|---|---|
freq |
str
|
The time resolution used (e.g., TemporalResolution.MONTH.value). |
model_results |
DataFrame
|
A DataFrame containing regression outputs (IRR, CIs, P-values). |
Source code in src/seroepi/estimators/_base.py
ModelledMixin ¶
Bases: ABC
Contract for estimators with an internal fitted state.
Enforces the scikit-learn fit/predict paradigm and provides universal serialization for fitted models.
Attributes:
| Name | Type | Description |
|---|---|---|
is_fitted_ |
bool
|
Boolean indicating if the model has been fitted. |
Source code in src/seroepi/estimators/_modelled.py
calculate ¶
check_is_fitted ¶
Checks if the model is fitted.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the model has not been fitted. |
Source code in src/seroepi/estimators/_modelled.py
fit
abstractmethod
¶
load_model
classmethod
¶
Loads a serialized estimator from disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
Union[str, Path]
|
Path to the serialized model file. |
required |
Returns:
| Type | Description |
|---|---|
T_Modelled
|
The loaded estimator instance. |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the file does not exist. |
TypeError
|
If the loaded model is not of the expected type. |
Source code in src/seroepi/estimators/_modelled.py
predict
abstractmethod
¶
save_model ¶
Universally serializes the fitted estimator instance to disk.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath
|
Union[str, Path]
|
Path where the model should be saved. |
required |
Source code in src/seroepi/estimators/_modelled.py
PrevalenceEstimates
dataclass
¶
Bases: Estimates
Container for prevalence results.
Attributes:
| Name | Type | Description |
|---|---|---|
method |
str
|
The statistical method used (e.g., 'bayesian_mcmc'). |
Source code in src/seroepi/estimators/_base.py
SpatialPrevalenceEstimator ¶
Bases: ModelledMixin, BayesianMixin, BaseEstimator[PrevalenceEstimates]
Gaussian Process (GP) based spatial prevalence estimator.
Fits a GP model to spatial binomial data, allowing for continuous mapping of prevalence across a geographic area.
Examples:
>>> from seroepi.estimators import SpatialPrevalenceEstimator
>>> estimator = SpatialPrevalenceEstimator(lat_col='lat', lon_col='lon')
>>> # result = estimator.calculate(agg_df)
Source code in src/seroepi/estimators/_modelled.py
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 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 | |
__init__ ¶
__init__(lat_col: str = 'lat', lon_col: str = 'lon', method: BayesianInferenceMethod = BayesianInferenceMethod.MCMC, num_samples: int = 1500, num_chains: int = 4, num_warmup: int = 1000, svi_steps: int = 3000, target_event: str = 'event', target_n: str = 'n', seed: int = 42)
Initializes the SpatialPrevalenceEstimator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lat_col
|
str
|
Column name for latitude. Defaults to 'lat'. |
'lat'
|
lon_col
|
str
|
Column name for longitude. Defaults to 'lon'. |
'lon'
|
method
|
BayesianInferenceMethod
|
Inference method. Defaults to 'mcmc'. |
MCMC
|
num_samples
|
int
|
Number of samples. Defaults to 1500. |
1500
|
num_chains
|
int
|
Number of chains. Defaults to 4. |
4
|
num_warmup
|
int
|
Number of warmup steps. Defaults to 1000. |
1000
|
svi_steps
|
int
|
Number of SVI steps. Defaults to 3000. |
3000
|
target_event
|
str
|
Column for events. Defaults to 'event'. |
'event'
|
target_n
|
str
|
Column for totals. Defaults to 'n'. |
'n'
|
seed
|
int
|
Random seed. Defaults to 42. |
42
|
Source code in src/seroepi/estimators/_modelled.py
fit ¶
Aggregates to unique locations, normalizes, and fits the GP.
Source code in src/seroepi/estimators/_modelled.py
predict ¶
Calculates the conditional predictive posterior for any set of coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
DataFrame containing latitude and longitude columns. |
required |
Returns:
| Type | Description |
|---|---|
PrevalenceEstimates
|
A PrevalenceEstimates object with predicted values at the locations. |
Source code in src/seroepi/estimators/_modelled.py
UnpooledPrevalenceEstimator ¶
Bases: BaseEstimator[PrevalenceEstimates]
Source code in src/seroepi/estimators/_core.py
calculate ¶
Expects the output of df.epi.aggregate_prevalence()
Source code in src/seroepi/estimators/_core.py
get_params ¶
seroepi.plotting ¶
BasePlotter ¶
Bases: ABC
Stateless base class for all plotting engines in seroepi.
Source code in src/seroepi/plotting.py
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 | |
apply_theme
classmethod
¶
Applies a universal transparent theme optimized for both light and dark web app modes.
Source code in src/seroepi/plotting.py
can_render
classmethod
¶
Checks if the incoming result object is supported by this plotter.
Source code in src/seroepi/plotting.py
get_colorscale
classmethod
¶
Returns the standard Cyberpunk continuous color scale.
Source code in src/seroepi/plotting.py
render
abstractmethod
classmethod
¶
Renders the result object into a Plotly figure.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result_obj
|
Any
|
The result object to visualize. |
required |
**kwargs
|
Additional plotting arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
Figure
|
A plotly Figure object. |
Source code in src/seroepi/plotting.py
CumulativeCoveragePlotter ¶
Bases: BasePlotter
Calculates cumulative population coverage. Crucial for designing multivalent vaccines (e.g., K-locus targeting).
Source code in src/seroepi/plotting.py
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 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 | |
NetworkPlotter ¶
Bases: BasePlotter
Source code in src/seroepi/plotting.py
883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 | |
render_plot ¶
A central router that invokes the correct plotter for the desired plot type.
Source code in src/seroepi/plotting.py
seroepi.io ¶
Module for genotype file I/O and parsing.
BaseGenotypeParser ¶
Base class for standardizing external datasets.
Subclasses must define column mappings and category definitions for specific input formats (e.g., Kleborate output).
Source code in src/seroepi/io.py
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 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 | |
from_files
classmethod
¶
from_files(genotype_path: Union[str, Path], meta_path: Optional[Union[str, Path]] = None, meta_kwargs: dict = None, dataset_name: str = 'Unknown Dataset') -> pd.DataFrame
Convenience factory to read CSV files and parse them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
genotype_path
|
Union[str, Path]
|
Path to the raw genotype CSV. |
required |
meta_path
|
Optional[Union[str, Path]]
|
Optional path to the metadata CSV. |
None
|
meta_kwargs
|
dict
|
Arguments for metadata ingestion. |
None
|
dataset_name
|
str
|
Name to tag the resulting dataset with. |
'Unknown Dataset'
|
Source code in src/seroepi/io.py
from_records
classmethod
¶
from_records(records: list[dict], meta_df: Optional[DataFrame] = None, meta_kwargs: dict = None, sep: str = '/', dataset_name: str = 'Unknown Dataset') -> pd.DataFrame
Convenience factory to read a list of nested dictionaries (e.g., from an API) and parse them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
records
|
list[dict]
|
List of nested dictionaries. |
required |
meta_df
|
Optional[DataFrame]
|
Optional metadata DataFrame to merge. |
None
|
meta_kwargs
|
dict
|
Arguments for metadata ingestion. |
None
|
sep
|
str
|
Separator for flattening nested JSON keys. Defaults to '/'. |
'/'
|
dataset_name
|
str
|
Name to tag the resulting dataset with. |
'Unknown Dataset'
|
Source code in src/seroepi/io.py
parse
classmethod
¶
parse(genotype_df: DataFrame, meta_df: Optional[DataFrame] = None, meta_kwargs: dict = None, dataset_name: str = 'Unknown Dataset') -> pd.DataFrame
Parses and validates a genotype dataset, optionally merging with metadata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
genotype_df
|
DataFrame
|
The raw genotype DataFrame. |
required |
meta_df
|
Optional[DataFrame]
|
Optional metadata DataFrame to merge. |
None
|
meta_kwargs
|
dict
|
Arguments for metadata ingestion (e.g., column names). |
None
|
dataset_name
|
str
|
Name to tag the resulting dataset with. |
'Unknown Dataset'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A validated DataFrame conforming to UnifiedIsolateSchema. |
Source code in src/seroepi/io.py
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 | |
PathogenwatchKleborateParser ¶
Bases: BaseGenotypeParser
Adapter for Kleborate files downloaded from Pathogenwatch.
This parser maps Kleborate's specific column names and categories to the UnifiedIsolateSchema.
Source code in src/seroepi/io.py
UnifiedIsolateSchema ¶
Bases: DataFrameModel
Pandera schema for validating and standardizing isolate datasets.
This schema ensures that all input data, whether from Pathogenwatch or user uploads, conforms to a unified structure for downstream analysis.
Attributes:
| Name | Type | Description |
|---|---|---|
sample_id |
Series[string]
|
Unique identifier for each isolate. |
latitude |
Optional[Series[Float64]]
|
Latitude coordinate (-90 to 90). |
longitude |
Optional[Series[Float64]]
|
Longitude coordinate (-180 to 180). |
qc_metrics |
Optional[Series[Float64]]
|
Dynamic columns for quality control (prefixed with 'qc_'). |
geno_traits |
Optional[Series[Float64]]
|
Dynamic columns for genotypes/alleles (prefixed with 'geno_'). |
pheno_traits |
Optional[Series[Float64]]
|
Dynamic columns for phenotypic traits (prefixed with 'pheno_'). |
amr_traits |
Optional[Series[Float64]]
|
Dynamic columns for AMR markers (prefixed with 'amr_'). |
vir_traits |
Optional[Series[Float64]]
|
Dynamic columns for virulence markers (prefixed with 'vir_'). |
temporal_cols |
Optional[Series[Float64]]
|
Dynamic columns for temporal data (prefixed with 'temporal_'). |
temporal_res_cols |
Optional[Series[Float64]]
|
Dynamic columns for temporal resolution (prefixed with 'temporal_res_'). |
spatial_cols |
Optional[Series[Float64]]
|
Dynamic columns for spatial data (prefixed with 'spatial_'). |
spatial_res_cols |
Optional[Series[Float64]]
|
Dynamic columns for spatial resolution (prefixed with 'spatial_res_'). |
user_metadata |
Optional[Series[Float64]]
|
Dynamic columns for user metadata (prefixed with 'meta_'). |
Examples:
>>> import pandas as pd
>>> df = pd.DataFrame({'sample_id': ['S1'], 'K_locus': ['KL1']})
>>> validated_df = UnifiedIsolateSchema.validate(df)
Source code in src/seroepi/io.py
seroepi.dist ¶
Module to handle genetic distance measures between isolates.
DistancesBase
dataclass
¶
Bases: ABC
Source code in src/seroepi/dist.py
__post_init__ ¶
Validates the consistency of the distance matrix and labels.
Source code in src/seroepi/dist.py
layout ¶
Calculates a 2D layout for the distance matrix using Multi-Dimensional Scaling (MDS).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
random_state
|
int
|
Seed for reproducibility. Defaults to 42. |
42
|
n_init
|
int
|
Number of initialization runs. Defaults to 1 for speed. |
1
|
max_iter
|
int
|
Maximum iterations. Defaults to 100 for speed. |
100
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A numpy array of shape (n_samples, 2) containing the 2D coordinates. |
Source code in src/seroepi/dist.py
GenomicDistances
dataclass
¶
Bases: DistancesBase
Source code in src/seroepi/dist.py
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 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 | |
from_file
classmethod
¶
from_file(filepath_or_buffer: Union[str, Path], flavour: Union[str, DistanceFlavour]) -> GenomicDistances
Factory method to parse a distance matrix or tree from a file based on flavour.
Source code in src/seroepi/dist.py
from_newick
classmethod
¶
Parses a Newick string and calculates patristic distances.
Requires Biopython (pip install biopython).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
newick_string
|
str
|
The Newick tree string. |
required |
Returns:
| Type | Description |
|---|---|
GenomicDistances
|
A new Distances instance. |
Raises:
| Type | Description |
|---|---|
ImportError
|
If biopython is not installed. |
Source code in src/seroepi/dist.py
from_pairwise
classmethod
¶
from_pairwise(query_col: Series, target_col: Series, weight_col: Series, metric_type: DistanceMetricType = DistanceMetricType.ABSOLUTE_DISTANCE) -> GenomicDistances
Creates a Distances instance from long-format pairwise data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
query_col
|
Series
|
Series containing the first isolate IDs. |
required |
target_col
|
Series
|
Series containing the second isolate IDs. |
required |
weight_col
|
Series
|
Series containing the distances/similarities. |
required |
metric_type
|
DistanceMetricType
|
The type of metric provided. Defaults to ABSOLUTE_DISTANCE. |
ABSOLUTE_DISTANCE
|
Returns:
| Type | Description |
|---|---|
GenomicDistances
|
A new Distances instance. |
Source code in src/seroepi/dist.py
from_pathogenwatch
classmethod
¶
Parses a square distance matrix from Pathogenwatch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath_or_buffer
|
Path to the Pathogenwatch CSV file. |
required |
Returns:
| Type | Description |
|---|---|
GenomicDistances
|
A new Distances instance. |
Source code in src/seroepi/dist.py
from_ska2
classmethod
¶
Parses a pairwise distance matrix from SKA2 output.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
filepath_or_buffer
|
Path to the SKA2 distance file. |
required |
Returns:
| Type | Description |
|---|---|
GenomicDistances
|
A new Distances instance. |
Source code in src/seroepi/dist.py
get_clusters ¶
Identifies clusters via connected components based on a distance threshold.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
threshold
|
int
|
Maximum distance to consider isolates as connected. Defaults to 20 (e.g., 20 SNPs). |
20
|
Returns:
| Type | Description |
|---|---|
Series
|
A Series of cluster labels indexed by isolate IDs. |
Source code in src/seroepi/dist.py
to_type ¶
Converts the distances to a different metric type.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target_type
|
DistanceMetricType
|
The desired target MetricType. |
required |
Returns:
| Type | Description |
|---|---|
GenomicDistances
|
A new Distances instance with the converted matrix. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If conversion requires |
Source code in src/seroepi/dist.py
TransmissionDistances
dataclass
¶
Bases: DistancesBase
Source code in src/seroepi/dist.py
from_spatiotemporal
classmethod
¶
from_spatiotemporal(sample_ids: Series, coords: ndarray, dates: ndarray, clones: ndarray, spatial_threshold_km: float = 10.0, temporal_threshold_days: int = 20) -> TransmissionDistances
Builds a sparse transmission adjacency graph from spatiotemporal arrays.
Source code in src/seroepi/dist.py
get_clusters ¶
Extracts cluster labels directly from the pre-computed adjacency network.
Source code in src/seroepi/dist.py
seroepi.constants ¶
Enums for non-user-facing API constants - mostly to help with the app
DistanceMetricType ¶
Bases: StrEnum
Enumeration of supported metric types for pairwise comparisons.
These metric types define how to interpret the numerical values in a distance/similarity matrix.
Attributes:
| Name | Type | Description |
|---|---|---|
ABSOLUTE_DISTANCE |
An absolute distance measure (e.g., 5 SNPs). |
|
RELATIVE_DISTANCE |
A relative distance measure typically between 0.0 and 1.0 (e.g., 0.05 Hamming). |
|
ABSOLUTE_SIMILARITY |
An absolute similarity measure (e.g., 95 shared nucleotides). |
|
RELATIVE_SIMILARITY |
A relative similarity measure typically between 0.0 and 1.0 (e.g., 0.95 Jaccard). |
Source code in src/seroepi/constants.py
TemporalResolution ¶
Bases: _UiEnum
Source code in src/seroepi/constants.py
seroepi.client ¶
Module to interact with the Pathogenwatch Next API.
PathogenwatchClient ¶
Client for the Pathogenwatch Next API.
Handles automatic retries, rate limiting, and pagination. It uses a session with a retry strategy to handle common transient errors and rate limits.
Attributes:
| Name | Type | Description |
|---|---|---|
session |
Session
|
The underlying requests session with retry strategy. |
Examples:
>>> from seroepi.client import PathogenwatchClient
>>> with PathogenwatchClient(api_key="your_api_key") as client:
... collections = list(client.get_collections(limit=5))
... for collection in collections:
... print(collection.name)
Source code in src/seroepi/client.py
13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 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 | |
__enter__ ¶
__exit__ ¶
__init__ ¶
Initializes the PathogenwatchClient with an API key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
api_key
|
str
|
The API key for Pathogenwatch Next. |
required |
Source code in src/seroepi/client.py
get ¶
Sends a GET request to the Pathogenwatch API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
endpoint
|
str
|
API endpoint path. |
required |
**kwargs
|
Additional arguments passed to requests.get. |
{}
|
Returns:
| Type | Description |
|---|---|
Response
|
The HTTP response. |
Raises:
| Type | Description |
|---|---|
HTTPError
|
If the request returned an error status code. |
Source code in src/seroepi/client.py
get_collections ¶
get_collections(exclude: str = None, limit: int = None, binned: bool = None) -> Generator[PathogenwatchCollection, None, None]
Retrieves collections from Pathogenwatch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exclude
|
str
|
Collections to exclude. |
None
|
limit
|
int
|
Maximum number of collections to retrieve. |
None
|
binned
|
bool
|
Whether to include binned collections. |
None
|
Yields:
| Name | Type | Description |
|---|---|---|
PathogenwatchCollection |
PathogenwatchCollection
|
The next collection retrieved. |
Source code in src/seroepi/client.py
get_folders ¶
get_folders(exclude: str = None, limit: int = None, binned: bool = None) -> Generator[PathogenwatchFolder, None, None]
Retrieves folders from Pathogenwatch.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
exclude
|
str
|
Folders to exclude. |
None
|
limit
|
int
|
Maximum number of folders to retrieve. |
None
|
binned
|
bool
|
Whether to include binned folders. |
None
|
Yields:
| Name | Type | Description |
|---|---|---|
PathogenwatchFolder |
PathogenwatchFolder
|
The next folder retrieved. |
Source code in src/seroepi/client.py
prefetch ¶
Concurrently populates the details and genomes cache for multiple collections or folders.
Uses thread pooling to fetch in parallel while urllib3 safely handles 429 rate limit backoffs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
Iterable[PathogenwatchContainerMixin]
|
An iterable of PathogenwatchCollection or PathogenwatchFolder objects. |
required |
max_workers
|
int
|
Maximum number of concurrent threads. Defaults to 10. |
10
|
Source code in src/seroepi/client.py
request ¶
Sends an HTTP request to the Pathogenwatch API.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str
|
HTTP method (e.g., 'GET', 'POST'). |
required |
endpoint
|
str
|
API endpoint path. |
required |
**kwargs
|
Additional arguments passed to requests.request. |
{}
|
Returns:
| Type | Description |
|---|---|
Response
|
The HTTP response. |
Raises:
| Type | Description |
|---|---|
HTTPError
|
If the request returned an error status code. |
Source code in src/seroepi/client.py
PathogenwatchCollection
dataclass
¶
Bases: PathogenwatchContainerMixin
A lazy-loaded proxy object representing a single Pathogenwatch collection.
Attributes:
| Name | Type | Description |
|---|---|---|
binned |
bool
|
Whether the collection is binned. |
createdAt |
str
|
Creation timestamp. |
description |
str
|
Collection description. |
name |
str
|
Collection name. |
organismId |
str
|
ID of the organism. |
owner |
str
|
Owner of the collection. |
uuid |
str
|
Unique identifier for the collection. |
size |
int
|
Number of genomes in the collection. |
Source code in src/seroepi/client.py
PathogenwatchContainerMixin ¶
Mixin providing shared fetching logic for Pathogenwatch Collection and Folder dataclasses.
Classes using this mixin must define _ENTITY_TYPE, _DETAILS_QUERY_PARAM, _GENOMES_ID_PARAM, _GENOMES_CURSOR_PARAM, and _ATTR_PREFIX.
Source code in src/seroepi/client.py
get_details ¶
Fetches detailed information for the container.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
PathogenwatchClient
|
An instance of PathogenwatchClient. |
required |
Returns:
| Type | Description |
|---|---|
dict
|
A dictionary containing the details. |
Source code in src/seroepi/client.py
get_genomes ¶
Fetches all genomes associated with this container.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
PathogenwatchClient
|
An instance of PathogenwatchClient. |
required |
limit
|
int
|
Number of genomes to fetch per request for pagination. Defaults to 1000. |
1000
|
Returns:
| Type | Description |
|---|---|
list[dict]
|
A list of dictionaries, each representing a genome. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the internal ID for the container cannot be resolved. |
Source code in src/seroepi/client.py
PathogenwatchFolder
dataclass
¶
Bases: PathogenwatchContainerMixin
A lazy-loaded proxy object representing a single Pathogenwatch folder.
Attributes:
| Name | Type | Description |
|---|---|---|
createdAt |
str
|
Creation timestamp. |
id |
str
|
Internal folder ID. |
uuid |
str
|
Unique identifier for the folder. |
access |
str
|
Access level. |
name |
str
|
Folder name. |
binned |
bool
|
Whether the folder is binned. |