> ## 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.

# Gene signatures

> Score gene signatures on M-Optimus predictions, then save the scores and the signature definitions for reuse.

A gene signature is a named group of genes reduced to one score per tile — for example, the mean predicted expression of a T-cell marker set. This guide scores signatures on [M-Optimus](https://docs.bioptimus.com/documentation/models/m-optimus.md) predictions, stores the per-tile scores beside the predictions, and stores the signature definitions in the [cohort](https://docs.bioptimus.com/guides/workflows/cohort.md) manifest so an analysis can be reloaded and reproduced later.

> [!NOTE]
>
> A score is a per-tile aggregate of predicted expression, not a statistical test. No p-values are computed and no control-gene baseline is subtracted.

## 1. Define signatures

A `GeneSet` names the genes; a `GeneSignature` adds how to reduce them to a score. Genes are identified by Ensembl gene ID, the same identifiers as the [prediction panel](https://docs.bioptimus.com/guides/workflows/spatial-transcriptomics.md#5-visualize).

```python theme={null}
from bioptimus.data.omics.gene_set import GeneSet
from bioptimus.inference.gene_signature import GeneSignature, GeneSignatureCollection
from bioptimus.inference.reducers import Reduce

CD3E, CD8A = "ENSG00000198851", "ENSG00000153563"
EPCAM, COL1A1 = "ENSG00000119888", "ENSG00000108821"

t_cell = GeneSet("t_cell", [CD3E, CD8A], id_type="ensembl")
epithelium = GeneSet("epithelium", [EPCAM], id_type="ensembl")
stroma = GeneSet("stroma", [COL1A1], id_type="ensembl")

sigs = GeneSignatureCollection.from_signatures([
    GeneSignature(t_cell, method=Reduce.MEAN),
    # Two-sided: up-genes minus down-genes (the default combine mode).
    GeneSignature(
        epithelium, method=Reduce.MEAN, down_gene_set=stroma, name="tumor_vs_stroma"
    ),
])
```

## 2. Score a prediction store

Load the predictions that M-Optimus wrote (see [Spatial transcriptomics](https://docs.bioptimus.com/guides/workflows/spatial-transcriptomics.md#4-inspect-the-output)) and score them. `score` returns a `GeneSignatureScores` with one row per tile and one column per signature; nothing is written yet.

```python theme={null}
from bioptimus.io.outputs import load_output

store_path = "/data/output/tcga_coad.zarr"
data = load_output(store_path)

res = sigs.score(data["outputs"], data["gene_names"], coords=data["coords"])
res.scores.head()   # DataFrame: columns "t_cell", "tumor_vs_stroma"
```

Plot a signature over the slide with the same tile coordinates:

```python theme={null}
from bioptimus import utils

utils.plot_spatial_gene(
    res.scores["t_cell"].to_numpy(), data["coords"], title="T-cell signature"
)
```

> [!TIP]
>
> Gene sets with HGNC symbols (the default `id_type="symbol"`) are matched to the Ensembl panel by passing a symbol-to-Ensembl `mapping` to `score(...)`.

## 3. Save the scores and the definitions

The two halves are stored separately (`cohort` is the cohort you ran inference with; see [Cohorts](https://docs.bioptimus.com/guides/workflows/cohort.md)). The **scores** are per-tile arrays, so they go into the prediction store, row-aligned with its tiles. The **definitions** are small and describe the analysis, so they go into the cohort manifest under `extras`.

```python theme={null}
res.save(store_path)                                  # per-tile scores -> prediction store

cohort.extras["gene_signatures"] = sigs.to_spec()     # definitions -> cohort manifest
cohort.save("/data/output/cohort.yaml")
```

`save` raises a `BIO-CFG-001` error if the number of scores doesn't match the store's tile count. If the store already holds signature scores, `on_conflict` controls what happens:

| `on_conflict` | Behavior |
| - | - |
| `OnConflict.MERGE` (default) | Replaces same-named signatures and adds new ones. |
| `OnConflict.OVERWRITE` | Replaces all stored signature scores. |
| `OnConflict.ERROR` | Raises if signature scores are already present. |

```python theme={null}
from bioptimus.io.outputs import OnConflict

res.save(store_path, on_conflict=OnConflict.OVERWRITE)
```

> [!NOTE]
>
> Zarr and HDF5 stores are appended in place. NPZ has no append API, so `save` rewrites the whole file and logs a warning; prefer Zarr (the default) for large slides.

## 4. Reload

In a later session, read the scores from the store and rebuild the signatures from the cohort manifest.

```python theme={null}
from bioptimus.data.cohort import Cohort
from bioptimus.inference.gene_signature import GeneSignatureCollection
from bioptimus.io.outputs import load_output

data = load_output(store_path)
scores = data["gene_signature_scores"]    # (n_tiles, n_signatures)
names = data["gene_signature_names"]      # ["t_cell", "tumor_vs_stroma"]

cohort = Cohort.load("/data/output/cohort.yaml")
sigs = GeneSignatureCollection.from_spec(cohort.extras["gene_signatures"])
```

The stored definition lists every gene, so the rebuilt collection scores new predictions exactly as the original did. Because `extras` is plain YAML, the definitions are also readable and diffable in the manifest.

## 5. Apply across a cohort

Score each slide's predictions with the same collection and save them into that slide's store:

```python theme={null}
from bioptimus.inference.schemas import InferenceMode

for wsi_id in cohort.wsi_ids:
    output = cohort.get_wsi(wsi_id).outputs.get("m-optimus")
    path = output.get_stage_path(InferenceMode.PREDICTION) if output else None
    if path is None:
        continue   # not processed yet
    data = load_output(path)
    sigs.score(data["outputs"], data["gene_names"]).save(path)
```

`get_stage_path` resolves paths relative to the manifest directory, so this works wherever the cohort is loaded from.

> [!TIP]
>
> `cohort.extras` is a general place for analysis definitions. Namespace each analysis under its own key (here `"gene_signatures"`) so analyses don't overwrite each other.


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