# `serogen.loci`

Biosynthetic locus archetypes, exact All-Contiguous-Partitions Dynamic Programming (ACP-DP) locus segmentation, cross-contig boundary stitching, and bipartite reference serotype matching.

---

## High-Level Locus Prediction (`serogen.loci.predictor`)

## predictor

End-to-end biosynthetic locus prediction pipeline (`LocusPredictor` / `LocusFinder`).

Classes:

| Name | Description |
| --- | --- |
| `LocusPredictor` | High-level biosynthetic gene cluster (BGC) discovery and segmentation pipeline. |

### LocusPredictor

High-level biosynthetic gene cluster (BGC) discovery and segmentation pipeline.

Orchestrates: 1. Open Reading Frame (ORF) prediction via `OrfPredictor`, 2. Protein sequence functional role classification via `GeneRoleClassifier`, and 3. Archetype-constrained chromosomal segmentation via `LocusSegmenter`.

Methods:

| Name | Description |
| --- | --- |
| `predict_role_probabilities` | Predict full `(N, 30)` `GeneRole` probability distributions (including `UNKNOWN`) for `genes`. |
| `predict` | Discover, classify, and segment biosynthetic `Loci` from genomic sequences or `Genes`. |

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `archetype_classifier` | `ArchetypeClassifier` | Return the underlying `ArchetypeClassifier` used by `self.segmenter`. |

#### archetype\_classifier

```python
archetype_classifier: ArchetypeClassifier
```

Return the underlying `ArchetypeClassifier` used by `self.segmenter`.

#### predict\_role\_probabilities

```python
predict_role_probabilities(genes: Genes) -> ndarray[tuple[int, int], dtype[float64]]
```

Predict full `(N, 30)` `GeneRole` probability distributions (including `UNKNOWN`) for `genes`.

#### predict

```python
predict(target: bytes | str | Sequence | Sequences | GenomeAssembly | Genes, *, categories: ArchetypeCategory | str | Iterable[ArchetypeCategory | str] | None = None, archetypes: LocusArchetype | str | int | Iterable[LocusArchetype | str | int] | None = None, min_completeness: float = 0.0, min_score: float = 0.0, max_frameshift_fraction: float = 1.0, only_intact: bool = False, heal_mobile_elements: bool = False) -> Loci
```

Discover, classify, and segment biosynthetic `Loci` from genomic sequences or `Genes`.

---

## ACP-DP Locus Segmentation (`serogen.loci.segmenter`)

## segmenter

Archetype-Constrained Exact Partitioning Dynamic Programming (ACP-DP) locus segmenter.

Classes:

| Name | Description |
| --- | --- |
| `LocusSegmenter` | Archetype-Constrained Exact Partitioning Dynamic Programming (ACP-DP) locus segmenter. |

### LocusSegmenter

Archetype-Constrained Exact Partitioning Dynamic Programming (ACP-DP) locus segmenter.

Segments chromosomal `Genes` and their `GeneRole` probability distributions (or discrete role labels) into non-overlapping `Loci`, disambiguating tandem loci (e.g., adjacent K-locus and O-locus in *Klebsiella* / *E. coli*), bridging internal unannotated (`UNKNOWN`) and mobile element (`TRANSPOSASE`/`INTEGRASE`) gaps, and stitching loci split across contig boundaries in fragmented assemblies.

Methods:

| Name | Description |
| --- | --- |
| `segment` | Segment a `Genes` container and role predictions into `Loci`. |

#### segment

```python
segment(genes: Genes, role_probs: ndarray | Sequence[int | GeneRole], *, clusters: Sequence[int] | ndarray | None = None) -> Loci
```

Segment a `Genes` container and role predictions into `Loci`.

---

## Locus &amp; Graph Models (`serogen.loci.models`)

## models

Data models for biosynthetic gene clusters (`Locus`, `Loci`) and syntenic graph primitives.

Classes:

| Name | Description |
| --- | --- |
| `IntergenicOrientation` | Relative transcriptional orientation between two adjacent genes in a locus. |
| `IntergenicType` | 32-bit integer encoding for an intergenic synteny transition between adjacent genes. |
| `IntergenicEdge` | Directed synteny edge connecting adjacent gene nodes `(source -> target)` in a `Locus`. |
| `GeneNode` | 32-bit integer encoding for a gene node inside a biosynthetic locus graph. |
| `Locus` | Scalar view and directed syntenic graph of a single biosynthetic gene cluster. |
| `Loci` | Structure-of-Arrays (SoA) batch container for biosynthetic gene clusters (`Locus`). |

### IntergenicOrientation

Bases: `IntEnum`

Relative transcriptional orientation between two adjacent genes in a locus.

### IntergenicType

Bases: `IntNode`

32-bit integer encoding for an intergenic synteny transition between adjacent genes.

Bit 0..1 (2 bits): Relative transcriptional orientation (`IntergenicOrientation`, 0..2). Bit 2..5 (4 bits): Discretized intergenic distance bin (0 = overlap, 1 = \<50bp, 2 = 50..200bp, 3 = \>200bp, 15 = healed MGE scar). Bit 31 (1 bit): `TAG_EDGE` (`1` = intermediate edge node in bipartite graphs).

Methods:

| Name | Description |
| --- | --- |
| `from_adjacent` | Construct an `IntergenicType` from adjacent gene strands and base-pair distance. |

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `orientation` | `IntergenicOrientation` | Relative transcriptional orientation between source and target genes. |
| `gap_bin` | `int` | Discretized intergenic distance bin (`0..15`). |
| `is_contig_break` | `bool` | True if this edge bridges a contig boundary in a fragmented assembly. |
| `is_healed_scar` | `bool` | True if this edge bridges a healed mobile genetic element (MGE) insertion. |

#### orientation

```python
orientation: IntergenicOrientation
```

Relative transcriptional orientation between source and target genes.

#### gap\_bin

```python
gap_bin: int
```

Discretized intergenic distance bin (`0..15`).

#### is\_contig\_break

```python
is_contig_break: bool
```

True if this edge bridges a contig boundary in a fragmented assembly.

#### is\_healed\_scar

```python
is_healed_scar: bool
```

True if this edge bridges a healed mobile genetic element (MGE) insertion.

#### from\_adjacent

```python
from_adjacent(strand_a: int, strand_b: int, gap_bp: int = 0) -> Self
```

Construct an `IntergenicType` from adjacent gene strands and base-pair distance.

### IntergenicEdge

Bases: `DirectedEdge`

Directed synteny edge connecting adjacent gene nodes `(source -> target)` in a `Locus`.

### GeneNode

Bases: `IntNode`

32-bit integer encoding for a gene node inside a biosynthetic locus graph.

Bit 0..4 (5 bits): Canonical `GeneRole` index (`0..29`). Bit 5 (1 bit): Frameshift / pseudogene indicator (`0` = intact, `1` = frameshifted). Bit 6..30 (25 bits): Sequence homology cluster ID (`0` = unclustered, `1..33,554,431` = cluster ID). Bit 31 (1 bit): `TAG_EDGE` (`0` = primary gene node).

Methods:

| Name | Description |
| --- | --- |
| `with_cluster` | Return a copy of this `GeneNode` with an updated homology `cluster_id`. |

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `role_idx` | `int` | Integer `GeneRole` index (`0..29`). |
| `role` | `GeneRole` | Canonical `GeneRole` enum member. |
| `is_frameshift` | `bool` | True if this gene contains a frameshift indel or premature stop. |
| `cluster_id` | `int` | Sequence homology cluster ID (`0` if unclustered). |
| `is_clustered` | `bool` | True if assigned to a homology cluster (`cluster_id > 0`). |
| `is_mobile_element` | `bool` | True if this node is a mobile genetic element (`TRANSPOSASE` or `INTEGRASE`). |
| `is_biosynthetic` | `bool` | True if this node is an active biosynthetic, modifier, or transport gene. |

#### role\_idx

```python
role_idx: int
```

Integer `GeneRole` index (`0..29`).

#### role

```python
role: GeneRole
```

Canonical `GeneRole` enum member.

#### is\_frameshift

```python
is_frameshift: bool
```

True if this gene contains a frameshift indel or premature stop.

#### cluster\_id

```python
cluster_id: int
```

Sequence homology cluster ID (`0` if unclustered).

#### is\_clustered

```python
is_clustered: bool
```

True if assigned to a homology cluster (`cluster_id > 0`).

#### is\_mobile\_element

```python
is_mobile_element: bool
```

True if this node is a mobile genetic element (`TRANSPOSASE` or `INTEGRASE`).

#### is\_biosynthetic

```python
is_biosynthetic: bool
```

True if this node is an active biosynthetic, modifier, or transport gene.

#### with\_cluster

```python
with_cluster(cluster_id: int) -> GeneNode
```

Return a copy of this `GeneNode` with an updated homology `cluster_id`.

### Locus

Bases: `GraphModel`

Scalar view and directed syntenic graph of a single biosynthetic gene cluster.

Embeds its constituent `Genes` container (`self.genes`), deriving per-gene intervals, strands, lengths, coding sequences, and frameshifts directly without duplicating metadata across parallel tuples.

Methods:

| Name | Description |
| --- | --- |
| `with_name` | Return a copy of this `Locus` with an updated identifier `name`. |
| `canonicalize_strand` | Orient the locus into canonical 5' -\> 3' operon order (`strand = +1`). |
| `heal_mobile_elements` | Excise mobile genetic element (`TRANSPOSASE`, `INTEGRASE`) insertions and heal synteny edges. |
| `from_genes` | Construct a `Locus` from either a `Genes` container or a sequence of gene symbols/roles. |
| `match` | Compare this `Locus` against a target `Locus` (returns `Match`) or target `Loci` database (returns `Matches`). |

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `num_genes` | `int` | Number of genes in this locus. |
| `start` | `int` | 0-based inclusive start coordinate on the parent contig. |
| `end` | `int` | 0-based exclusive end coordinate on the parent contig. |
| `strand` | `int` | Dominant transcriptional strand (`+1` or `-1`) of the locus. |
| `strands` | `ndarray[tuple[int], dtype[int8]]` | 1D `int8` array of per-gene transcriptional strands from `self.genes`. |
| `lengths` | `ndarray[tuple[int], dtype[int32]]` | 1D `int32` array of per-gene base-pair lengths from `self.genes`. |
| `roles` | `ndarray[tuple[int], dtype[int32]]` | 1D array of integer `GeneRole` indices (`0..29`) for each gene in the locus. |
| `cluster_ids` | `ndarray[tuple[int], dtype[int32]]` | 1D array of homology `cluster_id` values for each gene in the locus. |
| `frameshifts` | `ndarray[tuple[int], dtype[bool_]]` | 1D boolean array indicating which genes carry frameshift mutations. |
| `role_mask` | `int` | 32-bit integer presence bitmask of all `GeneRole`s present in this locus. |
| `has_mobile_elements` | `bool` | True if this locus contains any `TRANSPOSASE` or `INTEGRASE` insertions. |
| `has_mge` | `bool` | Alias for `has_mobile_elements`. |
| `is_fragmented` | `bool` | True if this locus spans multiple contigs across an assembly break. |
| `num_frameshifts` | `int` | Number of genes in this locus carrying frameshift mutations or premature stops. |
| `frameshift_fraction` | `float` | Fraction of genes in this locus (`[0.0, 1.0]`) carrying frameshift mutations. |
| `is_intact` | `bool` | True if this locus is on a single contig, has no mobile elements, and has no frameshifted genes. |
| `category` | `ArchetypeCategory` | High-level `ArchetypeCategory` (`Capsule`, `O-Antigen`, `Exopolysaccharide`, `Other`) of this locus. |
| `num_contigs` | `int` | Number of distinct contigs spanned by this locus. |

#### num\_genes

```python
num_genes: int
```

Number of genes in this locus.

#### start

```python
start: int
```

0-based inclusive start coordinate on the parent contig.

#### end

```python
end: int
```

0-based exclusive end coordinate on the parent contig.

#### strand

```python
strand: int
```

Dominant transcriptional strand (`+1` or `-1`) of the locus.

#### strands

```python
strands: ndarray[tuple[int], dtype[int8]]
```

1D `int8` array of per-gene transcriptional strands from `self.genes`.

#### lengths

```python
lengths: ndarray[tuple[int], dtype[int32]]
```

1D `int32` array of per-gene base-pair lengths from `self.genes`.

#### roles

```python
roles: ndarray[tuple[int], dtype[int32]]
```

1D array of integer `GeneRole` indices (`0..29`) for each gene in the locus.

#### cluster\_ids

```python
cluster_ids: ndarray[tuple[int], dtype[int32]]
```

1D array of homology `cluster_id` values for each gene in the locus.

#### frameshifts

```python
frameshifts: ndarray[tuple[int], dtype[bool_]]
```

1D boolean array indicating which genes carry frameshift mutations.

#### role\_mask

```python
role_mask: int
```

32-bit integer presence bitmask of all `GeneRole`s present in this locus.

#### has\_mobile\_elements

```python
has_mobile_elements: bool
```

True if this locus contains any `TRANSPOSASE` or `INTEGRASE` insertions.

#### has\_mge

```python
has_mge: bool
```

Alias for `has_mobile_elements`.

#### is\_fragmented

```python
is_fragmented: bool
```

True if this locus spans multiple contigs across an assembly break.

#### num\_frameshifts

```python
num_frameshifts: int
```

Number of genes in this locus carrying frameshift mutations or premature stops.

#### frameshift\_fraction

```python
frameshift_fraction: float
```

Fraction of genes in this locus (`[0.0, 1.0]`) carrying frameshift mutations.

#### is\_intact

```python
is_intact: bool
```

True if this locus is on a single contig, has no mobile elements, and has no frameshifted genes.

#### category

```python
category: ArchetypeCategory
```

High-level `ArchetypeCategory` (`Capsule`, `O-Antigen`, `Exopolysaccharide`, `Other`) of this locus.

#### num\_contigs

```python
num_contigs: int
```

Number of distinct contigs spanned by this locus.

#### with\_name

```python
with_name(name: str | bytes) -> Locus
```

Return a copy of this `Locus` with an updated identifier `name`.

#### canonicalize\_strand

```python
canonicalize_strand() -> Locus
```

Orient the locus into canonical 5' -\> 3' operon order (`strand = +1`).

If `self.strand >= 0`, returns `self` unchanged. If `self.strand < 0`, reverses `nodes` and `genes` and re-indexes `edges` so that directed synteny transitions run 5' -\> 3' along the dominant transcriptional strand.

#### heal\_mobile\_elements

```python
heal_mobile_elements(remove_nodes: bool = True) -> Locus
```

Excise mobile genetic element (`TRANSPOSASE`, `INTEGRASE`) insertions and heal synteny edges.

#### from\_genes

```python
from_genes(genes: Genes | Sequence[str | bytes | int | GeneRole] | ndarray, roles: Sequence[str | bytes | int | GeneRole] | ndarray | None = None, *, strands: Sequence[int] | ndarray | None = None, lengths: Sequence[int] | ndarray | None = None, clusters: Sequence[int] | ndarray | None = None, frameshifts: Sequence[bool] | ndarray | None = None, archetype: LocusArchetype = UNKNOWN, completeness: float = 0.0, score: float = 0.0, is_tandem_split: bool = False, contig_index: int = 0, name: str = '') -> Self
```

Construct a `Locus` from either a `Genes` container or a sequence of gene symbols/roles.

#### match

```python
match(targets: Locus | Loci, **kwargs: Any) -> Any
```

Compare this `Locus` against a target `Locus` (returns `Match`) or target `Loci` database (returns `Matches`).

### Loci

Bases: `GraphBatch[Locus, 'Loci']`

Structure-of-Arrays (SoA) batch container for biosynthetic gene clusters (`Locus`).

Combines `GraphBatch` sparse topology arrays (`node_types`, `node_offsets`, `edge_sources`, `edge_targets`, `edge_types`, `edge_offsets`) with a flat `Genes` container (`self.genes`, indexed per locus by `node_offsets`) and per-locus archetype metadata.

Methods:

| Name | Description |
| --- | --- |
| `with_names` | Return a new `Loci` batch with updated per-locus identifier `names`. |
| `best` | Return the highest-scoring `Locus` in the batch (or `None` if empty). |
| `filter` | Filter loci by `names`, ontology `categories`, specific `archetypes`, `min_completeness`, `min_score`, `max_frameshift_fraction`, and/or `only_intact`. |
| `empty` | Create an empty 0-length `Loci` container. |
| `concat` | Concatenate multiple `Loci` batches into a single contiguous `Loci` container. |
| `from_list` | Compile a sequence of scalar `Locus` objects into a contiguous `Loci` batch. |
| `canonicalize_strands` | Orient all loci in the batch into canonical 5' -\> 3' operon order (`strand = +1`). |
| `heal_mobile_elements` | Excise mobile genetic element (`TRANSPOSASE`, `INTEGRASE`) insertions across all loci in the batch. |
| `with_clusters` | Return a new `Loci` batch with homology `cluster_id` bitfields updated from `Clusters` or an ID array. |
| `cluster_genes` | Cluster translated locus proteins and return a new `Loci` batch with packed homology `CLUSTER_ID`s. |
| `as_pan_graph` | Compress the `Loci` batch into a directed consensus pan-locus graph. |
| `match` | Compare one or more `query` loci against this `Loci` batch acting as a reference database. |

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `roles` | `ndarray[tuple[int], dtype[int32]]` | Flat 1D array of `GeneRole` indices (`0..29`) across all gene nodes in the batch. |
| `cluster_ids` | `ndarray[tuple[int], dtype[int32]]` | Flat 1D array of homology `cluster_id` values across all gene nodes in the batch. |
| `is_fragmented` | `ndarray[tuple[int], dtype[bool_]]` | 1D boolean array (`(N,)`) indicating whether each locus spans a contig break (`gap_bin == 14`). |
| `num_frameshifts` | `ndarray[tuple[int], dtype[int32]]` | 1D `int32` array (`(N,)`) of frameshifted gene counts per locus. |
| `frameshift_fractions` | `ndarray[tuple[int], dtype[float32]]` | 1D `float32` array (`(N,)`) of frameshifted gene fractions (`[0.0, 1.0]`) per locus. |
| `has_mge` | `ndarray[tuple[int], dtype[bool_]]` | 1D boolean array (`(N,)`) indicating whether each locus contains `TRANSPOSASE` or `INTEGRASE` insertions. |
| `is_intact` | `ndarray[tuple[int], dtype[bool_]]` | 1D boolean array (`(N,)`) indicating whether each locus is single-contig, MGE-free, and frameshift-free. |
| `categories` | `ndarray[tuple[int], dtype[str_]]` | 1D string array (`(N,)`) of `ArchetypeCategory` values (`'Capsule'`, `'O-Antigen'`, etc.) per locus. |

#### roles

```python
roles: ndarray[tuple[int], dtype[int32]]
```

Flat 1D array of `GeneRole` indices (`0..29`) across all gene nodes in the batch.

#### cluster\_ids

```python
cluster_ids: ndarray[tuple[int], dtype[int32]]
```

Flat 1D array of homology `cluster_id` values across all gene nodes in the batch.

#### is\_fragmented

```python
is_fragmented: ndarray[tuple[int], dtype[bool_]]
```

1D boolean array (`(N,)`) indicating whether each locus spans a contig break (`gap_bin == 14`).

#### num\_frameshifts

```python
num_frameshifts: ndarray[tuple[int], dtype[int32]]
```

1D `int32` array (`(N,)`) of frameshifted gene counts per locus.

#### frameshift\_fractions

```python
frameshift_fractions: ndarray[tuple[int], dtype[float32]]
```

1D `float32` array (`(N,)`) of frameshifted gene fractions (`[0.0, 1.0]`) per locus.

#### has\_mge

```python
has_mge: ndarray[tuple[int], dtype[bool_]]
```

1D boolean array (`(N,)`) indicating whether each locus contains `TRANSPOSASE` or `INTEGRASE` insertions.

#### is\_intact

```python
is_intact: ndarray[tuple[int], dtype[bool_]]
```

1D boolean array (`(N,)`) indicating whether each locus is single-contig, MGE-free, and frameshift-free.

#### categories

```python
categories: ndarray[tuple[int], dtype[str_]]
```

1D string array (`(N,)`) of `ArchetypeCategory` values (`'Capsule'`, `'O-Antigen'`, etc.) per locus.

#### with\_names

```python
with_names(names: Sequence[str | bytes] | ndarray) -> Self
```

Return a new `Loci` batch with updated per-locus identifier `names`.

#### best

```python
best(*, prefer_intact: bool = False) -> Locus | None
```

Return the highest-scoring `Locus` in the batch (or `None` if empty).

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `prefer_intact` | `bool` | If True, prioritize intact loci without frameshifts or assembly breaks (e.g., an intact ectopic `CPS_SYNTHASE` over a frameshifted/cryptic `CPS_WZY` pseudogene cluster). | `False` |

#### filter

```python
filter(*, names: str | Iterable[str] | None = None, categories: ArchetypeCategory | str | Iterable[ArchetypeCategory | str] | None = None, archetypes: LocusArchetype | str | int | Iterable[LocusArchetype | str | int] | None = None, min_completeness: float = 0.0, min_score: float = 0.0, max_frameshift_fraction: float = 1.0, only_intact: bool = False) -> Self
```

Filter loci by `names`, ontology `categories`, specific `archetypes`, `min_completeness`, `min_score`, `max_frameshift_fraction`, and/or `only_intact`.

#### empty

```python
empty() -> Self
```

Create an empty 0-length `Loci` container.

#### concat

```python
concat(batches: Iterable[Self]) -> Self
```

Concatenate multiple `Loci` batches into a single contiguous `Loci` container.

#### from\_list

```python
from_list(loci: Sequence[Locus]) -> Self
```

Compile a sequence of scalar `Locus` objects into a contiguous `Loci` batch.

#### canonicalize\_strands

```python
canonicalize_strands() -> Self
```

Orient all loci in the batch into canonical 5' -\> 3' operon order (`strand = +1`).

#### heal\_mobile\_elements

```python
heal_mobile_elements(remove_nodes: bool = True) -> Self
```

Excise mobile genetic element (`TRANSPOSASE`, `INTEGRASE`) insertions across all loci in the batch.

#### with\_clusters

```python
with_clusters(clusters: Clusters | ndarray) -> Self
```

Return a new `Loci` batch with homology `cluster_id` bitfields updated from `Clusters` or an ID array.

#### cluster\_genes

```python
cluster_genes(clusterer: Clusterer | None = None, *, by_role: bool = True, classifier: Any | None = None, embedding_layer: str = 'task_weighted_conv_max', **kwargs: Any) -> Self
```

Cluster translated locus proteins and return a new `Loci` batch with packed homology `CLUSTER_ID`s.

#### as\_pan\_graph

```python
as_pan_graph(node_mask: int | None = None, *, canonicalize_strands: bool = True, heal_mges: bool = False, cluster_genes: bool = False, clusterer: Clusterer | None = None) -> tuple[csr_array, ndarray[tuple[int], dtype[uint32]], ndarray[tuple[int], dtype[uint32]]]
```

Compress the `Loci` batch into a directed consensus pan-locus graph.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `node_mask` | `int \| None` | Optional bitmask to apply to `GeneNode` values before merging (e.g., `GeneNode.mask("ROLE_ID", "CLUSTER_ID")`). | `None` |
| `canonicalize_strands` | `bool` | If True (default), orient `-1` strand loci into canonical 5' -\> 3' operon order prior to graph compression. | `True` |
| `heal_mges` | `bool` | If True, excise `TRANSPOSASE` and `INTEGRASE` insertions and heal synteny edges prior to graph compression. | `False` |
| `cluster_genes` | `bool` | If True (or if `clusterer` is provided), cluster translated gene proteins and pack homology `CLUSTER_ID`s into nodes before merging. | `False` |
| `clusterer` | `Clusterer \| None` | Optional pre-configured `Clusterer` instance to use when clustering proteins. | `None` |

Returns:

| Type | Description |
| --- | --- |
| `tuple[csr_array, ndarray[tuple[int], dtype[uint32]], ndarray[tuple[int], dtype[uint32]]]` | A tuple of `(adj, pan_nodes, node_counts)`. |

#### match

```python
match(query: Locus | Loci, *, top_k: int | None = None, min_score: float = 0.0, sort: bool = True, **matcher_kwargs: Any) -> Any
```

Compare one or more `query` loci against this `Loci` batch acting as a reference database.

---

## Biosynthetic Archetypes (`serogen.loci.archetypes`)

## archetypes

Biosynthetic locus archetypes, ontology categories, and structural specifications.

Classes:

| Name | Description |
| --- | --- |
| `ArchetypeCategory` | High-level structural category of a polysaccharide biosynthetic locus archetype. |
| `ArchetypeSpec` | Immutable biological specification for a canonical `LocusArchetype`. |
| `LocusArchetype` | Canonical biosynthetic locus archetypes (0..10). |
| `ArchetypeTensors` | Immutable container holding precomputed bitmask and role-indicator tensors for all `LocusArchetype`s. |

Functions:

| Name | Description |
| --- | --- |
| `roles_to_mask` | Pack a collection of `GeneRole` values into a 32-bit integer presence bitmask. |
| `mask_to_roles` | Unpack a 32-bit integer presence bitmask into a sorted tuple of `GeneRole` enums. |
| `get_archetype_tensors` | Return the cached singleton `ArchetypeTensors` instance. |

### ArchetypeCategory

Bases: `StrEnum`

High-level structural category of a polysaccharide biosynthetic locus archetype.

### ArchetypeSpec

Immutable biological specification for a canonical `LocusArchetype`.

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `required_mask` | `int` | Combined 32-bit union mask of all roles participating in any required module. |
| `all_relevant_mask` | `int` | Combined 32-bit bitmask of all required and optional cargo roles. |
| `num_modules` | `int` | Number of required functional modules (`M_A`) for this archetype. |

#### required\_mask

```python
required_mask: int
```

Combined 32-bit union mask of all roles participating in any required module.

#### all\_relevant\_mask

```python
all_relevant_mask: int
```

Combined 32-bit bitmask of all required and optional cargo roles.

#### num\_modules

```python
num_modules: int
```

Number of required functional modules (`M_A`) for this archetype.

### LocusArchetype

Bases: `IntEnum`

Canonical biosynthetic locus archetypes (0..10).

Defines the ontological classification and structural requirements of bacterial surface polysaccharide biosynthetic gene clusters. Scoring, completeness evaluation, and segment classification are encapsulated in `ArchetypeClassifier`.

Methods:

| Name | Description |
| --- | --- |
| `from_name` | Resolve an archetype by integer ID, enum name, or biological alias. |
| `resolve` | Resolve an archetype identifier, falling back to `default` (or `UNKNOWN`). |

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `spec` | `ArchetypeSpec` | Return the `ArchetypeSpec` metadata record for this archetype. |
| `category` | `ArchetypeCategory` | High-level `ArchetypeCategory` (`Capsule`, `O-Antigen`, `Exopolysaccharide`, `Other`). |
| `forbidden_mask` | `int` | 32-bit bitmask of `GeneRole` bits that are incompatible with this archetype. |
| `cargo_mask` | `int` | 32-bit bitmask of optional cargo/modifier/precursor `GeneRole` bits. |
| `required_mask` | `int` | Combined 32-bit union mask of all roles participating in any required module. |
| `all_relevant_mask` | `int` | Combined 32-bit bitmask of all required and optional cargo roles. |
| `description` | `str` | Human-readable biological description of the pathway. |
| `module_masks` | `tuple[int, ...]` | Tuple of 32-bit disjunctive module bitmasks (`M_1, ..., M_k`) required for completeness. |
| `num_modules` | `int` | Number of required functional modules (`M_A`) for this archetype. |

#### spec

```python
spec: ArchetypeSpec
```

Return the `ArchetypeSpec` metadata record for this archetype.

#### category

```python
category: ArchetypeCategory
```

High-level `ArchetypeCategory` (`Capsule`, `O-Antigen`, `Exopolysaccharide`, `Other`).

#### forbidden\_mask

```python
forbidden_mask: int
```

32-bit bitmask of `GeneRole` bits that are incompatible with this archetype.

#### cargo\_mask

```python
cargo_mask: int
```

32-bit bitmask of optional cargo/modifier/precursor `GeneRole` bits.

#### required\_mask

```python
required_mask: int
```

Combined 32-bit union mask of all roles participating in any required module.

#### all\_relevant\_mask

```python
all_relevant_mask: int
```

Combined 32-bit bitmask of all required and optional cargo roles.

#### description

```python
description: str
```

Human-readable biological description of the pathway.

#### module\_masks

```python
module_masks: tuple[int, ...]
```

Tuple of 32-bit disjunctive module bitmasks (`M_1, ..., M_k`) required for completeness.

#### num\_modules

```python
num_modules: int
```

Number of required functional modules (`M_A`) for this archetype.

#### from\_name

```python
from_name(key: str | bytes | int | LocusArchetype) -> LocusArchetype
```

Resolve an archetype by integer ID, enum name, or biological alias.

#### resolve

```python
resolve(key: str | bytes | int | LocusArchetype, default: LocusArchetype | None = None) -> LocusArchetype
```

Resolve an archetype identifier, falling back to `default` (or `UNKNOWN`).

### ArchetypeTensors

Immutable container holding precomputed bitmask and role-indicator tensors for all `LocusArchetype`s.

Encapsulates the vectorized lookup tables required by `ArchetypeClassifier` and `LocusSegmenter`.

Methods:

| Name | Description |
| --- | --- |
| `build` | Construct and freeze all archetype bitmask and indicator tensors from `LocusArchetype` specs. |

#### build

```python
build() -> Self
```

Construct and freeze all archetype bitmask and indicator tensors from `LocusArchetype` specs.

### roles\_to\_mask

```python
roles_to_mask(roles: Iterable[int | GeneRole] | ndarray) -> int
```

Pack a collection of `GeneRole` values into a 32-bit integer presence bitmask.

### mask\_to\_roles

```python
mask_to_roles(mask: int) -> tuple[GeneRole, ...]
```

Unpack a 32-bit integer presence bitmask into a sorted tuple of `GeneRole` enums.

### get\_archetype\_tensors

```python
get_archetype_tensors() -> ArchetypeTensors
```

Return the cached singleton `ArchetypeTensors` instance.

---

## Archetype Classification (`serogen.loci.classifier`)

## classifier

Probabilistic and bitmask-based classifier for biosynthetic locus archetypes.

Classes:

| Name | Description |
| --- | --- |
| `ArchetypeClassifier` | Scikit-learn compatible classifier and segment scorer for `LocusArchetype`s. |

### ArchetypeClassifier

Scikit-learn compatible classifier and segment scorer for `LocusArchetype`s.

Encapsulates all discrete bitmask evaluations and continuous noisy-OR log-likelihood-ratio (LLR) scoring over `ArchetypeTensors`. Works out-of-the-box with domain-calibrated weights (`w_comp`, `w_incomp`, `w_llr`, `unknown_logit`), and optionally supports empirical weight calibration via `.fit(X, y)` on labeled loci.

Methods:

| Name | Description |
| --- | --- |
| `check_modules` | Count how many required functional modules are satisfied for each archetype (`(11,)`). |
| `check_forbidden` | Return a boolean array `(11,)` indicating whether any forbidden role is present. |
| `is_complete` | Evaluate whether a 32-bit role presence mask satisfies each archetype. |
| `classify_mask` | Classify a single 32-bit role presence mask into its best-matching `LocusArchetype`. |
| `is_boundary_relevant` | Return True if `role` is a valid boundary/anchor/cargo gene for `archetype` (excluding MGEs/UNKNOWN). |
| `to_probability_matrix` | Convert 1D discrete role indices or a 2D probability matrix into a clean `(L, 30)` float64 matrix. |
| `precompute_prefixes` | Precompute \\(O(L)\\) prefix sums of log-complement and log-odds probabilities across a contig. |
| `score_segments` | Evaluate completeness, incompatibility, and LLR scores for \\(K\\) candidate segments in \\(O(K \\cdot \|\\mathcal{A}\|)\\). |
| `score_components` | Compute `(llr_scores, completeness, incompatibility)` matrices of shape `(N, 11)` across a batch. |
| `decision_function` | Compute unnormalized archetype logits of shape `(N, 11)` for input segments. |
| `predict_proba` | Compute calibrated softmax posterior probabilities `(N, 11)` across archetypes. |
| `predict` | Predict the integer `LocusArchetype` index (`0..10`) for each input locus or segment. |
| `classify` | Classify a single `Locus`, role sequence, or `(L, 30)` probability matrix into `(archetype, completeness, score)`. |
| `fit` | Calibrate `w_comp_`, `w_incomp_`, `w_llr_`, and `unknown_logit_` via L-BFGS-B cross-entropy minimization. |
| `score` | Compute classification accuracy on labeled segments `(X, y)`. |

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `classes_` | `ndarray[tuple[int], dtype[int32]]` | 1D array of archetype class labels (`0..10`). |
| `active_weights` | `tuple[float, float, float, float]` | Return `(w_comp, w_incomp, w_llr, unknown_logit)`, preferring fitted parameters if present. |

#### classes\_

```python
classes_: ndarray[tuple[int], dtype[int32]]
```

1D array of archetype class labels (`0..10`).

#### active\_weights

```python
active_weights: tuple[float, float, float, float]
```

Return `(w_comp, w_incomp, w_llr, unknown_logit)`, preferring fitted parameters if present.

#### check\_modules

```python
check_modules(mask: int) -> ndarray[tuple[int], dtype[int32]]
```

Count how many required functional modules are satisfied for each archetype (`(11,)`).

#### check\_forbidden

```python
check_forbidden(mask: int) -> ndarray[tuple[int], dtype[bool_]]
```

Return a boolean array `(11,)` indicating whether any forbidden role is present.

#### is\_complete

```python
is_complete(mask: int, min_completeness: float | None = None) -> ndarray[tuple[int], dtype[bool_]]
```

Evaluate whether a 32-bit role presence mask satisfies each archetype.

#### classify\_mask

```python
classify_mask(mask: int, min_completeness: float | None = None) -> tuple[LocusArchetype, float]
```

Classify a single 32-bit role presence mask into its best-matching `LocusArchetype`.

#### is\_boundary\_relevant

```python
is_boundary_relevant(archetype: LocusArchetype | int, role: GeneRole | int) -> bool
```

Return True if `role` is a valid boundary/anchor/cargo gene for `archetype` (excluding MGEs/UNKNOWN).

#### to\_probability\_matrix

```python
to_probability_matrix(roles_or_probs: ndarray | Sequence[int | GeneRole], confidence: float = 0.98) -> ndarray[tuple[int, int], dtype[float64]]
```

Convert 1D discrete role indices or a 2D probability matrix into a clean `(L, 30)` float64 matrix.

#### precompute\_prefixes

```python
precompute_prefixes(probs: ndarray[tuple[int, int], dtype[float64]]) -> tuple[ndarray[tuple[int, int, int], dtype[float64]], ndarray[tuple[int, int], dtype[float64]], ndarray[tuple[int, int], dtype[float64]]]
```

Precompute \\(O(L)\\) prefix sums of log-complement and log-odds probabilities across a contig.

#### score\_segments

```python
score_segments(starts: ndarray[tuple[int], dtype[intp]], ends: ndarray[tuple[int], dtype[intp]], *, probs: ndarray[tuple[int, int], dtype[float64]] | None = None, prefixes: tuple[ndarray, ndarray, ndarray] | None = None) -> tuple[ndarray[tuple[int, int], dtype[float64]], ndarray[tuple[int, int], dtype[float64]], ndarray[tuple[int, int], dtype[float64]]]
```

Evaluate completeness, incompatibility, and LLR scores for \\(K\\) candidate segments in \\(O(K \\cdot |\\mathcal{A}|)\\).

#### score\_components

```python
score_components(X: ArchetypeInput) -> tuple[ndarray[tuple[int, int], dtype[float64]], ndarray[tuple[int, int], dtype[float64]], ndarray[tuple[int, int], dtype[float64]]]
```

Compute `(llr_scores, completeness, incompatibility)` matrices of shape `(N, 11)` across a batch.

#### decision\_function

```python
decision_function(X: ArchetypeInput) -> ndarray[tuple[int, int], dtype[float64]]
```

Compute unnormalized archetype logits of shape `(N, 11)` for input segments.

#### predict\_proba

```python
predict_proba(X: ArchetypeInput) -> ndarray[tuple[int, int], dtype[float64]]
```

Compute calibrated softmax posterior probabilities `(N, 11)` across archetypes.

#### predict

```python
predict(X: ArchetypeInput) -> ndarray[tuple[int], dtype[int32]]
```

Predict the integer `LocusArchetype` index (`0..10`) for each input locus or segment.

#### classify

```python
classify(X: Locus | ndarray | Sequence[int | GeneRole]) -> tuple[LocusArchetype, float, float]
```

Classify a single `Locus`, role sequence, or `(L, 30)` probability matrix into `(archetype, completeness, score)`.

#### fit

```python
fit(X: ArchetypeInput, y: Sequence[int | LocusArchetype] | ndarray) -> Self
```

Calibrate `w_comp_`, `w_incomp_`, `w_llr_`, and `unknown_logit_` via L-BFGS-B cross-entropy minimization.

#### score

```python
score(X: ArchetypeInput, y: Sequence[int | LocusArchetype] | ndarray) -> float
```

Compute classification accuracy on labeled segments `(X, y)`.

---

## Reference Serotype Matching (`serogen.loci.matcher`)

## matcher

Vectorized locus comparison, structural difference bitflags, and database matching.

Classes:

| Name | Description |
| --- | --- |
| `MatchType` | Composable bitflag enumeration describing how two biosynthetic loci differ. |
| `Match` | Scalar view of a pairwise comparison between a query locus and a target locus. |
| `Matches` | Vectorized Structure-of-Arrays (SoA) batch container of locus comparison results. |
| `LocusNodeCostStrategy` | Semantic node compatibility cost model for aligning two `Locus` graphs via `GraphAligner`. |
| `LocusMatcher` | Vectorized 1-to-many and batch-to-many biosynthetic locus matcher. |

### MatchType

Bases: `IntFlag`

Composable bitflag enumeration describing how two biosynthetic loci differ.

`MatchType.EXACT` (`0`) indicates that two loci share identical non-MGE gene content, gene order, relative transcriptional orientations, dominant strand, frameshift state, and mobile genetic element (MGE) state. Any combination of structural or allelic differences is represented as the bitwise OR of the corresponding variant flags.

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `is_exact` | `bool` | True if no variant flags are set (`self == MatchType.EXACT`). |
| `is_novel` | `bool` | True if the comparison involves gene gain/loss, synteny rearrangement, or archetype mismatch. |
| `flag_count` | `int` | Number of active difference bitflags set in this `MatchType`. |

#### is\_exact

```python
is_exact: bool
```

True if no variant flags are set (`self == MatchType.EXACT`).

#### is\_novel

```python
is_novel: bool
```

True if the comparison involves gene gain/loss, synteny rearrangement, or archetype mismatch.

#### flag\_count

```python
flag_count: int
```

Number of active difference bitflags set in this `MatchType`.

### Match

Bases: `ScalarView`

Scalar view of a pairwise comparison between a query locus and a target locus.

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `is_exact` | `bool` | True if the query and target loci are an exact match (`MatchType.EXACT`). |
| `is_novel` | `bool` | True if the query differs from this target by gene content, synteny, or archetype. |

#### is\_exact

```python
is_exact: bool
```

True if the query and target loci are an exact match (`MatchType.EXACT`).

#### is\_novel

```python
is_novel: bool
```

True if the query differs from this target by gene content, synteny, or archetype.

### Matches

Bases: `BatchedContainer[Match, 'Matches']`

Vectorized Structure-of-Arrays (SoA) batch container of locus comparison results.

Methods:

| Name | Description |
| --- | --- |
| `empty` | Create an empty 0-length `Matches` container. |
| `concat` | Concatenate multiple `Matches` containers into a single batch. |
| `sort` | Sort matches by score, breaking ties by fewer `MatchType` bitflags, higher AA identity, and lower `target_index`. |
| `best` | Return the highest-scoring `Match` across the container (or `None` if empty). |
| `best_per_query` | Return a `Matches` container holding the single best target match for each unique `query_index`. |
| `filter` | Filter matches by minimum similarity metrics and/or permitted `MatchType` flags. |

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `is_novel` | `ndarray[tuple[int], dtype[bool_]]` | 1D boolean array (`(N,)`) indicating whether each match involves gene, synteny, or archetype divergence. |

#### is\_novel

```python
is_novel: ndarray[tuple[int], dtype[bool_]]
```

1D boolean array (`(N,)`) indicating whether each match involves gene, synteny, or archetype divergence.

#### empty

```python
empty() -> Self
```

Create an empty 0-length `Matches` container.

#### concat

```python
concat(batches: Iterable[Self]) -> Self
```

Concatenate multiple `Matches` containers into a single batch.

#### sort

```python
sort(descending: bool = True) -> Self
```

Sort matches by score, breaking ties by fewer `MatchType` bitflags, higher AA identity, and lower `target_index`.

#### best

```python
best() -> Match | None
```

Return the highest-scoring `Match` across the container (or `None` if empty).

#### best\_per\_query

```python
best_per_query() -> Self
```

Return a `Matches` container holding the single best target match for each unique `query_index`.

#### filter

```python
filter(*, min_score: float = 0.0, min_jaccard: float = 0.0, min_coverage: float = 0.0, allowed_flags: MatchType | None = None) -> Self
```

Filter matches by minimum similarity metrics and/or permitted `MatchType` flags.

### LocusNodeCostStrategy

Bases: `CostStrategy`

Semantic node compatibility cost model for aligning two `Locus` graphs via `GraphAligner`.

### LocusMatcher

Vectorized 1-to-many and batch-to-many biosynthetic locus matcher.

Indexes a reference database of target `Loci` (automatically clustering target proteins and building a single `RandstrobeIndex` over target proteins when translations are present) and compares query `Locus` or `Loci` instances in parallel via `_match_loci_kernel`.

Methods:

| Name | Description |
| --- | --- |
| `assign_query_clusters` | Assign target homology `CLUSTER_ID`s and compute per-gene AA identity in a single `RandstrobeIndex` pass. |
| `match` | Compare one or more query loci against all indexed target loci. |
| `align` | Perform detailed node-by-node bipartite `GraphAligner` alignment between `query` and `targets[target_index]`. |

#### assign\_query\_clusters

```python
assign_query_clusters(queries: Loci) -> tuple[Loci, ndarray[tuple[int], dtype[float32]], ndarray[tuple[int, int], dtype[float32]]]
```

Assign target homology `CLUSTER_ID`s and compute per-gene AA identity in a single `RandstrobeIndex` pass.

#### match

```python
match(query: Locus | Loci | Iterable[Locus], *, top_k: int | None = None, min_score: float = 0.0, sort: bool = True) -> Matches
```

Compare one or more query loci against all indexed target loci.

#### align

```python
align(query: Locus, target_index: int | str, *, canonicalize_strand: bool = True, heal_mges: bool = False) -> Alignment
```

Perform detailed node-by-node bipartite `GraphAligner` alignment between `query` and `targets[target_index]`.
