> ## Documentation Index
> Fetch the complete documentation index at: https://docs.bioptimus.com/llms.txt
> Use this file to discover all available pages before exploring further.

# bioptimus.inference.gene_signature

Gene signature scoring — reduce M-Optimus predictions to per-spot scores.

A [`GeneSignature`](https://docs.bioptimus.com/sdk-reference/inference/gene_signature#genesignature) pairs a data-layer `GeneSet` (*which genes*) with a scoring recipe (*how to reduce them to one number per spot*). This lives in the inference layer because scoring reuses the normalization transforms in `bioptimus.preprocess.omics.transforms` and sits beside the other prediction reducers (`Pseudobulk`, `slide_reduce`). Gene sets stay data-layer and never gain a `score` method; a signature *wraps* a gene set, so the dependency only ever points inference → data.

Built-in scoring is a normalize-then-reduce recipe. The normalize axis reuses the shared omics transforms directly (an `OmicsPreprocessor`: `IdentityTransform`, `Log1pTransform`, `SelfZScoreNormaliser`, `TotalCountNormaliser` for CPM/CP10k total-count normalization). The reduce axis is a `Reducer` (built-ins `Mean`, `Sum`, `WeightedSum`, `Min`, `Max`) that collapses the resolved genes. A [`GeneSignatureScoringRecipe`](https://docs.bioptimus.com/sdk-reference/inference/gene_signature#genesignaturescoringrecipe) pairs one of each. Users extend the reduce axis by subclassing `Reducer` (fixed linear combinations should subclass `LinearReducer` so the engine can batch them into one matmul), and the normalize axis with any `OmicsPreprocessor`.

## GeneSignatureDownCombine

```python theme={null}
class GeneSignatureDownCombine(enum.Enum)
```

How a two-sided signature combines its up-side and down-side scores.

Only meaningful when a [`GeneSignature`](https://docs.bioptimus.com/sdk-reference/inference/gene_signature#genesignature) carries a `down_gene_set`. `DIFFERENCE` (the default) is `up - down`; `RATIO` is `up / down`; `LOG2_RATIO` is `log2(up / down)` (the symmetric, better-behaved form). `RATIO` and `LOG2_RATIO` assume non-negative side scores (pair them with a non-negative normalizer such as CP10k or Log1p); a negative side score makes the ratio ill-defined and raises at score time.

## GeneSignatureScoringRecipe

```python theme={null}
@dataclass(frozen=True)
class GeneSignatureScoringRecipe()
```

A normalize-then-reduce recipe: the two orthogonal axes of scoring.

Pairs an `OmicsPreprocessor` normalizer (applied to the whole matrix) with a `Reducer` (collapsing the resolved genes). The normalize axis reuses the shared omics transforms directly (`Log1pTransform`, `TotalCountNormaliser` for CPM/CP10k total-count normalization, `SelfZScoreNormaliser`, `IdentityTransform`), so any normalization pairs with any reduction without a combined name.

**Attributes**:

* `normalize` - The omics transform applied before reduction. Defaults to `IdentityTransform` (no normalization).
* `reduce` - The reducer that collapses the resolved genes. Defaults to `Mean`.

***

#### GeneSignatureMethod

A signature's scoring recipe as accepted from callers: an explicit [`GeneSignatureScoringRecipe`](https://docs.bioptimus.com/sdk-reference/inference/gene_signature#genesignaturescoringrecipe), or a bare `Reducer` (paired with an `IdentityTransform`). Strings are not accepted; a bare reducer coerces to a [`GeneSignatureScoringRecipe`](https://docs.bioptimus.com/sdk-reference/inference/gene_signature#genesignaturescoringrecipe) on construction.

## GeneSignatureScores

```python theme={null}
@dataclass(frozen=True)
class GeneSignatureScores()
```

Per-spot signature scores, ready for tables and spatial plots.

A score is a per-spot aggregate, not a statistical test: the signature genes' predicted expression is normalized and then reduced (the mean by default) as set by each signature's [`GeneSignatureScoringRecipe`](https://docs.bioptimus.com/sdk-reference/inference/gene_signature#genesignaturescoringrecipe). No p-values are computed and no control-gene baseline is subtracted.

**Attributes**:

* `scores` - A DataFrame with one row per spot and one column per signature (column order matches the scored signatures). Drops straight into `plot_spatial_gene` and `.corr()`.
* `coords` - Optional `(N, 2)` array of spot coordinates, carried through unchanged for spatial visualization. `None` when not supplied; coordinates are never an input to scoring.

***

#### save

```python theme={null}
def save(path: str | Path,
         *,
         on_conflict: OnConflict = OnConflict.MERGE) -> None
```

Writes these per-tile scores into the prediction store at `path`.

Persists the score matrix as a `gene_signature_scores` array (with a `gene_signature_names` label array) row-aligned with the store's `outputs` / `coords`, so each tile keeps its score beside its prediction. `score()` and `save()` are deliberately separate: compute in memory first, then persist explicitly.

**path**

Path to the existing prediction store these scores were computed from (Zarr/HDF5/NPZ).

**on\_conflict**

Policy when the store already has signature scores — merge columns by name (default), overwrite, or raise. See `OnConflict`.

**Raises**:

* `BioptimusValueError` - If the score rows do not match the store's tile count, or a conflict occurs under [`OnConflict.ERROR`](https://docs.bioptimus.com/sdk-reference/io/outputs), tagged `BIO-CFG-001`.

## GeneSignature

```python theme={null}
@dataclass(frozen=True)
class GeneSignature()
```

A gene set plus a scoring recipe (composition, not subclassing).

Wraps a data-layer `GeneSet` and adds the reduce step that turns the set's per-gene predictions into one score per spot. `weights` are only valid for a [`WeightedSum`](https://docs.bioptimus.com/sdk-reference/inference/reducers#weightedsum) reducer and must align to the set's de-duplicated genes.

**Attributes**:

* `gene_set` - The genes to score (the "up" side of a two-sided signature).
* `method` - The scoring recipe: a [`GeneSignatureScoringRecipe`](https://docs.bioptimus.com/sdk-reference/inference/gene_signature#genesignaturescoringrecipe), or a bare `Reducer` (paired with an `IdentityTransform`). Coerced to a [`GeneSignatureScoringRecipe`](https://docs.bioptimus.com/sdk-reference/inference/gene_signature#genesignaturescoringrecipe) on construction.
* `weights` - Per-gene weights for a [`WeightedSum`](https://docs.bioptimus.com/sdk-reference/inference/reducers#weightedsum) reducer, aligned to `gene_set.genes`. `None` for every other reducer.
* `down_gene_set` - Optional "down" side. When set, the signature is two-sided and its score combines the up and down sides per `combine`. `None` for a one-sided signature.
* `down_weights` - Per-gene weights for the down side under a [`WeightedSum`](https://docs.bioptimus.com/sdk-reference/inference/reducers#weightedsum) reducer, aligned to `down_gene_set.genes`. `None` otherwise.
* `combine` - How the up and down sides combine, applied only when `down_gene_set` is set. Defaults to [`GeneSignatureDownCombine.DIFFERENCE`](https://docs.bioptimus.com/sdk-reference/inference/gene_signature).
* `name` - The signature name. Defaults to the gene set's name.

***

#### effective\_name

```python theme={null}
@property
def effective_name() -> str
```

Returns the signature name, defaulting to the gene set's name.

***

#### score

```python theme={null}
def score(preds: np.ndarray,
          panel: Sequence[str],
          *,
          mapping: Mapping[str, str] | None = None) -> np.ndarray
```

Scores this signature over a prediction matrix.

**preds**

An `(N_spots, G)` prediction matrix aligned to `panel`.

**panel**

The prediction panel gene identifiers, in panel order.

**mapping**

Optional symbol-to-panel-id mapping applied to each gene.

**Returns**:

A `(N_spots,)` array of per-spot scores.

**Raises**:

* `BioptimusValueError` - If `preds` does not match the panel (`BIO-CFG-001`), none of the genes resolve (`BIO-GENE-001`), a custom scorer returns the wrong shape (`BIO-CFG-001`), or a `RATIO`/`LOG2_RATIO` side score is negative (`BIO-CFG-001`).

***

#### to\_spec

```python theme={null}
def to_spec() -> dict[str, Any]
```

Returns a JSON/YAML-safe dict describing this signature.

Captures the up/down gene sets, the recipe (normalizer + reducer via their own specs), per-side weights, and the combine mode, so [`from_spec`](https://docs.bioptimus.com/sdk-reference/inference/gene_signature#from_spec) rebuilds an equivalent signature.

**Returns**:

A dict with `name`, `gene_set`, `down_gene_set`, `normalize`,
`reduce`, `weights`, `down_weights`, and `combine`.

***

#### from\_spec

```python theme={null}
@classmethod
def from_spec(cls, spec: dict[str, Any]) -> GeneSignature
```

Rebuilds a [`GeneSignature`](https://docs.bioptimus.com/sdk-reference/inference/gene_signature#genesignature) from a [`to_spec`](https://docs.bioptimus.com/sdk-reference/inference/gene_signature#to_spec) dict.

**spec**

A mapping produced by [`to_spec`](https://docs.bioptimus.com/sdk-reference/inference/gene_signature#to_spec).

**Returns**:

The reconstructed signature.

**Raises**:

* `BioptimusValueError` - If a recipe piece is not registered, the `combine` name is unknown (`BIO-CFG-001`), or the weight/combine combination is invalid (surfaced by construction).

## GeneSignatureCollection

```python theme={null}
class GeneSignatureCollection(members: Mapping[str, GeneSignature])
```

A named group of [`GeneSignature`](https://docs.bioptimus.com/sdk-reference/inference/gene_signature#genesignature) objects keyed by signature name.

Mirrors `GeneSetCollection`: behaves as a read-only `Mapping[str, GeneSignature]` and owns [`score`](https://docs.bioptimus.com/sdk-reference/inference/gene_signature#score), which the data-layer collection deliberately lacks (scoring is inference-layer).

**members**

A mapping of signature name to [`GeneSignature`](https://docs.bioptimus.com/sdk-reference/inference/gene_signature#genesignature).

**Raises**:

* `BioptimusValueError` - If `members` is empty, tagged `BIO-CFG-001`.

***

#### from\_signatures

```python theme={null}
@classmethod
def from_signatures(
        cls, signatures: Iterable[GeneSignature]) -> GeneSignatureCollection
```

Groups signatures into a collection keyed by their effective names.

**signatures**

The signatures to group. Effective names must be unique.

**Returns**:

A collection containing the given signatures.

**Raises**:

* `BioptimusValueError` - If two signatures share a name, tagged `BIO-CFG-001`.

***

#### to\_spec

```python theme={null}
def to_spec() -> dict[str, Any]
```

Returns a JSON/YAML-safe dict describing this collection.

Each member is stored with its mapping key alongside the signature spec, so a collection whose key differs from the signature's effective name (or that holds same-named signatures under distinct keys) rebuilds faithfully.

**Returns**:

A dict with a `signatures` list of `{"key", "spec"}` entries (see
[`GeneSignature.to_spec`](https://docs.bioptimus.com/sdk-reference/inference/gene_signature#to_spec)), in member order.

***

#### from\_spec

```python theme={null}
@classmethod
def from_spec(cls, spec: dict[str, Any]) -> GeneSignatureCollection
```

Rebuilds a [`GeneSignatureCollection`](https://docs.bioptimus.com/sdk-reference/inference/gene_signature#genesignaturecollection) from a [`to_spec`](https://docs.bioptimus.com/sdk-reference/inference/gene_signature#to_spec) dict.

**spec**

A mapping with a `signatures` list of `{"key", "spec"}` entries.

**Returns**:

The reconstructed collection, preserving member keys and order.

**Raises**:

* `BioptimusValueError` - If `signatures` is missing or an entry lacks `key` or `spec`, tagged `BIO-CFG-001`.

***

#### from\_collection

```python theme={null}
@classmethod
def from_collection(
    cls,
    collection: GeneSetCollection,
    *,
    method: GeneSignatureMethod | Mapping[str, GeneSignatureMethod]
    | None = None,
    weights: Mapping[str, Sequence[float]] | None = None,
    down: Mapping[str, GeneSet] | None = None,
    combine: GeneSignatureDownCombine
    | Mapping[str,
              GeneSignatureDownCombine] = GeneSignatureDownCombine.DIFFERENCE
) -> GeneSignatureCollection
```

Packs a gene-set collection into signatures (the bridge).

**collection**

The gene-set collection to wrap, one signature per set.

**method**

A single recipe/reducer applied to every set, or a per-set mapping of set name to recipe. Sets absent from a mapping (or when `method` is `None`) use a default [`GeneSignatureScoringRecipe`](https://docs.bioptimus.com/sdk-reference/inference/gene_signature#genesignaturescoringrecipe) (`IdentityTransform`

* [`Mean`](https://docs.bioptimus.com/sdk-reference/inference/reducers#mean)).

- `weights` - Optional per-set weights (set name to weight sequence), forwarded to the matching signatures.
- `down` - Optional per-set down gene sets (set name to [`GeneSet`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#geneset)), making the matching signatures two-sided.
- `combine` - A single combine mode applied to every two-sided set, or a per-set mapping of set name to [`GeneSignatureDownCombine`](https://docs.bioptimus.com/sdk-reference/inference/gene_signature#genesignaturedowncombine).

**Returns**:

A collection with one [`GeneSignature`](https://docs.bioptimus.com/sdk-reference/inference/gene_signature#genesignature) per member set.

***

#### \_\_getitem\_\_

```python theme={null}
def __getitem__(name: str) -> GeneSignature
```

Returns the member signature with the given name.

***

#### \_\_iter\_\_

```python theme={null}
def __iter__() -> Iterator[str]
```

Iterates over member signature names.

***

#### \_\_len\_\_

```python theme={null}
def __len__() -> int
```

Returns the number of member signatures.

***

#### signatures

```python theme={null}
@property
def signatures() -> list[GeneSignature]
```

Returns the member signatures as a list.

***

#### names

```python theme={null}
@property
def names() -> list[str]
```

Returns the member signature names in insertion order.

***

#### score

```python theme={null}
def score(preds: np.ndarray,
          panel: Sequence[str],
          *,
          mapping: Mapping[str, str] | None = None,
          coords: np.ndarray | None = None) -> GeneSignatureScores
```

Scores every member signature into a labeled [`GeneSignatureScores`](https://docs.bioptimus.com/sdk-reference/inference/gene_signature#genesignaturescores).

**preds**

An `(N_spots, G)` prediction matrix aligned to `panel`.

**panel**

The prediction panel gene identifiers, in panel order.

**mapping**

Optional symbol-to-panel-id mapping applied to each gene.

**coords**

Optional `(N_spots, 2)` coordinates carried onto the result for spatial plotting.

**Returns**:

A [`GeneSignatureScores`](https://docs.bioptimus.com/sdk-reference/inference/gene_signature#genesignaturescores) with one column per member signature.

**Raises**:

* `BioptimusValueError` - On a panel/shape mismatch, a signature resolving to no genes, a misbehaving custom scorer, a negative `RATIO`/`LOG2_RATIO` side score, or a `coords` length mismatch.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.