# `serogen.genes`

Single-pass bacterial and prophage Open Reading Frame (ORF) prediction, functional gene role ontology, and multi-channel 1D CNN protein classification.

---

## ORF Prediction (`serogen.genes.orf.predictor`)

## predictor

OrfPredictor high-level execution engine for sequences and assemblies.

Classes:

| Name | Description |
| --- | --- |
| `OrfPredictor` | High-performance Open Reading Frame (ORF) predictor. |

### OrfPredictor

High-performance Open Reading Frame (ORF) predictor.

Executes Numba JIT-compiled FragGeneScan HMM decoding over single sequences, `Sequences`, or `GenomeAssembly` containers using a unified flat window table and Numba `prange` parallelism, returning batched `Genes`. Supports bacterial and viral/phage translation tables and single-pass co-prediction of bacterial and prophage/phage ORFs.

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `model` | `HMM` | Baked HMM model parameter container. |
| `genetic_code` | `GeneticCode` | Translation table defining start/stop codons and amino acid mappings. |
| `include_phage` | `bool` | If True, enables single-pass phage/prophage ORF co-prediction (sliding local GC adaptation, overlapping operon transitions, and small ORF recovery). |
| `min_gene_len` | `int` | Minimum gene length in nucleotides. |
| `local_gc_window` | `int` | Sliding window size in bp for local GC bin adaptation. |

Methods:

| Name | Description |
| --- | --- |
| `predict` | Predict Open Reading Frames across target sequences. |

#### predict

```python
predict(target: bytes | str | Sequence | Sequences | GenomeAssembly) -> Genes
```

Predict Open Reading Frames across target sequences.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `target` | `bytes \| str \| Sequence \| Sequences \| GenomeAssembly` | Input genomic sequence(s). | *required* |

Returns:

| Name | Type | Description |
| --- | --- | --- |
| `Genes` | `Genes` | Batched `Genes` container containing interval coordinates, in-frame coding sequences (5' -\> 3'), contig assignments, frameshift indels, and `is_partial` mask. |

Raises:

| Type | Description |
| --- | --- |
| `TypeError` | If target is not a supported sequence type. |

---

## Gene Containers &amp; HMM Parameters (`serogen.genes.models`)

## models

Structure-of-Arrays data containers for predicted genes, indels, and HMM parameters.

Classes:

| Name | Description |
| --- | --- |
| `IndelKind` | Indel mutation type for frameshift tracking. |
| `IndelRecord` | Scalar view of frameshift indel events for a single gene. |
| `Indels` | Ragged Structure-of-Arrays container for frameshift indels across a Genes batch. |
| `Gene` | Scalar view of a single predicted gene. |
| `Genes` | Structure-of-Arrays (SoA) container for predicted genes. |
| `HMM` | Container holding baked FragGeneScan HMM parameters. |

Functions:

| Name | Description |
| --- | --- |
| `get_hmm_model` | Return cached singleton instance of the default bundled HMM model. |

### IndelKind

Bases: `IntEnum`

Indel mutation type for frameshift tracking.

### IndelRecord

Scalar view of frameshift indel events for a single gene.

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `positions` | `ndarray` | 0-based contig coordinates where indels occurred. |
| `kinds` | `ndarray` | Indel mutation types (+1 for Insertion, -1 for Deletion). |

### Indels

Bases: `RaggedArrayContainer[IndelRecord, 'Indels']`

Ragged Structure-of-Arrays container for frameshift indels across a Genes batch.

Stores variable-length indel event coordinates and mutation kinds in flat contiguous arrays, indexed via `offsets` and `lengths` per gene.

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `positions` | `ndarray` | 1D array of 0-based contig coordinates across all indels. |
| `kinds` | `ndarray` | 1D array of indel kinds (+1=ins, -1=del). |
| `offsets` | `ndarray` | Starting index into `positions` and `kinds` for each gene. |
| `lengths` | `ndarray` | Number of indels for each gene. |

Methods:

| Name | Description |
| --- | --- |
| `empty` | Create an empty Indels container. |
| `concat` | Concatenate multiple Indels containers into a single batch. |

#### empty

```python
empty(length: int = 0) -> Indels
```

Create an empty Indels container.

#### concat

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

Concatenate multiple Indels containers into a single batch.

### Gene

Scalar view of a single predicted gene.

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `interval` | `Interval` | Genomic interval coordinate (`Interval`). |
| `seq` | `Sequence \| None` | Coding nucleotide or protein sequence (`Sequence`). |
| `contig_index` | `int` | 0-based contig index offset corresponding to parent contig name. |
| `indels` | `IndelRecord` | Scalar frameshift indel record (`IndelRecord`). |
| `is_partial` | `bool` | True if the ORF is truncated at a contig boundary without a start or stop codon. |

### Genes

Bases: `BatchedContainer[Gene, 'Genes']`

Structure-of-Arrays (SoA) container for predicted genes.

Stores interval coordinates, in-frame coding nucleotide sequences, and contig index mappings for a collection of predicted Open Reading Frames (ORFs). Inherits vectorised slicing and concatenation interface from `BatchedContainer`.

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `intervals` | `Intervals` | Genomic interval coordinates for predicted ORFs (`Intervals`). |
| `seqs` | `Sequences` | In-frame coding nucleotide sequences oriented 5' to 3' (`Sequences`). |
| `contig_indices` | `ndarray[tuple[int], dtype[uint32]]` | 1D array of 0-based contig index offsets corresponding to parent contig names. |
| `indels` | `Indels` | Ragged frameshift indel records. |
| `is_partial` | `ndarray[tuple[int], dtype[bool_]]` | Boolean mask indicating contig-edge partial ORFs. |

Methods:

| Name | Description |
| --- | --- |
| `translate` | Translate coding nucleotide sequences into protein sequences. |
| `empty` | Create an empty `Genes` container. |
| `concat` | Concatenate multiple `Genes` batches into a single container. |

#### has\_frameshift

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

Boolean mask indicating which genes contain at least one frameshift indel.

#### frameshift\_count

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

Array of frameshift indel counts per gene.

#### translations

```python
translations: Sequences
```

Translated protein sequences.

Returns pre-computed translations if provided, or computes them lazily using `self.genetic_code`.

Returns:

| Name | Type | Description |
| --- | --- | --- |
| `Sequences` | `Sequences` | Protein translation sequences. |

#### translate

```python
translate(code: GeneticCode | int | str | None = None, to_stop: bool = True) -> Sequences
```

Translate coding nucleotide sequences into protein sequences.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `code` | `GeneticCode \| int \| str \| None` | Genetic code translation table to use. If None, uses `self.genetic_code`. | `None` |
| `to_stop` | `bool` | If True, truncates translation at the first stop codon (\*). Defaults to True. | `True` |

Returns:

| Name | Type | Description |
| --- | --- | --- |
| `Sequences` | `Sequences` | Translated protein sequences. |

#### empty

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

Create an empty `Genes` container.

#### concat

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

Concatenate multiple `Genes` batches into a single container.

### HMM

Container holding baked FragGeneScan HMM parameters.

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `tr` | `ndarray` | Global transition penalties (14,). |
| `tr_mi` | `ndarray` | Match-to-insertion transitions (4, 4). |
| `tr_ii` | `ndarray` | Insertion-to-insertion transitions (4, 4). |
| `pi` | `ndarray` | Initial state log-probabilities (29,). |
| `e_m` | `ndarray` | Forward match state emission log-probabilities (44, 6, 16, 4). |
| `e_m1` | `ndarray` | Reverse match state emission log-probabilities (44, 6, 16, 4). |
| `tr_rr` | `ndarray` | Non-coding state transitions (44, 4, 4). |
| `tr_s` | `ndarray` | PWM window transitions around forward start (44, 61, 64). |
| `tr_e` | `ndarray` | PWM window transitions around forward stop (44, 61, 64). |
| `tr_s1` | `ndarray` | PWM window transitions around reverse start (44, 61, 64). |
| `tr_e1` | `ndarray` | PWM window transitions around reverse stop (44, 61, 64). |
| `dist_s` | `ndarray` | Gaussian parameters for forward start (44, 6). |
| `dist_e` | `ndarray` | Gaussian parameters for forward stop (44, 6). |
| `dist_s1` | `ndarray` | Gaussian parameters for reverse start (44, 6). |
| `dist_e1` | `ndarray` | Gaussian parameters for reverse stop (44, 6). |

Methods:

| Name | Description |
| --- | --- |
| `load` | Load HMM parameters from compressed NumPy archive (.npz). |

#### load

```python
load(path: str | Path | None = None) -> HMM
```

Load HMM parameters from compressed NumPy archive (.npz).

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `path` | `str \| Path \| None` | Optional path to .npz archive. If None, loads the bundled default model located at `serogen/bgc/data/fgs_model.npz`. | `None` |

Returns:

| Name | Type | Description |
| --- | --- | --- |
| `HMM` | `HMM` | Instantiated HMM parameter container. |

### get\_hmm\_model

```python
get_hmm_model() -> HMM
```

Return cached singleton instance of the default bundled HMM model.

Returns:

| Name | Type | Description |
| --- | --- | --- |
| `HMM` | `HMM` | Default baked model. |

---

## Functional Gene Role Ontology (`serogen.genes.roles`)

## roles

Canonical biosynthetic gene roles, metadata specifications, and 4-tier regex classification.

Classes:

| Name | Description |
| --- | --- |
| `RoleCategory` | Functional category of a biosynthetic gene role. |
| `RoleSpec` | Immutable metadata and classification specification for a canonical gene role. |
| `GeneRole` | Canonical biosynthetic gene roles (0..29) for surface polysaccharide loci. |

### RoleCategory

Bases: `StrEnum`

Functional category of a biosynthetic gene role.

### RoleSpec

Immutable metadata and classification specification for a canonical gene role.

### GeneRole

Bases: `IntEnum`

Canonical biosynthetic gene roles (0..29) for surface polysaccharide loci.

Subclasses `IntEnum` for zero-overhead integer semantics in bitfields (`IntNode`), 32-bit presence masks (`1 << role`), Numba kernels, and SciPy CSR matrices.

Methods:

| Name | Description |
| --- | --- |
| `from_name` | Resolve a role from an integer index, canonical name, abbreviation, or alias. |
| `resolve` | Resolve a role identifier, falling back to `default` (or `GeneRole.UNKNOWN`) if not found. |
| `names_array` | Contiguous 1D NumPy string array of canonical role names. |
| `abbreviations_array` | Contiguous 1D NumPy string array of role abbreviations. |
| `categories_array` | Contiguous 1D NumPy string array of role categories. |
| `feature_matrix` | Return precomputed `(30, D)` float32 one-hot category feature matrix for embeddings. |
| `label` | Assign gene role indices for a single gene or batch of genes using the 4-tier strategy. |

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `spec` | `RoleSpec` | Return the immutable `RoleSpec` metadata for this role. |
| `abbreviation` | `str` | Short display abbreviation (e.g. `'Wzx'`, `'GT'`). |
| `abbr` | `str` | Alias for `abbreviation`. |
| `category` | `RoleCategory` | Functional `RoleCategory` of this gene role. |
| `description` | `str` | Human-readable biochemical description. |
| `aliases` | `tuple[str, ...]` | Known gene symbol aliases for this role. |
| `trusted_prefixes` | `tuple[str, ...]` | Trusted canonical gene symbol prefixes for Tier-1 classification. |
| `bitmask` | `int` | 32-bit integer bitmask (`1 << int(self)`) for archetype presence masks. |
| `is_mobile_element` | `bool` | True if this role is a mobile genetic element (`TRANSPOSASE`, `INTEGRASE`). |
| `is_biosynthetic` | `bool` | True if this role represents active locus biosynthesis, modification, or transport. |

#### spec

```python
spec: RoleSpec
```

Return the immutable `RoleSpec` metadata for this role.

#### abbreviation

```python
abbreviation: str
```

Short display abbreviation (e.g. `'Wzx'`, `'GT'`).

#### abbr

```python
abbr: str
```

Alias for `abbreviation`.

#### category

```python
category: RoleCategory
```

Functional `RoleCategory` of this gene role.

#### description

```python
description: str
```

Human-readable biochemical description.

#### aliases

```python
aliases: tuple[str, ...]
```

Known gene symbol aliases for this role.

#### trusted\_prefixes

```python
trusted_prefixes: tuple[str, ...]
```

Trusted canonical gene symbol prefixes for Tier-1 classification.

#### bitmask

```python
bitmask: int
```

32-bit integer bitmask (`1 << int(self)`) for archetype presence masks.

#### is\_mobile\_element

```python
is_mobile_element: bool
```

True if this role is a mobile genetic element (`TRANSPOSASE`, `INTEGRASE`).

#### is\_biosynthetic

```python
is_biosynthetic: bool
```

True if this role represents active locus biosynthesis, modification, or transport.

#### from\_name

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

Resolve a role from an integer index, canonical name, abbreviation, or alias.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `key` | `str \| bytes \| int \| GeneRole` | Role identifier (`GeneRole`, `int`, `str`, or `bytes`). | *required* |

Returns:

| Name | Type | Description |
| --- | --- | --- |
| `GeneRole` | `GeneRole` | Resolved canonical role enum member. |

Raises:

| Type | Description |
| --- | --- |
| `KeyError` | If a string/bytes key does not match any known role name, abbreviation, or alias. |
| `ValueError` | If an integer index is out of range. |

#### resolve

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

Resolve a role identifier, falling back to `default` (or `GeneRole.UNKNOWN`) if not found.

#### names\_array

```python
names_array() -> ndarray[tuple[int], dtype[str_]]
```

Contiguous 1D NumPy string array of canonical role names.

#### abbreviations\_array

```python
abbreviations_array() -> ndarray[tuple[int], dtype[str_]]
```

Contiguous 1D NumPy string array of role abbreviations.

#### categories\_array

```python
categories_array() -> ndarray[tuple[int], dtype[str_]]
```

Contiguous 1D NumPy string array of role categories.

#### feature\_matrix

```python
feature_matrix() -> ndarray[tuple[int, int], dtype[float32]]
```

Return precomputed `(30, D)` float32 one-hot category feature matrix for embeddings.

#### label

```python
label(symbol: str | bytes | Sequence[str | bytes] | ndarray | None = None, description: str | bytes | Sequence[str | bytes] | ndarray | None = None) -> GeneRole | ndarray[tuple[int], dtype[int8]]
```

Assign gene role indices for a single gene or batch of genes using the 4-tier strategy.

1. Tier 1: Canonical trusted core symbol prefixes.
2. Tier 2: Informative product description regex.
3. Tier 3: Symbol regex and aliases fallback (with locus suffix stripping).
4. Tier 4: Gene identifier extraction from product description fallback.

Returns:

| Type | Description |
| --- | --- |
| `GeneRole \| ndarray[tuple[int], dtype[int8]]` | `GeneRole` if inputs are scalar, or `np.ndarray[int8]` if inputs are a sequence/array. |

---

## 1D CNN Role Classifier (`serogen.genes.cnn`)

## cnn

Classifying gene roles from amino acid sequences using a Multi-Scale 1D-CNN trained via compiled Numba AdamW backpropagation with dual (max + average) pooling.

Classes:

| Name | Description |
| --- | --- |
| `GeneRoleClassifier` | Classifies `GeneRole`s from amino acid sequences using a Multi-Scale 1D-CNN with Dual Pooling. |

### GeneRoleClassifier

Classifies `GeneRole`s from amino acid sequences using a Multi-Scale 1D-CNN with Dual Pooling.

Learns representations from variable-length sequence token arrays using an embedding layer, multi-scale 1D convolutions (e.g. receptive fields 5, 9, 13), ReLU activation, dual pooling (global max pooling + global average pooling) concatenated with normalized log-length and amino acid composition, and a dense classification layer. Optimization is performed via a parallel compiled Numba AdamW training kernel with exact gradient routing.

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `vocab_size` |  | Number of discrete tokens in sequence vocabulary (default 23: 22 AMINO tokens + 1 unknown/pad). |
| `embed_dim` |  | Dimensionality of token embedding vectors. |
| `num_filters` |  | Number of 1D convolutional feature channels across all kernel sizes. |
| `kernel_size` |  | Width of 1D convolution receptive field window (int), or tuple of multi-scale kernel sizes (e.g. `(5, 9, 13)`). |
| `learning_rate` |  | AdamW step size hyperparameter. |
| `epochs` |  | Number of complete training epochs over dataset. |
| `batch_size` |  | Mini-batch size for parallel AdamW gradient accumulation and updates. |
| `weight_decay` |  | Decoupled L2 weight decay coefficient applied to model parameters. |
| `random_state` |  | Optional seed for reproducible parameter initialization and sample shuffling. |
| `class_weight` |  | Optional `"balanced"` inverse-frequency class weighting or `None`. |

Methods:

| Name | Description |
| --- | --- |
| `fit` | Fit the 1D-CNN using parallel mini-batch AdamW optimization over ragged token sequences. |
| `transform` | Extract sequence representations from the specified network layer. |
| `decision_function` | Compute raw pre-softmax class logits `(n_samples, n_classes)` for each sequence in `X`. |
| `predict_proba` | Predict class probabilities `(n_samples, n_classes)` for each sequence in `X`. |
| `predict` | Predict most likely class label (e.g. `GeneRole` integer index) for each sequence in `X`. |
| `score` | Return classification accuracy on `(X, y)`. |
| `top_k_accuracy` | Compute Top-`k` classification accuracy on `(X, y)`. |
| `save` | Save model weights, classes, and hyperparameters to a compressed `.npz` archive. |
| `load` | Load model weights, classes, and hyperparameters from a compressed `.npz` archive. |
| `pretrained` | Load the packaged pre-trained `GeneRoleClassifier` from `serogen.data/model.npz`. |

#### is\_fitted

```python
is_fitted: bool
```

Return `True` if all model parameters have been fitted or loaded.

#### num\_classes

```python
num_classes: int
```

Number of target classes learned by the fitted model.

#### feature\_dim

```python
feature_dim: int
```

Dimensionality of the penultimate 1D-CNN + global composition feature vector.

#### fit

```python
fit(X: Genes | Sequences | Sequence[Any] | tuple[ndarray, ndarray], y: Sequence[int | GeneRole] | ndarray, sample_weight: Sequence[float] | ndarray | None = None, *, init_from: GeneRoleClassifier | None = None, backbone_lr_scale: float = 1.0) -> Self
```

Fit the 1D-CNN using parallel mini-batch AdamW optimization over ragged token sequences.

#### transform

```python
transform(X: Genes | Sequences | Sequence[Any] | tuple[ndarray, ndarray], *, layer: str = 'penultimate') -> ndarray[tuple[int, int], dtype[float32]]
```

Extract sequence representations from the specified network layer.

#### decision\_function

```python
decision_function(X: Genes | Sequences | Sequence[Any] | tuple[ndarray, ndarray]) -> ndarray[tuple[int, int], dtype[float32]]
```

Compute raw pre-softmax class logits `(n_samples, n_classes)` for each sequence in `X`.

#### predict\_proba

```python
predict_proba(X: Genes | Sequences | Sequence[Any] | tuple[ndarray, ndarray]) -> ndarray[tuple[int, int], dtype[float32]]
```

Predict class probabilities `(n_samples, n_classes)` for each sequence in `X`.

#### predict

```python
predict(X: Genes | Sequences | Sequence[Any] | tuple[ndarray, ndarray], min_confidence: float = 0.0, unknown_label: int | None = None) -> ndarray[tuple[int], dtype[Any]]
```

Predict most likely class label (e.g. `GeneRole` integer index) for each sequence in `X`.

#### score

```python
score(X: Genes | Sequences | Sequence[Any] | tuple[ndarray, ndarray], y: Sequence[int | GeneRole] | ndarray) -> float
```

Return classification accuracy on `(X, y)`.

#### top\_k\_accuracy

```python
top_k_accuracy(X: Genes | Sequences | Sequence[Any] | tuple[ndarray, ndarray], y: Sequence[int | GeneRole] | ndarray, k: int = 3) -> float
```

Compute Top-`k` classification accuracy on `(X, y)`.

#### save

```python
save(path: Path | str) -> None
```

Save model weights, classes, and hyperparameters to a compressed `.npz` archive.

#### load

```python
load(path: Path | str) -> Self
```

Load model weights, classes, and hyperparameters from a compressed `.npz` archive.

#### pretrained

```python
pretrained() -> Self
```

Load the packaged pre-trained `GeneRoleClassifier` from `serogen.data/model.npz`.
