# From Genome Assemblies to Glycan Structures &amp; Vaccine Formulations

**SeroVerse** is an end-to-end, high-performance Python ecosystem uniting **bacterial polysaccharide locus genomics (`SeroGen`)**, **structural glycomics and biosynthetic pathway alignment (`KBank`)**, and **hierarchical Bayesian sero-epidemiological modelling (`SeroEpi`)**.

\>65 Mb/s Single-pass bacterial + prophage ORF calling (\~70 ms per genome)

1,530 Curated bacterial glycan graphs paired with biosynthetic gene clusters

91.4% F1 Zero-dependency 1D-CNN protein role classification across 30 roles

MCMC &amp; SVI Hierarchical Bayesian prevalence &amp; LOSO-validated vaccine design

---

## The Three Pillars

Select a pillar below to explore its documentation, interactive benchmark slide decks, API references, and live applications.

### SeroGen

Genomics

Zero-copy Structure-of-Arrays (SoA) genomic engine that decodes bacterial and prophage ORFs, classifies biosynthetic protein roles via a pure NumPy/Numba 1D-CNN, segments capsule and O-antigen loci via exact ACP-DP, and resolves serotypes with bipartite graph alignment.

Zero CLI Dependencies 99.7% 3'-Stop Recall 100% Contig-Split Stitching

[Docs &amp; Guide](<https://seroverse.github.io/SeroGen/>) [Marimo Slides](<https://seroverse.github.io/SeroGen/notebooks/>) [API](<https://seroverse.github.io/SeroGen/reference/>) [GitHub ↗](<https://github.com/SeroVerse/SeroGen>)

### KBank

Glycomics

Geno-glycomic database and polysaccharide structure predictor bridging `SeroGen` gene clusters to directed chemical polysaccharide graphs (`CSDB` / `IUPAC` / `KEGG KCF`) via bipartite enzyme-to-linkage alignment and a Relational Message-Passing Neural Network.

1,530 Locus–Glycan Pairs \>92% Monosaccharide F1 Bipartite GT-Linkage EM

[Docs &amp; Guide](<https://seroverse.github.io/KBank/>) [Benchmarks](<https://seroverse.github.io/KBank/notebooks/>) [API](<https://seroverse.github.io/KBank/reference/>) [GitHub ↗](<https://github.com/SeroVerse/KBank>)

### SeroEpi

Epidemiology

`scikit-learn` and `JAX`/`NumPyro` library for genomic sero-epidemiology. Ingests Pathogenwatch cohorts and UN/World Bank demographics, fits stratified hierarchical Bayesian prevalence models, and optimizes multi-valent vaccine and phage formulations.

NUTS MCMC &amp; SVI LOSO Formulation CV PyShiny Web Dashboard

[Docs &amp; Guide](<https://seroverse.github.io/SeroEpi/>) [Live Web App ↗](<https://tomdstanton-seroepi.share.connect.posit.cloud>) [Embedded App](<https://seroverse.github.io/SeroEpi/app/>) [GitHub ↗](<https://github.com/SeroVerse/SeroEpi>)

---

## End-to-End Architecture

**SeroVerse** connects raw sequencing reads and assemblies directly to structural glycobiology and public-health intervention design:

```
flowchart LR
    subgraph SG["<b>1. SeroGen (Genomic Engine)</b>"]
        direction TB
        FA["<b>FASTA Assembly</b><br/><i>2-Bit SoA DNA &amp; Contigs</i>"]
        ORF["<b>OrfPredictor</b><br/><i>Bacterial + Prophage Viterbi HMM</i>"]
        CNN["<b>GeneRoleClassifier</b><br/><i>Multi-Scale 1D-CNN (30 Roles)</i>"]
        SEG["<b>LocusSegmenter &amp; Matcher</b><br/><i>ACP-DP + Bipartite Synteny Graph</i>"]
        FA --> ORF --> CNN --> SEG
    end

    subgraph KB["<b>2. KBank (Structural Glycomics)</b>"]
        direction TB
        DB["<b>Curated Glycan-Locus DB</b><br/><i>1,530 CSDB / IUPAC CSR Graphs</i>"]
        ALN["<b>BiosyntheticAssigner</b><br/><i>Pan-Graph EM Enzyme-to-Linkage</i>"]
        MPNN["<b>GlycanPredictor (MPNN)</b><br/><i>Arborescence De Novo Structure</i>"]
        DB --> ALN --> MPNN
    end

    subgraph SE["<b>3. SeroEpi (Bayesian Sero-Epidemiology)</b>"]
        direction TB
        COH["<b>Surveillance Cohorts</b><br/><i>Pathogenwatch + World Bank API</i>"]
        BAY["<b>Hierarchical Estimators</b><br/><i>NumPyro NUTS MCMC &amp; SVI</i>"]
        VAC["<b>Formulation Optimizer</b><br/><i>LOSO Cross-Validated Coverage</i>"]
        COH --> BAY --> VAC
    end

    SEG ==>|"Segmented Loci &amp;<br/>Serotype Calls"| ALN
    SEG ==>|"Population Serotype<br/>Assignments"| COH
    MPNN ==>|"Antigenic Epitope &amp;<br/>Cross-Reactivity"| VAC
```

---

## Technical Highlights Across the Suite

- **Zero-Copy SoA &amp; SIMD Acceleration (`SeroGen`)**

  ---

  Contigs, intervals, k-mer randstrobes, and CSR graphs are stored in contiguous NumPy Structure-of-Arrays buffers (`serogen.core`) operated on by GIL-free Numba kernels — eliminating external binary wrappers (`prodigal`, `diamond`, `minimap2`, `blast+`).
- **Single-Pass Prophage &amp; Bacterial Gene Calling (`SeroGen`)**

  ---

  `OrfPredictor` combines a 21-state frameshift-tolerant profile-HMM with Shine-Dalgarno RBS scoring and viral gap rescue, achieving **99.7% 3'-stop recall** on bacterial chromosomes and **95.3% recall** across embedded prophages at **\>65 Mb/s**.
- **De Novo Glycan Structure Prediction (`KBank`)**

  ---

  `KBank` pairs factorized 1D-CNN glycosyltransferase/polymerase classifiers (`BiosyntheticClassifierSuite`) with a Relational MPNN and a branch-and-bound Constrained Spanning Arborescence solver (`GlycanPredictor`) to reconstruct complete repeating-unit topologies *de novo*.
- **Bipartite Gene-to-Glycan Alignment (`KBank`)**

  ---

  `BiosyntheticAssigner` maps individual glycosyltransferases, acetyltransferases, and `Wzy`/`Wzx` flippases onto specific monosaccharide linkages using pan-graph Expectation-Maximization homology priors and biological Und-PP reducing-end frame rotation.
- **Hierarchical Partial Pooling (`SeroEpi`)**

  ---

  `SeroEpi` models geographic, temporal, and clinical sampling heterogeneity using `JAX`/`NumPyro` Binomial and Beta-Binomial hierarchical estimators (`MCMC` NUTS and `SVI`), preventing small-stratum noise from distorting global antigen rankings.
- **LOSO-Validated Vaccine Formulation (`SeroEpi`)**

  ---

  The `Formulation` meta-estimator selects optimal \\(K\\)-valent capsule/O-antigen cocktails under pooled or equal-stratum weights, controls Bayesian/BH False Discovery Rates against burden thresholds, and quantifies geographic generalizability via Leave-One-Stratum-Out CV.

---

## Unified Quickstart

```python
from serogen.core.io.fasta import GenomeAssembly
from serogen.loci.matcher import LocusMatcher
from serogen.loci.models import LocusDatabase
from serogen.loci.predictor import LocusPredictor

# 1. Load a bacterial genome assembly (single or fragmented multi-contig FASTA)
assembly = GenomeAssembly.from_fasta("klebsiella_isolate.fasta")

# 2. Predict ORFs (bacterial + prophage), classify 30 CNN gene roles, and segment loci via ACP-DP
predictor = LocusPredictor()
loci = predictor.predict(assembly)

for locus in loci:
    print(f"{locus.archetype.name}: {locus.start}..{locus.end} ({len(locus.genes)} genes)")

# 3. Match segmented loci against a compiled reference database with bipartite synteny alignment
db = LocusDatabase.load("spneumo_cps.npz")
matcher = LocusMatcher.from_database(db)
best = matcher.match(loci)[0]
print(f"Serotype: {best.serotype} (score={best.score:.3f}, AA identity={best.mean_aa_identity:.1%})")
```

```python
from kbank.biosynthesis.align import BiosyntheticAssigner
from kbank.biosynthesis.predictor import GlycanPredictor
from kbank.db.records import GlycanRecords
from serogen.core.io.fasta import GenomeAssembly
from serogen.loci.predictor import LocusPredictor

# 1. Load the 1,530 curated bacterial glycan + biosynthetic gene cluster records
records = GlycanRecords.load()

# 2. Segment a capsular polysaccharide locus from raw assembly DNA via SeroGen
assembly = GenomeAssembly.from_fasta("KL106.fasta")
locus = LocusPredictor().predict(assembly)[0]

# 3. Predict the complete repeating-unit polysaccharide structure de novo via Relational MPNN
predictor = GlycanPredictor.from_records(records)
top_hit = predictor.predict(locus, top_k=1)[0]
print(f"Predicted CSDB structure: {top_hit.glycan.to_csdb().decode()} (p={top_hit.probability:.2%})")

# 4. Or align a locus directly to a known IUPAC/CSDB glycan to assign enzyme-to-linkage roles
assigner = BiosyntheticAssigner()
assignment = assigner.assign_record(top_hit.glycan, locus)
```

```python
from seroepi.aggregate import Aggregator
from seroepi.estimators.formulation import FormulationEstimator
from seroepi.estimators.hierarchical import HierarchicalSVIEstimator
from seroepi.examples import KlebnetNeonatalSepsis
from seroepi.plotting.choropleth import ChoroplethPlotter

# 1. Load the KlebNET Neonatal Sepsis surveillance cohort (981 K. pneumoniae isolates)
ds = KlebnetNeonatalSepsis.load_built()

# 2. Aggregate K-locus serotype counts stratified by country/site
agg = Aggregator(target=ds.var("K_locus"), strata=[ds.var("country")]).fit(ds)

# 3. Fit a NumPyro Hierarchical Bayesian estimator & 10-valent vaccine formulation
est = HierarchicalSVIEstimator().fit(agg)
vaccine = FormulationEstimator(max_valency=10).fit(est)
chart = ChoroplethPlotter().plot(est)
```

---

## Interactive Benchmarks &amp; Live Applications

| Pillar | Interactive Resource | Highlights |
| :--- | :--- | :--- |
| **SeroGen** | [Prophage &amp; Bacterial ORF Benchmark](<https://seroverse.github.io/SeroGen/notebooks/prophage-orfs/>) | Interactive 16:9 Marimo slide deck benchmarking `OrfPredictor` across complete *K. pneumoniae* chromosomes (**99.7% 3'-stop recall**) and prophages (**95.3% recall**). |
| **SeroGen** | [Multi-Scale 1D-CNN Role Classifier](<https://seroverse.github.io/SeroGen/notebooks/gene-classifier/>) | Optuna TPE hyperparameter tuning and confusion matrices across 30 polysaccharide biosynthesis, transport, and MGE roles (**91.4% Macro F1**). |
| **SeroGen** | [*S. pneumoniae* 98-Serotype CPS Benchmark](<https://seroverse.github.io/SeroGen/notebooks/spneumo-serotyping/>) | Whole-genome serotyping (**100% Top-1 accuracy**), contig-split boundary stitching, LOO novelty detection, and Fruchterman-Reingold synteny networks. |
| **KBank** | [CSDB Curation &amp; BGC-to-Glycan Alignment](<https://seroverse.github.io/KBank/notebooks/>) | Curation of **1,530** bacterial surface polysaccharide structures, pan-graph EM glycosyltransferase assignment, and MPNN *de novo* structure recovery (`KL106`, `KL107`). |
| **SeroEpi** | [Live PyShiny Surveillance &amp; Formulation App ↗](<https://tomdstanton-seroepi.share.connect.posit.cloud>) | Interactive cohort explorer, compositional antigen target builder, NUTS MCMC / SVI Bayesian prevalence fitting, spatial choropleths, UpSet plots, and vaccine coverage curves. |

---

## Installation

Each pillar package can be installed independently or together via [`uv`](<https://docs.astral.sh/uv/>) or `pip`:

```bash
# Core genomic ORF calling, 1D-CNN role classification, and locus segmentation
uv add serogen

# Geno-glycomic database, CSDB/IUPAC graph parsers, and MPNN glycan predictor
uv add kbank

# Bayesian sero-epidemiological estimators, plotting, and interactive PyShiny dashboard
uv add "seroepi[all]"
```
