> ## 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.data.omics.gene_set

Gene sets over M-Optimus prediction panels.

Provides [`GeneSet`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#geneset) — a named, immutable group of gene identifiers — and the shared [`select_genes`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#select_genes) helper for subsetting a prediction matrix to a set's genes.

M-Optimus emits one predicted expression value per gene of a fixed panel (`gene_names`). A [`GeneSet`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#geneset) names a subset of those genes (for example a hypoxia signature) so callers can slice predictions down to a biologically meaningful group.

Gene sets are usually authored in gene **symbols** while prediction panels are often **Ensembl**-indexed. Pass a `mapping` (symbol -> Ensembl id) to [`GeneSet.resolve`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#resolve), [`GeneSet.coverage`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#coverage), or [`select_genes`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#select_genes) to bridge the two id spaces. Genes that do not resolve against the panel are dropped with a structured warning; a set that resolves to no genes at all raises `BioptimusValueError` tagged `BIO-GENE-001`.

Two kinds of identifier collision are handled keep-first + warn rather than silently: a many-to-one `mapping` (two set genes mapping to one panel column) drops the later gene so the column is not double-counted (`gene_set_duplicate_columns`), and a panel that lists an id more than once binds to its first column rather than the last (`panel_duplicate_genes`).

***

#### GeneIdType

Supported gene identifier spaces for a [`GeneSet`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#geneset).

## GeneSet

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

A named, immutable group of gene identifiers.

Duplicate genes are removed on construction while preserving first-seen order, so the resolved column order is deterministic. A set must contain at least one gene.

**name**

Human-readable set name, for example `"hypoxia"`.

**genes**

The gene identifiers in the set. Duplicates are removed.

**id\_type**

The identifier space of `genes` — `"symbol"` (default) or `"ensembl"`.

**description**

Optional free-text description of the set.

**Attributes**:

* `name` - The set name.
* `genes` - The de-duplicated gene identifiers in first-seen order.
* `id_type` - The identifier space of `genes`.
* `description` - Optional description.

***

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

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

Returns the number of unique genes in the set.

***

#### from\_gene\_list

```python theme={null}
@classmethod
def from_gene_list(cls,
                   path: str | Path,
                   *,
                   name: str,
                   gene_col: str = "gene_id",
                   id_type: GeneIdType = "ensembl",
                   description: str | None = None) -> GeneSet
```

Builds a set from a flat single-column gene-list file.

Reads a CSV/TSV holding one gene identifier per row under a single column (the layout of predefined panel/gene-list files). The column is matched tolerantly against common spellings (for example `"Ensembl ID"`) when the exact name is absent.

**path**

Path to the CSV/TSV file.

**name**

The name to give the resulting set.

**gene\_col**

Column holding the gene identifiers.

**id\_type**

The identifier space of the genes. Defaults to `"ensembl"` since flat gene lists are typically Ensembl ids.

**description**

Optional free-text description of the set.

**Returns**:

A [`GeneSet`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#geneset) containing the file's gene identifiers.

**Raises**:

* `BioptimusValueError` - If the gene column is missing, the file is missing/unreadable/malformed, or the list is empty, tagged `BIO-CFG-001`.

***

#### to\_spec

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

Returns a JSON/YAML-safe dict describing this gene set.

Stores the full (de-duplicated) gene list plus id space and description, so [`from_spec`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#from_spec) rebuilds an identical set. Used to persist gene-set definitions (for example in a cohort manifest).

**Returns**:

A dict with `name`, `genes`, `id_type`, and `description`.

***

#### from\_spec

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

Rebuilds a [`GeneSet`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#geneset) from a [`to_spec`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#to_spec) dict.

**spec**

A mapping with `name` and `genes` and optional `id_type` / `description` (as produced by [`to_spec`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#to_spec)).

**Returns**:

The reconstructed gene set.

**Raises**:

* `BioptimusValueError` - If `name` or `genes` is missing, or `id_type` is not a supported identifier space, tagged `BIO-CFG-001`.

***

#### coverage

```python theme={null}
def coverage(gene_names: Sequence[str],
             *,
             mapping: Mapping[str, str] | None = None
             ) -> tuple[int, int, list[str]]
```

Reports how many of the set's genes are present in a panel.

This is a pure query with no side effects (it does not warn or raise), so callers can inspect coverage before deciding how to proceed.

**gene\_names**

The prediction panel gene identifiers, in panel order.

**mapping**

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

**Returns**:

A `(hit, total, missing)` tuple where `hit` is the number of set
genes found in the panel, `total` is the set size, and `missing`
lists the set genes (as authored) not found in the panel.

***

#### resolve

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

Resolves the set's genes to column indices into a prediction panel.

Genes absent from the panel are dropped with a structured warning. A set that resolves to no genes at all raises, since the caller almost certainly has an id-space mismatch (for example a symbol set against an Ensembl panel without a `mapping`).

**gene\_names**

The prediction panel gene identifiers, in panel order.

**mapping**

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

**Returns**:

An `int` array of column indices into `gene_names`, in the set's
gene order, for the genes that resolved.

**Raises**:

* `BioptimusValueError` - If none of the set's genes resolve against the panel, tagged `BIO-GENE-001`.

***

#### resolve\_with\_mask

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

Resolves genes to panel indices and reports which genes survived.

Like [`resolve`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#resolve), but also returns a boolean mask over the set's (de-duplicated) `genes` marking which ones resolved. Callers that carry per-gene data aligned to `genes` (for example signature weights) use the mask to drop the same positions the resolution dropped, keeping the two aligned.

**gene\_names**

The prediction panel gene identifiers, in panel order.

**mapping**

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

**Returns**:

A `(indices, kept_mask)` tuple where `indices` are the resolved
column indices (in set order) and `kept_mask` is a boolean array
of length `len(self)` that is `True` at each gene that resolved.

**Raises**:

* `BioptimusValueError` - If none of the set's genes resolve against the panel, tagged `BIO-GENE-001`.

***

#### select\_genes

```python theme={null}
def select_genes(
        values: np.ndarray,
        gene_names: Sequence[str],
        gene_set: GeneSet,
        *,
        mapping: Mapping[str, str] | None = None
) -> tuple[np.ndarray, list[str]]
```

Subsets a prediction matrix to a gene set's resolved genes.

**values**

An `(N, G)` array of predictions, where `G` matches the length of `gene_names`.

**gene\_names**

The prediction panel gene identifiers, in panel order.

**gene\_set**

The gene set to select.

**mapping**

Optional symbol-to-panel-id mapping forwarded to [`GeneSet.resolve`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#resolve).

**Returns**:

A `(selected, names)` tuple where `selected` is an `(N, k)` array
of the resolved columns (in the set's gene order) and `names` are the
corresponding panel identifiers.

**Raises**:

* `BioptimusValueError` - If values does not match the panel, tagged `BIO-CFG-001`, or if none of the set's genes resolve, tagged `BIO-GENE-001`.

## GeneSetCollection

```python theme={null}
class GeneSetCollection(members: Mapping[str, GeneSet | Iterable[str]],
                        *,
                        id_type: GeneIdType = 'symbol')
```

A named group of [`GeneSet`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#geneset) objects keyed by set name.

Behaves as a read-only `Mapping[str, GeneSet]` (supports `coll["name"]`, iteration over names, `len`, `in`, `.values()`, `.items()`), and adds batch operations that resolve every member against a panel in one pass.

**members**

A mapping of set name to either a [`GeneSet`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#geneset) or a plain iterable of gene identifiers. Plain iterables are wrapped in a [`GeneSet`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#geneset) using the mapping key as the name.

**id\_type**

The identifier space used for members supplied as plain iterables. Ignored for members that are already [`GeneSet`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#geneset) objects.

**Raises**:

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

***

#### from\_sets

```python theme={null}
@classmethod
def from_sets(cls, gene_sets: Iterable[GeneSet]) -> GeneSetCollection
```

Groups existing gene sets into a collection keyed by their names.

**gene\_sets**

The gene sets to group. Names must be unique.

**Returns**:

A collection containing the given sets.

**Raises**:

* `BioptimusValueError` - If two sets share the same 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 member spec, so a collection whose key differs from the member's name (or that holds same-named members under distinct keys) rebuilds faithfully.

**Returns**:

A dict with a `sets` list of `{"key", "spec"}` entries (see
[`GeneSet.to_spec`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#to_spec)), in member order.

***

#### from\_spec

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

Rebuilds a [`GeneSetCollection`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#genesetcollection) from a [`to_spec`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#to_spec) dict.

**spec**

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

**Returns**:

The reconstructed collection, preserving member keys and order.

**Raises**:

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

***

#### from\_gmt

```python theme={null}
@classmethod
def from_gmt(cls,
             path: str | Path,
             *,
             id_type: GeneIdType = "symbol") -> GeneSetCollection
```

Builds a collection from a single GMT file (for example MSigDB).

**path**

Path to the `.gmt` file. Each line is `<set name>\t<description>\t<gene>\t<gene>...`.

**id\_type**

The identifier space of the genes in the file.

**Returns**:

A collection with one [`GeneSet`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#geneset) per GMT line.

**Raises**:

* `BioptimusValueError` - If two GMT lines share a set name, tagged `BIO-CFG-001`.

***

#### from\_records

```python theme={null}
@classmethod
def from_records(cls,
                 source: str | Path | pd.DataFrame,
                 *,
                 set_col: str,
                 gene_col: str,
                 id_type: GeneIdType = "symbol") -> GeneSetCollection
```

Builds a collection from a long-form `(set, gene)` table.

Each row assigns one gene to one set, so a set spans multiple rows (the layout of MSigDB-style CSVs and the decoupler "net" format). Rows are grouped by `set_col` and, within a set, gene order follows first appearance.

**source**

A path to a CSV/TSV file (separator inferred from the extension) or an in-memory `pandas.DataFrame`.

**set\_col**

Column holding the set name.

**gene\_col**

Column holding the gene identifier.

**id\_type**

The identifier space of the genes.

**Returns**:

A collection with one [`GeneSet`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#geneset) per distinct `set_col`
value.

**Raises**:

* `BioptimusValueError` - If a required column is missing, tagged `BIO-CFG-001`.

***

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

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

Returns the member set with the given name.

***

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

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

Iterates over member set names.

***

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

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

Returns the number of member sets.

***

#### sets

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

Returns the member sets as a list of [`GeneSet`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#geneset) objects.

***

#### names

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

Returns the member set names in insertion order.

***

#### coverage

```python theme={null}
def coverage(gene_names: Sequence[str],
             *,
             mapping: Mapping[str, str] | None = None) -> pd.DataFrame
```

Reports panel coverage for every member set in one table.

The panel lookup is built once and shared across all member sets, so this is cheaper than calling [`GeneSet.coverage`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#coverage) per set.

**gene\_names**

The prediction panel gene identifiers, in panel order.

**mapping**

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

**Returns**:

A DataFrame indexed by set name with `hit`, `total`, and
`missing` (a list of the unresolved genes) columns.

***

#### resolve\_columns

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

Resolves the union of every member set's genes to panel columns.

Returns the sorted, de-duplicated column indices spanning all member sets. A caller that reads predictions lazily (for example `bioptimus.data.cohort.Cohort.select_genes`) uses this to read only the needed columns instead of the full panel, then re-selects per set with [`select`](https://docs.bioptimus.com/sdk-reference/data/omics/gene_set#select) on the reduced matrix.

**gene\_names**

The prediction panel gene identifiers, in panel order.

**mapping**

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

**Returns**:

The sorted, unique panel column indices covered by any member set.

**Raises**:

* `BioptimusValueError` - If any member set resolves to no genes, tagged `BIO-GENE-001`.

***

#### select

```python theme={null}
def select(
    values: np.ndarray,
    gene_names: Sequence[str],
    *,
    mapping: Mapping[str, str] | None = None
) -> dict[str, tuple[np.ndarray, list[str]]]
```

Subsets a prediction matrix to each member set's resolved genes.

The panel lookup is built once and shared across all member sets.

**values**

An `(N, G)` array of predictions, where `G` matches the length of `gene_names`.

**gene\_names**

The prediction panel gene identifiers, in panel order.

**mapping**

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

**Returns**:

A mapping of set name to a `(selected, names)` tuple, where
`selected` is an `(N, k)` array and `names` are the resolved
panel identifiers.

**Raises**:

* `BioptimusValueError` - If values does not match the panel, tagged `BIO-CFG-001`, or if any member set resolves to no genes, tagged `BIO-GENE-001`.


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