seroepi.aggregate & estimators¶
Stratified isolate aggregation, frequentist and bootstrap confidence intervals, JAX/NumPyro hierarchical Bayesian partial-pooling models, clonal outbreak deduplication, and Leave-One-Stratum-Out (LOSO) multi-valent formulation optimization.
Stratified Count Aggregator (seroepi.aggregate)¶
aggregate
¶
Dedicated aggregation engine, parameter validation, and structured Aggregates result container.
Classes:
| Name | Description |
|---|---|
Aggregator |
Scikit-learn compatible transformer for dataset aggregation, temporal windowing, and stratification. |
Aggregator
¶
Bases: StratifiedResultMixin, BaseEstimator, TransformerMixin
Scikit-learn compatible transformer for dataset aggregation, temporal windowing, and stratification.
Transforms an isolate-level Dataset into a structured contingency table (data_) with columns
[*strata_cols, "target", "event", "n"], supporting both mutually exclusive compositional traits
(e.g. capsule K-locus serotypes) and binary/compound Target definitions, with optional cluster
deduplication (adjust_for), Cartesian zero-padding (pad_zeros), and rolling temporal windows (every).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
target
|
Target | Criterion | Variable
|
Target |
required |
strata
|
Sequence[Variable] | Variable | None
|
Optional stratification |
None
|
adjust_for
|
Variable | None
|
Optional cluster/outbreak |
None
|
negative_indicator
|
str | Pattern[str] | Sequence[str] | None
|
Optional string, regex pattern, or sequence of strings treated as missing/negative calls for compositional targets. |
None
|
pad_zeros
|
bool
|
Whether to zero-pad unobserved |
False
|
filter_qc
|
bool
|
Whether to automatically apply all |
True
|
every
|
str | None
|
Optional Polars duration string (e.g. |
None
|
period
|
str | None
|
Optional Polars window length string when using sliding temporal windows (defaults to |
None
|
offset
|
str | None
|
Optional Polars window offset string for dynamic temporal grouping. |
None
|
closed
|
Literal['left', 'right', 'none', 'both']
|
Boundary closure rule ( |
'left'
|
upsample
|
bool
|
Whether to upsample missing regular temporal intervals with zero counts. |
False
|
compositional
|
bool | None
|
Optional explicit override for whether |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
data_ |
DataFrame
|
Fitted Polars |
variables_ |
dict[str, Variable]
|
Mapping of output column names to semantic |
target_ |
Variable
|
Resolved output |
strata_ |
tuple[Variable, ...]
|
Tuple of stratification |
adjust_for_ |
Variable | None
|
Optional cluster-adjustment |
is_compositional_ |
bool
|
Whether |
is_padded_ |
bool
|
Whether unobserved cells were zero-padded or upsampled. |
Examples:
>>> from seroepi.aggregate import Aggregator
>>> from seroepi.examples import KlebnetNeonatalSepsis
>>> ds = KlebnetNeonatalSepsis.load()
>>> agg = Aggregator(
... target=ds.var("K_locus"),
... strata=ds.var("Country"),
... pad_zeros=True,
... ).fit(ds)
>>> agg.data_.columns
['Country', 'target', 'event', 'n']
Methods:
| Name | Description |
|---|---|
fit_transform |
Fits the aggregator on |
transform |
Clones and fits the aggregator on |
fit |
Executes QC filtering, target resolution, strata projection, windowing, and zero-padding on |
Source code in src/seroepi/aggregate.py
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 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 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 | |
fit_transform
¶
fit_transform(
X: Dataset, y: Any = None, **fit_params: Any
) -> Self
Fits the aggregator on X and returns the fitted Aggregator instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Dataset
|
Input isolate-level |
required |
y
|
Any
|
Ignored; present for scikit-learn pipeline compatibility. |
None
|
**fit_params
|
Any
|
Additional fit keyword parameters (unused). |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
Fitted |
Source code in src/seroepi/aggregate.py
transform
¶
transform(X: Dataset) -> Self
Clones and fits the aggregator on X without mutating self in-place.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Dataset
|
Input isolate-level |
required |
Returns:
| Type | Description |
|---|---|
Self
|
A newly fitted |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
Source code in src/seroepi/aggregate.py
fit
¶
fit(X: Dataset, y: Any = None) -> Self
Executes QC filtering, target resolution, strata projection, windowing, and zero-padding on X.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Dataset
|
Input isolate-level |
required |
y
|
Any
|
Ignored; present for scikit-learn compatibility. |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
Fitted |
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
Source code in src/seroepi/aggregate.py
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 | |
Estimator Base Contracts (seroepi.estimators.base)¶
base
¶
Universal base classes, adapters, and contracts for SeroEpi estimators.
Classes:
| Name | Description |
|---|---|
BaseEstimator |
Abstract base class for all SeroEpi prevalence estimators. |
BayesianEstimator |
Abstract base class for hierarchical Bayesian prevalence estimators. |
BaseEstimator
¶
Bases: StratifiedResultMixin, RegressorMixin, BaseEstimator, ABC
Abstract base class for all SeroEpi prevalence estimators.
Implements scikit-learn's BaseEstimator and RegressorMixin interfaces alongside
StratifiedResultMixin, providing uniform fitted tabular storage (estimates_),
posterior/bootstrap draw pooling (target_posterior_draws()), stratum pooling
(summarize_by_target(), pool_strata()), stratum tail-lumping (summarize_by_stratum(),
lump_strata()), and within-stratum cumulative coverage trajectories (cumulative_coverage()).
Attributes:
| Name | Type | Description |
|---|---|---|
is_fitted_ |
bool
|
Whether |
estimates_ |
DataFrame | None
|
Fitted Polars |
variables_ |
dict[str, Variable]
|
Mapping of output column names to semantic |
target_ |
Variable
|
Fitted target |
strata_ |
tuple[Variable, ...]
|
Tuple of stratification |
adjust_for_ |
Variable | None
|
Optional cluster-adjustment |
is_compositional_ |
bool
|
Whether target categories are mutually exclusive compositional categories. |
is_padded_ |
bool
|
Whether unobserved |
aggregator_ |
Any
|
Reference to the upstream fitted |
train_draws_ |
ndarray | None
|
Optional |
warnings_ |
tuple[str, ...]
|
Tuple of deduplicated user-facing warning strings recorded during |
model_family |
str
|
High-level estimator family label (e.g. |
engine |
str | None
|
Optional inference backend label (e.g. |
name |
str | None
|
Optional user-assigned instance display name. |
is_bayesian |
bool
|
Whether this estimator produces Bayesian credible intervals ( |
ci_prefix |
str
|
Short uncertainty interval prefix ( |
alpha |
float
|
Significance level for |
Methods:
| Name | Description |
|---|---|
describe_interval |
Descriptive string for uncertainty intervals (e.g. '95% CIs'). |
ranked_targets |
Returns target categories ranked descending by mean estimated prevalence across strata. |
target_posterior_draws |
Returns pooled posterior or bootstrap prevalence draws per target if supported by this estimator. |
summarize_by_target |
Aggregates prevalence estimates and uncertainty intervals across all strata for each target category. |
pool_strata |
Returns an unstratified clone with estimates pooled across all strata per target. |
summarize_by_stratum |
Computes total prevalence across targets within each single stratum using true stratum denominators. |
lump_strata |
Retains the top |
cumulative_coverage |
Computes cumulative target coverage and model-faithful uncertainty intervals within each stratum. |
contrast_label_with |
Infers comparative display labels contrasting |
fit |
Fits the estimator to data. |
predict |
Standard scikit-learn predict returning point estimate arrays or uncertainty intervals. |
predict_interval |
Explicit method to obtain (estimate, lower, upper) uncertainty intervals. |
fit_predict |
Fits the model and returns the fitted estimates DataFrame. |
score |
Calculates negative weighted Brier score between observed events and model predictions. |
filter |
Filters the fitted estimator's |
Source code in src/seroepi/estimators/base.py
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 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 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 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 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 | |
ci_plural
property
¶
Plural representation of the uncertainty interval (e.g. 'CIs' or 'CrIs').
ci_percentage
property
¶
Percentage integer of the uncertainty interval (e.g. 95).
display_name
property
¶
Formatted human-readable display name for the model/method.
describe_interval
¶
ranked_targets
¶
Returns target categories ranked descending by mean estimated prevalence across strata.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
top_n
|
int | None
|
Optional maximum number of top-ranked targets to return. |
None
|
Returns:
| Type | Description |
|---|---|
list[str]
|
List of target category strings ordered from highest to lowest mean prevalence. |
Source code in src/seroepi/estimators/base.py
target_posterior_draws
¶
target_posterior_draws(
targets: Sequence[str] | None = None,
*,
weighting: Literal["pooled", "equal"] = "pooled",
) -> tuple[list[str], ndarray] | None
Returns pooled posterior or bootstrap prevalence draws per target if supported by this estimator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
targets
|
Sequence[str] | None
|
Optional subset of target names to include. |
None
|
weighting
|
Literal['pooled', 'equal']
|
Stratum weighting scheme ( |
'pooled'
|
Returns:
| Type | Description |
|---|---|
tuple[list[str], ndarray] | None
|
Tuple |
tuple[list[str], ndarray] | None
|
for analytical frequentist estimators without draw simulation. |
Source code in src/seroepi/estimators/base.py
summarize_by_target
¶
summarize_by_target(
targets: Sequence[str] | None = None,
*,
weighting: Literal["pooled", "equal"] = "pooled",
) -> DataFrame
Aggregates prevalence estimates and uncertainty intervals across all strata for each target category.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
targets
|
Sequence[str] | None
|
Optional sequence of target categories to include. |
None
|
weighting
|
Literal['pooled', 'equal']
|
Stratum aggregation scheme ( |
'pooled'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Polars |
DataFrame
|
sorted descending by estimated prevalence. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/seroepi/estimators/base.py
pool_strata
¶
Returns an unstratified clone with estimates pooled across all strata per target.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
weighting
|
Literal['pooled', 'equal']
|
Stratum weighting scheme ( |
'pooled'
|
Returns:
| Type | Description |
|---|---|
Self
|
Shallow clone of |
Source code in src/seroepi/estimators/base.py
summarize_by_stratum
¶
summarize_by_stratum(
targets: Sequence[str] | None = None,
*,
x_limit: int | None = None,
other_label: str = "Other",
) -> tuple[DataFrame, list[str]]
Computes total prevalence across targets within each single stratum using true stratum denominators.
Ranks strata descending by total prevalence and optionally pools the tail strata beyond
x_limit - 1 into other_label.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
targets
|
Sequence[str] | None
|
Optional subset of target categories to sum over within each stratum. |
None
|
x_limit
|
int | None
|
Optional maximum number of strata to display (must be |
None
|
other_label
|
str
|
Label used for the pooled tail stratum when |
'Other'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Tuple |
list[str]
|
point estimates, and uncertainty intervals, and |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/seroepi/estimators/base.py
lump_strata
¶
lump_strata(
targets: Sequence[str] | None = None,
*,
x_limit: int | None = None,
ranked_strata: Sequence[str] | None = None,
other_label: str = "Other",
) -> tuple[DataFrame, list[str]]
Retains the top x_limit - 1 strata and pools remaining strata into other_label per target.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
targets
|
Sequence[str] | None
|
Optional subset of target categories to retain. |
None
|
x_limit
|
int | None
|
Optional maximum number of strata columns ( |
None
|
ranked_strata
|
Sequence[str] | None
|
Optional explicit stratum ordering overriding prevalence-based ranking. |
None
|
other_label
|
str
|
Display label for the pooled tail stratum. |
'Other'
|
Returns:
| Type | Description |
|---|---|
tuple[DataFrame, list[str]]
|
Tuple |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/seroepi/estimators/base.py
cumulative_coverage
¶
cumulative_coverage(
targets: Sequence[str] | None = None,
*,
top_n: int | None = None,
max_strata: int | None = None,
other_label: str = "Other",
) -> tuple[DataFrame, list[str]]
Computes cumulative target coverage and model-faithful uncertainty intervals within each stratum.
Completes missing (stratum, target) steps via within-stratum forward-filling so unpadded
aggregators produce continuous step-by-step trajectories, and optionally caps the number of
displayed strata to max_strata by pooling tail strata into other_label.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
targets
|
Sequence[str] | None
|
Optional explicit ordered sequence of target categories to accumulate across. |
None
|
top_n
|
int | None
|
Optional cap on the number of top-ranked targets when |
None
|
max_strata
|
int | None
|
Optional cap on the number of individual strata before pooling the tail into |
None
|
other_label
|
str
|
Display label for the pooled tail stratum. |
'Other'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Tuple |
list[str]
|
|
Source code in src/seroepi/estimators/base.py
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 | |
contrast_label_with
¶
contrast_label_with(
other: BaseEstimator,
self_label: str | None = None,
other_label: str | None = None,
) -> tuple[str, str]
Infers comparative display labels contrasting self with other.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
BaseEstimator
|
Second fitted |
required |
self_label
|
str | None
|
Optional explicit label override for |
None
|
other_label
|
str | None
|
Optional explicit label override for |
None
|
Returns:
| Type | Description |
|---|---|
str
|
Tuple |
str
|
by stratum value, cluster-adjustment state, or model display name. |
Source code in src/seroepi/estimators/base.py
fit
abstractmethod
¶
fit(
X: Aggregator, y: Any = None, sample_weight: Any = None
) -> Self
Fits the estimator to data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Aggregator
|
Input fitted Aggregator instance. |
required |
y
|
Any
|
Target values (optional if already embedded in X). |
None
|
sample_weight
|
Any
|
Optional observation weights. |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
Fitted estimator instance. |
Source code in src/seroepi/estimators/base.py
predict
abstractmethod
¶
predict(
X: Aggregator, return_interval: bool = False
) -> ndarray | tuple[ndarray, ...]
Standard scikit-learn predict returning point estimate arrays or uncertainty intervals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Aggregator
|
Fitted Aggregator instance. |
required |
return_interval
|
bool
|
If True, returns a 3-tuple (estimate, lower, upper) of 1D arrays. Otherwise, returns the 1D point estimate array. |
False
|
Returns:
| Type | Description |
|---|---|
ndarray | tuple[ndarray, ...]
|
1D NumPy array or 3-tuple of 1D NumPy arrays. |
Source code in src/seroepi/estimators/base.py
predict_interval
¶
predict_interval(
X: Aggregator, alpha: float = 0.05
) -> tuple[ndarray, ndarray, ndarray]
Explicit method to obtain (estimate, lower, upper) uncertainty intervals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Aggregator
|
Fitted Aggregator instance. |
required |
alpha
|
float
|
Significance level (default 0.05 for 95% intervals). |
0.05
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray, ndarray]
|
3-tuple of 1D NumPy arrays (estimate, lower, upper). |
Source code in src/seroepi/estimators/base.py
fit_predict
¶
fit_predict(
X: Aggregator, y: Any = None, sample_weight: Any = None
) -> DataFrame
Fits the model and returns the fitted estimates DataFrame.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Aggregator
|
Fitted Aggregator instance. |
required |
y
|
Any
|
Target values. |
None
|
sample_weight
|
Any
|
Optional observation weights. |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
Fitted estimates Polars DataFrame containing estimate, lower, and upper bounds. |
Source code in src/seroepi/estimators/base.py
score
¶
score(
X: Aggregator, y: Any = None, sample_weight: Any = None
) -> float
Calculates negative weighted Brier score between observed events and model predictions.
Higher scores indicate better calibration, with 0.0 being optimal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Aggregator
|
Fitted Aggregator instance. |
required |
y
|
Any
|
Optional ground-truth target values (prevalence proportions). |
None
|
sample_weight
|
Any
|
Optional sample weights (defaults to cohort size n). |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Negative weighted Brier score in [-1.0, 0.0]. |
Source code in src/seroepi/estimators/base.py
filter
¶
Filters the fitted estimator's estimates_ and underlying aggregator_ by predicates or kwargs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*predicates
|
Expr | bool
|
Polars boolean filter expressions ( |
()
|
**kwargs
|
Any
|
Column equality constraints ( |
{}
|
Returns:
| Type | Description |
|---|---|
Self
|
Shallow clone of |
Source code in src/seroepi/estimators/base.py
BayesianEstimator
¶
Bases: BaseEstimator, ABC
Abstract base class for hierarchical Bayesian prevalence estimators.
Configures is_bayesian = True and ci_prefix = 'CrI' so downstream tables and plotters
automatically label intervals as Bayesian credible intervals.
Attributes:
| Name | Type | Description |
|---|---|---|
model_family |
str
|
Defaults to |
engine |
str | None
|
Inference engine identifier ( |
is_bayesian |
bool
|
Always |
ci_prefix |
str
|
Defaults to |
Methods:
| Name | Description |
|---|---|
describe_interval |
Descriptive string for Bayesian credible intervals. |
Source code in src/seroepi/estimators/base.py
describe_interval
¶
Descriptive string for Bayesian credible intervals.
Confidence & Credible Interval Kernels (seroepi.estimators.intervals)¶
intervals
¶
Vectorized analytical, bootstrap, and Dirichlet Bayesian bootstrap confidence/credible interval functions.
Functions:
| Name | Description |
|---|---|
wilson_interval |
Computes vectorized Wilson score binomial confidence intervals. |
clopper_pearson_interval |
Computes vectorized exact Clopper-Pearson binomial confidence intervals via the Beta distribution. |
agresti_coull_interval |
Computes vectorized Agresti-Coull binomial confidence intervals. |
wald_interval |
Computes vectorized asymptotic Wald binomial confidence intervals. |
jeffreys_interval |
Computes vectorized Jeffreys equal-tailed credible intervals with a |
bootstrap_interval |
Computes vectorized parametric binomial simulation bootstrap confidence intervals. |
bayesian_bootstrap_row_draws |
Draws |
bayesian_bootstrap_interval |
Computes Bayesian bootstrap intervals sampled directly via |
bayesian_bootstrap_compositional_draws |
Draws joint stratum-level simplex proportions |
wilson_interval
¶
Computes vectorized Wilson score binomial confidence intervals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k
|
ndarray
|
1D NumPy array of observed event counts. |
required |
n
|
ndarray
|
1D NumPy array of total sample denominators. |
required |
alpha
|
float
|
Two-sided significance level in |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray, ndarray]
|
A 3-tuple |
Source code in src/seroepi/estimators/intervals.py
clopper_pearson_interval
¶
clopper_pearson_interval(
k: ndarray, n: ndarray, alpha: float
) -> tuple[ndarray, ndarray, ndarray]
Computes vectorized exact Clopper-Pearson binomial confidence intervals via the Beta distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k
|
ndarray
|
1D NumPy array of observed event counts. |
required |
n
|
ndarray
|
1D NumPy array of total sample denominators. |
required |
alpha
|
float
|
Two-sided significance level in |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray, ndarray]
|
A 3-tuple |
Source code in src/seroepi/estimators/intervals.py
agresti_coull_interval
¶
Computes vectorized Agresti-Coull binomial confidence intervals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k
|
ndarray
|
1D NumPy array of observed event counts. |
required |
n
|
ndarray
|
1D NumPy array of total sample denominators. |
required |
alpha
|
float
|
Two-sided significance level in |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray, ndarray]
|
A 3-tuple |
Source code in src/seroepi/estimators/intervals.py
wald_interval
¶
Computes vectorized asymptotic Wald binomial confidence intervals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k
|
ndarray
|
1D NumPy array of observed event counts. |
required |
n
|
ndarray
|
1D NumPy array of total sample denominators. |
required |
alpha
|
float
|
Two-sided significance level in |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray, ndarray]
|
A 3-tuple |
Source code in src/seroepi/estimators/intervals.py
jeffreys_interval
¶
Computes vectorized Jeffreys equal-tailed credible intervals with a Beta(0.5, 0.5) prior.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k
|
ndarray
|
1D NumPy array of observed event counts. |
required |
n
|
ndarray
|
1D NumPy array of total sample denominators. |
required |
alpha
|
float
|
Two-sided significance level in |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray, ndarray]
|
A 3-tuple |
Source code in src/seroepi/estimators/intervals.py
bootstrap_interval
¶
bootstrap_interval(
k: ndarray,
n: ndarray,
alpha: float,
n_resamples: int = 1000,
random_state: Any = None,
) -> tuple[ndarray, ndarray, ndarray]
Computes vectorized parametric binomial simulation bootstrap confidence intervals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k
|
ndarray
|
1D NumPy array of observed event counts. |
required |
n
|
ndarray
|
1D NumPy array of total sample denominators. |
required |
alpha
|
float
|
Two-sided significance level in |
required |
n_resamples
|
int
|
Number of bootstrap Monte Carlo resamples to draw per row. |
1000
|
random_state
|
Any
|
Optional integer seed or NumPy |
None
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray, ndarray]
|
A 3-tuple |
Source code in src/seroepi/estimators/intervals.py
bayesian_bootstrap_row_draws
¶
bayesian_bootstrap_row_draws(
k: ndarray,
n: ndarray,
n_resamples: int = 1000,
prior_concentration: float = 0.5,
random_state: Any = None,
) -> ndarray
Draws (n_resamples, len(k)) 2-component Beta/Dirichlet proportions via scipy.stats.dirichlet.rvs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k
|
ndarray
|
1D NumPy array of observed event counts. |
required |
n
|
ndarray
|
1D NumPy array of total sample denominators. |
required |
n_resamples
|
int
|
Number of posterior Dirichlet draws per row. |
1000
|
prior_concentration
|
float
|
Symmetric Dirichlet prior concentration added to positive and negative counts. |
0.5
|
random_state
|
Any
|
Optional integer seed or NumPy |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A 2D float64 NumPy array of shape |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/seroepi/estimators/intervals.py
bayesian_bootstrap_interval
¶
bayesian_bootstrap_interval(
k: ndarray,
n: ndarray,
alpha: float,
n_resamples: int = 1000,
prior_concentration: float = 0.5,
random_state: Any = None,
) -> tuple[ndarray, ndarray, ndarray]
Computes Bayesian bootstrap intervals sampled directly via scipy.stats.dirichlet.rvs.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
k
|
ndarray
|
1D NumPy array of observed event counts. |
required |
n
|
ndarray
|
1D NumPy array of total sample denominators. |
required |
alpha
|
float
|
Two-sided significance level in |
required |
n_resamples
|
int
|
Number of posterior Dirichlet draws per row. |
1000
|
prior_concentration
|
float
|
Symmetric Dirichlet prior concentration parameter |
0.5
|
random_state
|
Any
|
Optional integer seed or NumPy |
None
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray, ndarray]
|
A 3-tuple |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/seroepi/estimators/intervals.py
bayesian_bootstrap_compositional_draws
¶
bayesian_bootstrap_compositional_draws(
df: DataFrame,
strata_cols: tuple[str, ...],
n_resamples: int = 1000,
prior_concentration: float = 0.5,
random_state: Any = None,
) -> ndarray
Draws joint stratum-level simplex proportions (n_resamples, len(df)) via scipy.stats.dirichlet.rvs.
Within each stratum, category event counts k_s and any unobserved remainder
max(0, n_s - sum(k_s)) are jointly sampled on the probability simplex so that
cumulative target coverage and stratum pooling preserve exact compositional negative
covariance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
df
|
DataFrame
|
Aggregated Polars |
required |
strata_cols
|
tuple[str, ...]
|
Tuple of stratum column names used to partition rows into independent simplices. |
required |
n_resamples
|
int
|
Number of joint Dirichlet simplex draws to simulate per stratum. |
1000
|
prior_concentration
|
float
|
Symmetric Dirichlet prior concentration added to each category. |
0.5
|
random_state
|
Any
|
Optional integer seed or NumPy |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
A 2D float64 NumPy array of shape |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/seroepi/estimators/intervals.py
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 | |
Unpooled & Bootstrap Estimators (seroepi.estimators.unpooled)¶
unpooled
¶
Unpooled analytical and non-parametric bootstrap prevalence estimator (UnpooledEstimator).
Classes:
| Name | Description |
|---|---|
UnpooledEstimator |
Calculates unpooled prevalence proportions and analytical or bootstrap confidence intervals. |
UnpooledEstimator
¶
Bases: BaseEstimator
Calculates unpooled prevalence proportions and analytical or bootstrap confidence intervals.
Supports exact Clopper-Pearson, Wilson Score, Agresti-Coull, Wald, Jeffreys, frequentist binomial simulation bootstrap, and Dirichlet Bayesian bootstrap intervals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
Literal['wilson', 'clopper_pearson', 'agresti_coull', 'wald', 'jeffreys', 'bootstrap', 'bayesian_bootstrap']
|
Confidence/credible interval estimation method. |
'wilson'
|
alpha
|
float
|
Significance level (e.g. 0.05 for 95% intervals). |
0.05
|
n_resamples
|
int
|
Number of Monte Carlo resamples for bootstrap and Bayesian bootstrap methods. |
1000
|
prior_concentration
|
float
|
Symmetric Dirichlet prior concentration added to counts for
|
0.5
|
random_state
|
int | Generator | None
|
Optional integer seed or NumPy Generator for reproducible resampling. |
None
|
name
|
str | None
|
Optional custom display name for the estimator. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
estimates_ |
DataFrame | None
|
Fitted Polars |
train_draws_ |
ndarray | None
|
Optional |
Examples:
>>> from seroepi.aggregate import Aggregator
>>> from seroepi.estimators import UnpooledEstimator
>>> from seroepi.examples import KlebnetNeonatalSepsis
>>> ds = KlebnetNeonatalSepsis.load()
>>> agg = Aggregator(target=ds.var("K_locus"), strata=ds.var("Country")).fit(ds)
>>> est = UnpooledEstimator(method="wilson", alpha=0.05).fit(agg)
>>> est.ranked_targets(top_n=3)
['KL102', 'KL2', 'KL25']
Methods:
| Name | Description |
|---|---|
describe_interval |
Descriptive string for uncertainty intervals. |
fit |
Fits the unpooled prevalence estimator on a fitted |
predict |
Predicts point prevalence proportions or |
Source code in src/seroepi/estimators/unpooled.py
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 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 361 362 363 364 365 | |
is_bootstrapped
property
¶
Whether this estimator uses resampling bootstrap inference.
inference_type
property
¶
Inference paradigm: analytical asymptotic/exact vs non-parametric resampling.
describe_interval
¶
Descriptive string for uncertainty intervals.
Source code in src/seroepi/estimators/unpooled.py
fit
¶
fit(
X: Aggregator | Any,
y: Any = None,
sample_weight: Any = None,
) -> Self
Fits the unpooled prevalence estimator on a fitted Aggregator.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Aggregator | Any
|
Input fitted |
required |
y
|
Any
|
Ignored; present for scikit-learn pipeline compatibility. |
None
|
sample_weight
|
Any
|
Ignored; present for scikit-learn pipeline compatibility. |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
Fitted |
Source code in src/seroepi/estimators/unpooled.py
predict
¶
predict(
X: Aggregator | Any, return_interval: bool = False
) -> ndarray | tuple[ndarray, ndarray, ndarray]
Predicts point prevalence proportions or (estimate, lower, upper) intervals for X.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Aggregator | Any
|
Fitted |
required |
return_interval
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
ndarray | tuple[ndarray, ndarray, ndarray]
|
1D NumPy array of point estimates, or a 3-tuple of 1D NumPy arrays |
Source code in src/seroepi/estimators/unpooled.py
Hierarchical Bayesian MCMC & SVI Estimators (seroepi.estimators.hierarchical)¶
hierarchical
¶
Hierarchical Bayesian prevalence estimators via NumPyro NUTS MCMC and SVI.
Classes:
| Name | Description |
|---|---|
BaseHierarchicalEstimator |
Abstract base class for hierarchical Bayesian prevalence estimators. |
HierarchicalMCMCEstimator |
Hierarchical Bayesian model for prevalence estimation fitted via NumPyro NUTS MCMC. |
HierarchicalSVIEstimator |
Hierarchical Bayesian model for prevalence estimation fitted via fast Stochastic Variational Inference (SVI). |
BaseHierarchicalEstimator
¶
Bases: BayesianEstimator
Abstract base class for hierarchical Bayesian prevalence estimators.
Unifies data pre-processing, compound strata grouping, label encoding, 1D observed-cell partial pooling, posterior derivation, and scikit-learn prediction for hierarchical models.
Attributes:
| Name | Type | Description |
|---|---|---|
engine |
str | None
|
Inference engine identifier ( |
estimate_method |
str
|
Method label recorded in |
likelihood |
Literal['binomial', 'beta_binomial']
|
Observation likelihood kernel ( |
samples_ |
dict[str, ndarray] | None
|
Dictionary of posterior parameter draws extracted after fitting. |
extra_fields_ |
dict[str, ndarray] | None
|
Dictionary of sampler diagnostic fields (MCMC only). |
losses_ |
ndarray | None
|
1D NumPy array of variational ELBO losses per optimization step (SVI only). |
encoders_ |
dict[str, LabelEncoder]
|
Mapping from target/stratum column names to fitted |
cell_index_ |
dict[tuple[str, str], int]
|
Mapping from |
Methods:
| Name | Description |
|---|---|
fit |
Fits the hierarchical Bayesian estimator on a fitted |
predict |
Predicts posterior mean prevalence (and optional credible intervals) for |
Source code in src/seroepi/estimators/hierarchical.py
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 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 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 | |
fit
¶
fit(
X: Aggregator | Any,
y: Any = None,
sample_weight: Any = None,
) -> Self
Fits the hierarchical Bayesian estimator on a fitted Aggregator.
Encodes target and stratum categories, runs NumPyro MCMC or SVI inference, and derives posterior mean prevalence and equal-tailed credible intervals.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Aggregator | Any
|
Fitted |
required |
y
|
Any
|
Ignored; present for scikit-learn pipeline compatibility. |
None
|
sample_weight
|
Any
|
Ignored; present for scikit-learn pipeline compatibility. |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
The fitted hierarchical estimator instance ( |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
RuntimeError
|
If |
Source code in src/seroepi/estimators/hierarchical.py
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 | |
predict
¶
predict(
X: Aggregator | Any, return_interval: bool = False
) -> ndarray | tuple[ndarray, ndarray, ndarray]
Predicts posterior mean prevalence (and optional credible intervals) for X.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Aggregator | Any
|
Fitted |
required |
return_interval
|
bool
|
Whether to also return |
False
|
Returns:
| Type | Description |
|---|---|
ndarray | tuple[ndarray, ndarray, ndarray]
|
A 1D float64 NumPy array of posterior mean prevalence estimates, or a 3-tuple |
ndarray | tuple[ndarray, ndarray, ndarray]
|
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the estimator has not been fitted yet. |
TypeError
|
If |
Source code in src/seroepi/estimators/hierarchical.py
HierarchicalMCMCEstimator
¶
Bases: BaseHierarchicalEstimator
Hierarchical Bayesian model for prevalence estimation fitted via NumPyro NUTS MCMC.
Models target effects and random group interactions, estimating full posterior distributions and offering formal MCMC convergence diagnostics (R-hat, effective sample size).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_samples
|
int
|
Number of posterior samples to draw per chain. |
1500
|
num_chains
|
int
|
Number of parallel MCMC chains. |
4
|
num_warmup
|
int
|
Number of warmup/burn-in steps. |
1000
|
likelihood
|
Literal['binomial', 'beta_binomial']
|
Binomial or overdispersed beta_binomial likelihood kernel. |
'binomial'
|
alpha
|
float
|
Significance level for credible intervals (default 0.05 for 95% CrIs). |
0.05
|
chain_method
|
Literal['auto', 'parallel', 'vectorized', 'sequential']
|
MCMC chain execution strategy ('auto', 'parallel', 'vectorized', or 'sequential'). |
'auto'
|
target_accept_prob
|
float
|
NUTS target acceptance probability (default 0.8). |
0.8
|
max_tree_depth
|
int
|
NUTS maximum tree depth (default 10). |
10
|
init_strategy
|
Literal['median', 'uniform', 'sample'] | Callable[..., Any]
|
Parameter initialization strategy ('median', 'uniform', 'sample', or custom callable). |
'median'
|
random_state
|
int | None
|
Random seed for reproducibility. |
42
|
name
|
str | None
|
Optional custom display name for the estimator. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
samples_ |
dict[str, ndarray] | None
|
Dictionary mapping model parameter names to NumPy arrays of posterior draws. |
extra_fields_ |
dict[str, ndarray] | None
|
Dictionary of NUTS sampler diagnostic fields (e.g., |
estimates_ |
DataFrame | None
|
Polars |
Examples:
>>> import polars as pl
>>> from seroepi.dataset import Dataset
>>> from seroepi.aggregate import Aggregator
>>> from seroepi.estimators.hierarchical import HierarchicalMCMCEstimator
>>> from seroepi.variables import Identifier, Spatial, Trait
>>> ds = Dataset(
... pl.DataFrame({"id": ["s1", "s2", "s3"], "region": ["A", "A", "B"], "k": ["K1", "K2", "K1"]}),
... variables={"id": Identifier("id"), "region": Spatial("region"), "k": Trait("k", compositional=True)},
... )
>>> agg = Aggregator(target=ds.var("k"), strata=[ds.var("region")], pad_zeros=True).fit(ds)
>>> est = HierarchicalMCMCEstimator(num_warmup=50, num_samples=50, num_chains=1).fit(agg)
>>> est.is_fitted_
True
Methods:
| Name | Description |
|---|---|
diagnostics |
Returns MCMC convergence diagnostics (R-hat, ESS, mean, std) as a Polars |
Source code in src/seroepi/estimators/hierarchical.py
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 | |
diagnostics
¶
Returns MCMC convergence diagnostics (R-hat, ESS, mean, std) as a Polars DataFrame.
Returns:
| Type | Description |
|---|---|
DataFrame
|
A Polars |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the estimator has not been fitted or no posterior samples are available. |
Source code in src/seroepi/estimators/hierarchical.py
HierarchicalSVIEstimator
¶
Bases: BaseHierarchicalEstimator
Hierarchical Bayesian model for prevalence estimation fitted via fast Stochastic Variational Inference (SVI).
Uses an automatic variational guide (AutoNormal) and Adam optimization to achieve fast approximate
posterior draws on large datasets without full MCMC simulation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
num_steps
|
int
|
Number of optimization steps for variational ELBO. |
3000
|
learning_rate
|
float
|
Step size for Adam optimizer. |
0.01
|
num_samples
|
int
|
Number of posterior predictive draws from the fitted guide. |
1500
|
likelihood
|
Literal['binomial', 'beta_binomial']
|
Binomial or overdispersed beta_binomial likelihood kernel. |
'binomial'
|
alpha
|
float
|
Significance level for credible intervals (default 0.05 for 95% CrIs). |
0.05
|
random_state
|
int | None
|
Random seed for reproducibility. |
42
|
name
|
str | None
|
Optional custom display name for the estimator. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
losses_ |
ndarray | None
|
1D NumPy array of variational ELBO loss values recorded at each optimization step. |
samples_ |
dict[str, ndarray] | None
|
Dictionary mapping model parameter names to NumPy arrays of variational posterior draws. |
estimates_ |
DataFrame | None
|
Polars |
Examples:
>>> import polars as pl
>>> from seroepi.dataset import Dataset
>>> from seroepi.aggregate import Aggregator
>>> from seroepi.estimators.hierarchical import HierarchicalSVIEstimator
>>> from seroepi.variables import Identifier, Spatial, Trait
>>> ds = Dataset(
... pl.DataFrame({"id": ["s1", "s2", "s3"], "region": ["A", "A", "B"], "k": ["K1", "K2", "K1"]}),
... variables={"id": Identifier("id"), "region": Spatial("region"), "k": Trait("k", compositional=True)},
... )
>>> agg = Aggregator(target=ds.var("k"), strata=[ds.var("region")], pad_zeros=True).fit(ds)
>>> est = HierarchicalSVIEstimator(num_steps=200, num_samples=100).fit(agg)
>>> est.diagnostics().columns
['step', 'elbo_loss']
Methods:
| Name | Description |
|---|---|
diagnostics |
Returns SVI optimization ELBO loss history as a formatted Polars |
Source code in src/seroepi/estimators/hierarchical.py
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 | |
diagnostics
¶
Returns SVI optimization ELBO loss history as a formatted Polars DataFrame.
Returns:
| Type | Description |
|---|---|
DataFrame
|
A Polars |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the estimator has not been fitted or no loss history is available. |
Source code in src/seroepi/estimators/hierarchical.py
Multi-Valent Formulation & Differential Contrasts (seroepi.estimators.formulation)¶
formulation
¶
Scikit-learn meta-estimators for vaccine/cocktail formulation design, LOO stability, and model comparison.
Classes:
| Name | Description |
|---|---|
Formulation |
Scikit-learn meta-estimator for target formulation design and Leave-One-Stratum-Out stability. |
FormulationComparison |
Meta-estimator comparing target rankings, rank shifts, concordance, and differential prevalence across models or cohorts. |
Formulation
¶
Bases: BaseEstimator, RegressorMixin, MetaEstimatorMixin
Scikit-learn meta-estimator for target formulation design and Leave-One-Stratum-Out stability.
Wraps a single prevalence estimator to:
1. Rank target categories globally (1..K) using pooled or equal-stratum weighting.
2. Evaluate burden threshold exceedance (\(H_{0,j}: p_j \le \tau_{\min}\)) with Bayesian or BH FDR control.
3. Select the top-valency target formulation and export it as a binary Target.
4. Quantify sampling/geographic sensitivity via Leave-One-Stratum-Out (LOSO) or group cross-validation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
BaseEstimator
|
Base prevalence estimator instance to wrap. |
required |
valency
|
int
|
Number of top-ranked target categories to include in the formulation. |
6
|
weighting
|
Literal['pooled', 'equal']
|
Stratum aggregation scheme ('pooled' for sample-size weighted or 'equal' for macro-averaged). |
'pooled'
|
targets
|
Sequence[str] | None
|
Optional explicit sequence of target names overriding top-valency selection. |
None
|
cv
|
Literal['loso'] | bool | BaseCrossValidator | None
|
Cross-validation strategy ('loso', False/None to disable, or a scikit-learn BaseCrossValidator). |
'loso'
|
min_prevalence
|
float
|
Minimum prevalence threshold for burden exceedance hypothesis testing. |
0.0
|
alpha
|
float
|
Significance level for credible/confidence intervals and FDR control. |
0.05
|
name
|
str | None
|
Optional custom display name for the formulation. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
is_fitted_ |
bool
|
Boolean flag indicating whether |
aggregator_ |
Aggregator
|
Fitted |
estimator_ |
BaseEstimator
|
Fitted |
rankings_ |
DataFrame
|
Polars |
selected_targets_ |
list[str]
|
List of selected target category names in the formulation. |
cv_rankings_ |
DataFrame
|
Polars |
stability_metrics_ |
DataFrame
|
Polars |
fold_summary_ |
DataFrame
|
Polars |
warnings_ |
tuple[str, ...]
|
Tuple of warning messages captured from the underlying estimator. |
Examples:
>>> import polars as pl
>>> from seroepi.dataset import Dataset
>>> from seroepi.aggregate import Aggregator
>>> from seroepi.estimators.unpooled import UnpooledEstimator
>>> from seroepi.estimators.formulation import Formulation
>>> from seroepi.variables import Identifier, Spatial, Trait
>>> ds = Dataset(
... pl.DataFrame({"id": ["s1", "s2", "s3", "s4"], "site": ["A", "A", "B", "B"], "k": ["K1", "K2", "K1", "K3"]}),
... variables={"id": Identifier("id"), "site": Spatial("site"), "k": Trait("k", compositional=True)},
... )
>>> agg = Aggregator(target=ds.var("k"), strata=[ds.var("site")]).fit(ds)
>>> form = Formulation(UnpooledEstimator(method="wilson"), valency=2, cv="loso").fit(agg)
>>> form.selected_targets_
['K1', 'K2']
Methods:
| Name | Description |
|---|---|
check_is_fitted |
Validates that the formulation has been fitted. |
save |
Serializes the fitted |
load |
Loads a fitted |
fit |
Fits the underlying estimator on |
score_by_stratum |
Computes observed and predicted formulation coverage per stratum. |
stratum_trajectories |
Computes step-by-step cumulative coverage trajectories across formulation-ranked targets per stratum. |
predict |
Predicts formulation coverage fraction for each stratum in |
score |
Computes negative sample-size-weighted Brier score of formulation coverage across strata in |
to_target |
Exports the formulated top-valency targets into a binary SeroEpi |
compare |
Fits and returns a |
Source code in src/seroepi/estimators/formulation.py
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 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 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 734 735 736 737 738 739 740 741 742 743 744 745 | |
display_name
property
¶
Returns a human-readable label for this formulation configuration.
Returns:
| Type | Description |
|---|---|
str
|
Custom |
summary_label
property
¶
Returns a concise target and valency summary for UI registries.
Returns:
| Type | Description |
|---|---|
str
|
Formatted summary string describing the target title, valency, and weighting. |
check_is_fitted
¶
Validates that the formulation has been fitted.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
Source code in src/seroepi/estimators/formulation.py
save
¶
Serializes the fitted Formulation into a compressed Joblib file or in-memory bytes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
|
str | Path | None
|
Optional file path to write the Joblib archive to. If |
None
|
compress
|
int
|
Joblib compression level from |
3
|
Returns:
| Type | Description |
|---|---|
bytes | Path
|
The destination |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the formulation has not been fitted yet. |
Source code in src/seroepi/estimators/formulation.py
load
classmethod
¶
Loads a fitted Formulation from a Joblib file, path, or bytes buffer.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
|
str | Path | bytes | BytesIO
|
File path, |
required |
Returns:
| Type | Description |
|---|---|
Self
|
The deserialized |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If a path is given and does not exist. |
TypeError
|
If |
Source code in src/seroepi/estimators/formulation.py
fit
¶
fit(
X: Aggregator | None = None,
y: Any = None,
sample_weight: Any = None,
) -> Self
Fits the underlying estimator on X (or reuses a pre-fitted estimator), ranks targets, and runs LOSO CV.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Aggregator | None
|
Optional fitted |
None
|
y
|
Any
|
Ignored; present for scikit-learn compatibility. |
None
|
sample_weight
|
Any
|
Optional sample weights forwarded to |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
The fitted |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If |
Source code in src/seroepi/estimators/formulation.py
score_by_stratum
¶
score_by_stratum(X: Aggregator | None = None) -> DataFrame
Computes observed and predicted formulation coverage per stratum.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Aggregator | None
|
Optional fitted |
None
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A Polars |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the formulation has not been fitted yet. |
TypeError
|
If |
Source code in src/seroepi/estimators/formulation.py
stratum_trajectories
¶
stratum_trajectories(
*,
top_n: int | None = None,
max_strata: int | None = 8,
other_label: str = "Other",
) -> tuple[DataFrame, list[str]]
Computes step-by-step cumulative coverage trajectories across formulation-ranked targets per stratum.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
top_n
|
int | None
|
Optional maximum number of top-ranked targets to include along the trajectory. |
None
|
max_strata
|
int | None
|
Optional maximum number of strata before lumping remaining strata into |
8
|
other_label
|
str
|
Display label for lumped tail strata. |
'Other'
|
Returns:
| Type | Description |
|---|---|
DataFrame
|
A 2-tuple |
list[str]
|
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the formulation has not been fitted yet. |
Source code in src/seroepi/estimators/formulation.py
predict
¶
predict(X: Aggregator) -> ndarray
Predicts formulation coverage fraction for each stratum in X.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Aggregator
|
Fitted |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
A 1D float64 NumPy array of predicted coverage proportions in |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the formulation has not been fitted yet. |
Source code in src/seroepi/estimators/formulation.py
score
¶
score(
X: Aggregator, y: Any = None, sample_weight: Any = None
) -> float
Computes negative sample-size-weighted Brier score of formulation coverage across strata in X.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Aggregator
|
Fitted |
required |
y
|
Any
|
Optional ground-truth coverage array overriding |
None
|
sample_weight
|
Any
|
Optional stratum weights overriding stratum sample sizes |
None
|
Returns:
| Type | Description |
|---|---|
float
|
Negative weighted mean squared error between observed and predicted stratum coverage. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the formulation has not been fitted yet. |
Source code in src/seroepi/estimators/formulation.py
to_target
¶
to_target(
name: str | None = None, title: str | None = None
) -> Target
Exports the formulated top-valency targets into a binary SeroEpi Target.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | None
|
Optional machine identifier for the exported |
None
|
title
|
str | None
|
Optional human-readable display title for the exported |
None
|
Returns:
| Type | Description |
|---|---|
Target
|
A binary (non-compositional) |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the formulation has not been fitted yet. |
Source code in src/seroepi/estimators/formulation.py
compare
¶
compare(
other: Formulation | BaseEstimator,
name: str | None = None,
*,
alpha: float | None = None,
null_margin: float = 0.0,
) -> FormulationComparison
Fits and returns a FormulationComparison contrasting this formulation with another.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
other
|
Formulation | BaseEstimator
|
Another |
required |
name
|
str | None
|
Optional display label for |
None
|
alpha
|
float | None
|
Optional significance level override for differential prevalence FDR control. |
None
|
null_margin
|
float
|
Minimum absolute prevalence difference margin |
0.0
|
Returns:
| Type | Description |
|---|---|
FormulationComparison
|
A fitted |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If this formulation has not been fitted yet. |
Source code in src/seroepi/estimators/formulation.py
FormulationComparison
¶
Bases: BaseEstimator, MetaEstimatorMixin
Meta-estimator comparing target rankings, rank shifts, concordance, and differential prevalence across models or cohorts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
formulations
|
Mapping[str, Formulation | BaseEstimator]
|
Mapping from model/cohort labels to |
required |
valency
|
int
|
Default target valency applied when wrapping raw |
6
|
weighting
|
Literal['pooled', 'equal']
|
Default stratum weighting ('pooled' or 'equal') applied when wrapping raw |
'pooled'
|
cv
|
Literal['loso'] | bool | BaseCrossValidator | None
|
Optional cross-validation strategy applied when fitting raw |
None
|
alpha
|
float
|
Significance level for differential prevalence intervals and FDR control. |
0.05
|
null_margin
|
float
|
Minimum absolute prevalence difference margin |
0.0
|
Attributes:
| Name | Type | Description |
|---|---|---|
is_fitted_ |
bool
|
Boolean flag indicating whether |
aggregator_ |
Aggregator
|
Primary |
formulations_ |
dict[str, Formulation]
|
Dictionary mapping each label to its fitted |
rankings_ |
DataFrame
|
Stacked Polars |
rank_shifts_ |
DataFrame
|
Wide Polars |
concordance_ |
DataFrame
|
Polars |
differential_prevalence_ |
DataFrame
|
Polars |
Examples:
>>> import polars as pl
>>> from seroepi.dataset import Dataset
>>> from seroepi.aggregate import Aggregator
>>> from seroepi.estimators.unpooled import UnpooledEstimator
>>> from seroepi.estimators.formulation import FormulationComparison
>>> from seroepi.variables import Identifier, Spatial, Trait
>>> ds = Dataset(
... pl.DataFrame({"id": ["s1", "s2", "s3", "s4"], "site": ["A", "A", "B", "B"], "k": ["K1", "K2", "K1", "K3"]}),
... variables={"id": Identifier("id"), "site": Spatial("site"), "k": Trait("k", compositional=True)},
... )
>>> agg = Aggregator(target=ds.var("k"), strata=[ds.var("site")]).fit(ds)
>>> comp = FormulationComparison.from_strata(UnpooledEstimator(method="wilson"), agg, valency=2)
>>> comp.is_fitted_
True
Methods:
| Name | Description |
|---|---|
check_is_fitted |
Validates that the formulation comparison has been fitted. |
from_strata |
Slices a stratified |
fit |
Fits constituent formulations (or preserves pre-fitted cohort formulations) and computes comparisons. |
contrast |
Computes per-target differential prevalence, fold change, rank shifts, and FDR between two formulations. |
Source code in src/seroepi/estimators/formulation.py
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 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 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 | |
check_is_fitted
¶
Validates that the formulation comparison has been fitted.
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If |
Source code in src/seroepi/estimators/formulation.py
from_strata
classmethod
¶
from_strata(
estimator: BaseEstimator,
X: Aggregator,
strata_values: Sequence[str] | None = None,
*,
stratum_col: str | None = None,
valency: int = 6,
weighting: Literal["pooled", "equal"] = "pooled",
alpha: float = 0.05,
null_margin: float = 0.0,
) -> Self
Slices a stratified Aggregator across strata into cohort Formulation objects and fits a comparison.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
estimator
|
BaseEstimator
|
Unfitted or fitted |
required |
X
|
Aggregator
|
Stratified fitted |
required |
strata_values
|
Sequence[str] | None
|
Optional subset of stratum values to compare (requires at least 2). |
None
|
stratum_col
|
str | None
|
Optional stratum column name when |
None
|
valency
|
int
|
Target formulation valency for each cohort. |
6
|
weighting
|
Literal['pooled', 'equal']
|
Stratum weighting scheme ( |
'pooled'
|
alpha
|
float
|
Significance level for differential prevalence intervals and FDR control. |
0.05
|
null_margin
|
float
|
Minimum absolute prevalence difference margin |
0.0
|
Returns:
| Type | Description |
|---|---|
Self
|
A fitted |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/seroepi/estimators/formulation.py
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 | |
fit
¶
fit(X: Aggregator | None = None, y: Any = None) -> Self
Fits constituent formulations (or preserves pre-fitted cohort formulations) and computes comparisons.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Aggregator | None
|
Optional fitted |
None
|
y
|
Any
|
Ignored; present for scikit-learn compatibility. |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
The fitted |
Raises:
| Type | Description |
|---|---|
ValueError
|
If any constituent formulation/estimator is unfitted and |
TypeError
|
If any constituent entry is not a |
Source code in src/seroepi/estimators/formulation.py
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 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 | |
contrast
¶
Computes per-target differential prevalence, fold change, rank shifts, and FDR between two formulations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label_a
|
str
|
Key of the baseline formulation in |
required |
label_b
|
str
|
Key of the comparison formulation in |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
A Polars |
DataFrame
|
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the comparison has not been fitted yet. |
KeyError
|
If either |
Source code in src/seroepi/estimators/formulation.py
Spatiotemporal & Genomic Transmission Clustering (seroepi.estimators.transmission)¶
transmission
¶
Scikit-learn compatible estimator for estimating pathogen transmission between isolates.
Classes:
| Name | Description |
|---|---|
TransmissionEstimator |
Scikit-learn compatible neighbor & cluster estimator for pathogen transmission on a |
Functions:
| Name | Description |
|---|---|
parse_temporal_cutoff_days |
Converts a temporal cutoff specification into a non-negative float number of days. |
haversine_distance_km |
Computes vectorized great-circle Haversine distance in kilometers between coordinate arrays. |
TransmissionEstimator
¶
Bases: StratifiedResultMixin, NearestNeighbors
Scikit-learn compatible neighbor & cluster estimator for pathogen transmission on a Dataset.
Combines pairwise genomic distances (Dataset.distances) with clonal/lineage stratification
(strata) and epidemiological Spatial and Temporal variables to infer transmission links,
connected transmission clusters (labels_), isolate-level summaries (isolates_), pairwise
transmission edge lists (pairs_), and stratum-level transmission tables (data_).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n_neighbors
|
int
|
Number of nearest transmission neighbors to retrieve in |
5
|
radius
|
float
|
Maximum genomic distance (e.g. SNPs or cgMLST alleles) for a transmission link. |
20.0
|
strata
|
Sequence[Variable] | Variable | None
|
Clonal, spatial, temporal, or metadata |
None
|
spatial
|
Sequence[Spatial] | Spatial | None
|
Explicit |
None
|
temporal
|
Temporal | None
|
Explicit |
None
|
spatial_resolution
|
Resolution | str | None
|
Optional |
None
|
temporal_resolution
|
Resolution | str | None
|
Optional |
None
|
spatial_cutoff
|
float | None
|
Optional maximum geographic Haversine distance in kilometers (km) between
isolates when |
None
|
temporal_cutoff
|
str | float | timedelta | None
|
Optional maximum time elapsed between linked isolates (e.g. |
None
|
directed
|
bool
|
If True, requires |
False
|
target
|
Target | Criterion | Variable | None
|
Optional |
None
|
filter_qc
|
bool
|
If True (default), filters the input |
True
|
pad_zeros
|
bool
|
If True, zero-pads unobserved strata combinations in |
False
|
include_singletons
|
bool
|
If False (default), unlinked singleton isolates receive |
False
|
cluster_prefix
|
str
|
String prefix for formatted cluster identifiers (default |
'TC_'
|
algorithm
|
Literal['auto', 'ball_tree', 'kd_tree', 'brute']
|
NearestNeighbors algorithm when fitted on raw feature matrices. |
'auto'
|
leaf_size
|
int
|
Leaf size passed to BallTree or KDTree for raw matrix inputs. |
30
|
metric
|
str | Callable[..., Any]
|
Distance metric for raw matrix inputs (defaults to |
'precomputed'
|
p
|
float
|
Power parameter for Minkowski metric on raw matrix inputs. |
2
|
metric_params
|
dict[str, Any] | None
|
Additional keyword arguments for metric function on raw matrix inputs. |
None
|
n_jobs
|
int | None
|
Number of parallel jobs for neighbor search on raw matrix inputs. |
None
|
Attributes:
| Name | Type | Description |
|---|---|---|
is_fitted_ |
bool
|
Boolean flag indicating whether |
data_ |
DataFrame
|
Stratified summary Polars |
pairs_ |
DataFrame
|
Polars |
isolates_ |
DataFrame
|
Polars |
labels_ |
ndarray
|
1D int64 NumPy array of cluster IDs for each isolate ( |
sample_ids_ |
ndarray
|
1D string NumPy array of fitted isolate identifiers. |
Examples:
>>> import polars as pl
>>> from scipy.sparse import csr_matrix
>>> from seroepi.dataset import Dataset
>>> from seroepi.dist import GenomicDistances
>>> from seroepi.estimators.transmission import TransmissionEstimator
>>> from seroepi.variables import Identifier, Spatial
>>> dist = GenomicDistances(csr_matrix([[0.0, 2.0, 50.0], [2.0, 0.0, 50.0], [50.0, 50.0, 0.0]]), ("s1", "s2", "s3"))
>>> ds = Dataset(
... pl.DataFrame({"id": ["s1", "s2", "s3"], "site": ["W1", "W1", "W1"]}),
... variables={"id": Identifier("id"), "site": Spatial("site")},
... distances=dist,
... )
>>> te = TransmissionEstimator(radius=10.0, strata=[ds.var("site")]).fit(ds)
>>> te.labels_.tolist()
[0, 0, -1]
Methods:
| Name | Description |
|---|---|
fit |
Fits the transmission model on a |
radius_neighbors |
Finds all transmission neighbors within a given genomic |
radius_neighbors_graph |
Computes the (weighted) sparse graph of isolate transmission neighbors within |
kneighbors |
Finds the K-nearest transmission neighbors for each isolate. |
kneighbors_graph |
Computes the (weighted) sparse graph of K-nearest transmission neighbors. |
fit_predict |
Fits the transmission model on |
to_dataset |
Returns a new |
Source code in src/seroepi/estimators/transmission.py
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 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 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 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 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 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 | |
fit
¶
fit(X: Dataset | Any, y: Any = None) -> Self
Fits the transmission model on a Dataset (or precomputed/feature matrix X).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Dataset | Any
|
A |
required |
y
|
Any
|
Ignored; present for scikit-learn compatibility. |
None
|
Returns:
| Type | Description |
|---|---|
Self
|
The fitted |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/seroepi/estimators/transmission.py
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 | |
radius_neighbors
¶
radius_neighbors(
X: Dataset | Any = None,
radius: float | None = None,
return_distance: bool = True,
sort_results: bool = False,
) -> tuple[ndarray, ndarray] | ndarray
Finds all transmission neighbors within a given genomic radius for each isolate.
Respects all configured strata, Spatial, and Temporal cutoffs/resolutions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Dataset | Any
|
Optional query |
None
|
radius
|
float | None
|
Optional genomic distance threshold override. Defaults to |
None
|
return_distance
|
bool
|
Whether to return both |
True
|
sort_results
|
bool
|
Whether to sort each isolate's neighbors in ascending distance order. |
False
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray] | ndarray
|
A 2-tuple |
tuple[ndarray, ndarray] | ndarray
|
or |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the estimator has not been fitted yet. |
Source code in src/seroepi/estimators/transmission.py
1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 | |
radius_neighbors_graph
¶
radius_neighbors_graph(
X: Dataset | Any = None,
radius: float | None = None,
mode: Literal[
"connectivity", "distance"
] = "connectivity",
sort_results: bool = False,
) -> csr_matrix
Computes the (weighted) sparse graph of isolate transmission neighbors within radius.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Dataset | Any
|
Optional query |
None
|
radius
|
float | None
|
Optional genomic distance threshold override. Defaults to |
None
|
mode
|
Literal['connectivity', 'distance']
|
Edge weight mode ( |
'connectivity'
|
sort_results
|
bool
|
Whether to sort column indices by distance within each CSR row. |
False
|
Returns:
| Type | Description |
|---|---|
csr_matrix
|
A square SciPy |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the estimator has not been fitted yet. |
ValueError
|
If |
Source code in src/seroepi/estimators/transmission.py
kneighbors
¶
kneighbors(
X: Dataset | Any = None,
n_neighbors: int | None = None,
return_distance: bool = True,
) -> tuple[ndarray, ndarray] | ndarray
Finds the K-nearest transmission neighbors for each isolate.
Isolates with fewer than n_neighbors valid transmission candidates within self.radius
have remaining slots padded with -1 in indices and np.nan in distances.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Dataset | Any
|
Optional query |
None
|
n_neighbors
|
int | None
|
Optional number of neighbors |
None
|
return_distance
|
bool
|
Whether to return |
True
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray] | ndarray
|
A 2-tuple |
tuple[ndarray, ndarray] | ndarray
|
or |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the estimator has not been fitted yet. |
ValueError
|
If |
Source code in src/seroepi/estimators/transmission.py
kneighbors_graph
¶
kneighbors_graph(
X: Dataset | Any = None,
n_neighbors: int | None = None,
mode: Literal[
"connectivity", "distance"
] = "connectivity",
) -> csr_matrix
Computes the (weighted) sparse graph of K-nearest transmission neighbors.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Dataset | Any
|
Optional query |
None
|
n_neighbors
|
int | None
|
Optional number of neighbors |
None
|
mode
|
Literal['connectivity', 'distance']
|
Edge weight mode ( |
'connectivity'
|
Returns:
| Type | Description |
|---|---|
csr_matrix
|
A square SciPy |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the estimator has not been fitted yet. |
ValueError
|
If |
Source code in src/seroepi/estimators/transmission.py
fit_predict
¶
fit_predict(X: Dataset | Any, y: Any = None) -> ndarray
Fits the transmission model on X and returns integer cluster labels_.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
X
|
Dataset | Any
|
A |
required |
y
|
Any
|
Ignored; present for scikit-learn compatibility. |
None
|
Returns:
| Type | Description |
|---|---|
ndarray
|
1D int64 NumPy array of cluster labels for each isolate. |
Source code in src/seroepi/estimators/transmission.py
to_dataset
¶
Returns a new Dataset with the fitted transmission cluster labels joined as a TRANSMISSION_CLONE column.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset
|
Dataset
|
Target |
required |
name
|
str
|
Column name for the new |
'transmission_cluster'
|
Returns:
| Type | Description |
|---|---|
Dataset
|
A new |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the estimator has not been fitted yet. |
Source code in src/seroepi/estimators/transmission.py
parse_temporal_cutoff_days
¶
Converts a temporal cutoff specification into a non-negative float number of days.
Supports numeric days (int / float), datetime.timedelta, and Polars-style
duration strings such as '14d', '4w', '3mo', '1q', '1y', or '48h'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cutoff
|
str | float | timedelta
|
Temporal cutoff as numeric days, |
required |
Returns:
| Type | Description |
|---|---|
float
|
Equivalent non-negative duration in days as a float. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
TypeError
|
If |
Source code in src/seroepi/estimators/transmission.py
haversine_distance_km
¶
Computes vectorized great-circle Haversine distance in kilometers between coordinate arrays.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lat1
|
ndarray
|
Array of source latitudes in decimal degrees. |
required |
lon1
|
ndarray
|
Array of source longitudes in decimal degrees. |
required |
lat2
|
ndarray
|
Array of target latitudes in decimal degrees. |
required |
lon2
|
ndarray
|
Array of target longitudes in decimal degrees. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
NumPy array of great-circle distances in kilometers (km). |