# graph { #tvbo.ontology.graph }

`ontology.graph`

# Graph-based representation of the ontology.

This module contains functions for representing ontology-based structures as graphs, and various utilities for manipulating and visualizing these graphs.

## Functions:

- [`owl2networkx`](#owl2networkx): Convert an ontology object to a NetworkX graph.
- [`nx2mermaid`](#nx2mermaid): Convert a NetworkX graph to a Mermaid representation.
- [`create_graph_from_dataframe`](#create_graph_from_dataframe): Construct a graph from a pandas DataFrame representing ontology.
- [`get_color_mapping`](#get_color_mapping): Map nodes of a graph to distinct colors based on a node attribute.
- [`get_node_colors`](#get_node_colors): Retrieve the colors associated with nodes in a graph.

## Functions

| Name | Description |
| --- | --- |
| [adjust_positions](#tvbo.ontology.graph.adjust_positions) | Nudge node positions apart or together along the chosen axes. |
| [edge_exists](#tvbo.ontology.graph.edge_exists) | Check if an edge with the given type exists between source and target in a MultiDiGraph. |
| [get_color_mapping](#tvbo.ontology.graph.get_color_mapping) | Map nodes of a graph to distinct colors based on a node attribute. |
| [hierarchy_graph](#tvbo.ontology.graph.hierarchy_graph) | Extract the `is_a` hierarchy of a graph into a new multigraph. |
| [labels_as_symbols](#tvbo.ontology.graph.labels_as_symbols) | Map graph nodes to LaTeX-rendered symbol labels. |
| [model2graph](#tvbo.ontology.graph.model2graph) | Build a dependency graph of a model's dynamics components. |
| [nx2mermaid](#tvbo.ontology.graph.nx2mermaid) | Convert a NetworkX graph to a Mermaid representation. |
| [onto2graph](#tvbo.ontology.graph.onto2graph) | Convert an ontology into a NetworkX directed graph. |
| [owl2nx_digraph](#tvbo.ontology.graph.owl2nx_digraph) | Convert an ontology into a NetworkX directed graph. |
| [subset2graph](#tvbo.ontology.graph.subset2graph) | Build a directed multigraph from a subset of ontology classes. |

### adjust_positions { #tvbo.ontology.graph.adjust_positions }

```python
ontology.graph.adjust_positions(
    pos,
    threshold_percent=10,
    direction='xy',
    mode='outward',
)
```

Nudge node positions apart or together along the chosen axes.

Compares every pair of points and, where their separation along an axis is below (outward mode) or above (inward mode) a threshold expressed as a percentage of the layout span, shifts the two points relative to each other to enforce the spacing.

#### Parameters {.doc-section .doc-section-parameters}

| Name              | Type                    | Description                                                                                 | Default     |
|-------------------|-------------------------|---------------------------------------------------------------------------------------------|-------------|
| pos               | dict\[Any, np.ndarray\] | Mapping from node to its 2-D position array.                                                | _required_  |
| threshold_percent | int                     | Target separation as a percentage of the total span along each considered axis.             | `10`        |
| direction         | str                     | Axes to adjust; include `"x"` and/or `"y"` (e.g. `"xy"`).                                   | `'xy'`      |
| mode              | str                     | `"outward"` to push points apart when too close, otherwise pull them together when too far. | `'outward'` |

#### Returns {.doc-section .doc-section-returns}

| Name   | Type                    | Description                                                      |
|--------|-------------------------|------------------------------------------------------------------|
|        | dict\[Any, np.ndarray\] | A new mapping from each node to its adjusted 2-D position array. |

### edge_exists { #tvbo.ontology.graph.edge_exists }

```python
ontology.graph.edge_exists(G, source, target, edge_type)
```

Check if an edge with the given type exists between source and target in a MultiDiGraph.

#### Parameters {.doc-section .doc-section-parameters}

| Name      | Type            | Description                          | Default    |
|-----------|-----------------|--------------------------------------|------------|
| G         | nx.MultiDiGraph | The graph.                           | _required_ |
| source    | hashable        | Source node.                         | _required_ |
| target    | hashable        | Target node.                         | _required_ |
| edge_type | str             | Type attribute of the edge to check. | _required_ |

#### Returns {.doc-section .doc-section-returns}

| Name   | Type   | Description                                   |
|--------|--------|-----------------------------------------------|
| bool   | bool   | True if such an edge exists, False otherwise. |

### get_color_mapping { #tvbo.ontology.graph.get_color_mapping }

```python
ontology.graph.get_color_mapping(g, by='type')
```

Map nodes of a graph to distinct colors based on a node attribute.



#### Parameters: {.doc-section .doc-section-parameters}

g : nx.Graph
    The input graph.
by : str, optional
    Node attribute to be used for color mapping. Default is "type".



#### Returns: {.doc-section .doc-section-returns}

dict
    A dictionary mapping each node to a color index.

### hierarchy_graph { #tvbo.ontology.graph.hierarchy_graph }

```python
ontology.graph.hierarchy_graph(G)
```

Extract the `is_a` hierarchy of a graph into a new multigraph.

Copies only the edges whose `type` attribute equals `"is_a"`, together with their incident nodes and attributes, dropping all object-property and other relation edges.

#### Parameters {.doc-section .doc-section-parameters}

| Name   | Type            | Description                                        | Default    |
|--------|-----------------|----------------------------------------------------|------------|
| G      | nx.MultiDiGraph | Source graph whose edges carry a `type` attribute. | _required_ |

#### Returns {.doc-section .doc-section-returns}

| Name   | Type            | Description                                                              |
|--------|-----------------|--------------------------------------------------------------------------|
|        | nx.MultiDiGraph | A `networkx.MultiDiGraph` containing only the `is_a` edges and the nodes |
|        | nx.MultiDiGraph | they connect.                                                            |

### labels_as_symbols { #tvbo.ontology.graph.labels_as_symbols }

```python
ontology.graph.labels_as_symbols(G)
```

Map graph nodes to LaTeX-rendered symbol labels.

For each node exposing a non-empty `symbol` annotation, the label is that symbol typeset as inline LaTeX (e.g. `$x$`); nodes without a symbol map to themselves.

#### Parameters {.doc-section .doc-section-parameters}

| Name   | Type     | Description                                                 | Default    |
|--------|----------|-------------------------------------------------------------|------------|
| G      | nx.Graph | Graph whose nodes may carry a `symbol` annotation property. | _required_ |

#### Returns {.doc-section .doc-section-returns}

| Name   | Type             | Description                                                            |
|--------|------------------|------------------------------------------------------------------------|
|        | dict\[Any, str\] | A mapping from each node to its inline-LaTeX label string, or the node |
|        | dict\[Any, str\] | itself when it has no symbol.                                          |

### model2graph { #tvbo.ontology.graph.model2graph }

```python
ontology.graph.model2graph(model)
```

Build a dependency graph of a model's dynamics components.

Resolves `model` (by name if given as a string), walks its descendant classes, and keeps only those categorised as a `Parameter`, `StateVariable`, `TimeDerivative`, `Function`, or `ConditionalDerivedVariable`. Each retained class becomes a node tagged with its category, with `is_a` edges to parent classes and object-property edges to other in-model classes.

#### Parameters {.doc-section .doc-section-parameters}

| Name   | Type   | Description                                                                | Default    |
|--------|--------|----------------------------------------------------------------------------|------------|
| model  |        | A model class, or the name of a model to resolve via `ontology.get_model`. | _required_ |

#### Returns {.doc-section .doc-section-returns}

| Name   | Type            | Description                                                          |
|--------|-----------------|----------------------------------------------------------------------|
|        | nx.MultiDiGraph | A `networkx.MultiDiGraph` induced on the retained dynamics-component |
|        | nx.MultiDiGraph | nodes, each node's `type` set to its ontology category.              |

### nx2mermaid { #tvbo.ontology.graph.nx2mermaid }

```python
ontology.graph.nx2mermaid(G, id_as_label=False)
```

Convert a NetworkX graph to a Mermaid representation.



#### Parameters: {.doc-section .doc-section-parameters}

G : nx.Graph
    NetworkX graph to be converted.
id_as_label : bool, optional
    Use identifier as label in the Mermaid graph. Default is False.



#### Returns: {.doc-section .doc-section-returns}

str
    The Mermaid representation of the graph.

### onto2graph { #tvbo.ontology.graph.onto2graph }

```python
ontology.graph.onto2graph(
    onto='default',
    add_object_properties=True,
    storid=False,
    object2string=True,
)
```

Convert an ontology into a NetworkX directed graph.

The function generates a directed graph (`DiGraph`) where:

- Nodes represent ontology classes.
- Node attributes contain annotation properties of the classes.
- Edges represent relationships between the classes, either
  hierarchical (`is_a`) or based on object properties.

#### Note {.doc-section .doc-section-note}

The function assumes that there's a utility function
`get_class_properties(c)` available which retrieves properties
of a given ontology class in a predefined format, especially
the "annotation_properties" and "object_properties".

#### Warning {.doc-section .doc-section-warning}

The function omits the "Thing" class and its properties
to avoid redundant information.

#### Returns {.doc-section .doc-section-returns}

| Name   | Type            | Description                                                                |
|--------|-----------------|----------------------------------------------------------------------------|
|        | nx.MultiDiGraph | nx.MultiDiGraph: A directed multigraph representation of the ontology with |
|        | nx.MultiDiGraph | nodes representing ontology classes and edges representing relationships.  |

#### Examples {.doc-section .doc-section-examples}

```python
>>> G = owl2nx_digraph()
>>> print(G.nodes(data=True))
[('ClassA', {'ID': 'id123', 'label': 'A'}), ...]
>>> print(G.edges(data=True))
[('ClassA', 'ClassB', {'type': 'is_a'}), ...]
```

#### Raises {.doc-section .doc-section-raises}

| Name   | Type      | Description                                                 |
|--------|-----------|-------------------------------------------------------------|
|        | KeyError  | If expected properties are not found in the ontology class. |
|        | TypeError | If the ontology structure differs from the expected format. |

### owl2nx_digraph { #tvbo.ontology.graph.owl2nx_digraph }

```python
ontology.graph.owl2nx_digraph(
    onto='default',
    add_object_properties=True,
    object2string=True,
)
```

Convert an ontology into a NetworkX directed graph.

The function generates a directed graph (`DiGraph`) where:

- Nodes represent ontology classes.
- Node attributes contain annotation properties of the classes.
- Edges represent relationships between the classes, either
  hierarchical (`is_a`) or based on object properties.

#### Note {.doc-section .doc-section-note}

The function assumes that there's a utility function
`get_class_properties(c)` available which retrieves properties
of a given ontology class in a predefined format, especially
the "annotation_properties" and "object_properties".

#### Warning {.doc-section .doc-section-warning}

The function omits the "Thing" class and its properties
to avoid redundant information.

#### Returns {.doc-section .doc-section-returns}

| Name   | Type            | Description                                                       |
|--------|-----------------|-------------------------------------------------------------------|
|        | nx.MultiDiGraph | networkx.DiGraph: A directed graph representation of the ontology |
|        | nx.MultiDiGraph | with nodes representing ontology classes and edges representing   |
|        | nx.MultiDiGraph | relationships.                                                    |

#### Examples {.doc-section .doc-section-examples}

```python
>>> G = owl2nx_digraph()
>>> print(G.nodes(data=True))
[('ClassA', {'ID': 'id123', 'label': 'A'}), ...]
>>> print(G.edges(data=True))
[('ClassA', 'ClassB', {'type': 'is_a'}), ...]
```

#### Raises {.doc-section .doc-section-raises}

| Name   | Type      | Description                                                 |
|--------|-----------|-------------------------------------------------------------|
|        | KeyError  | If expected properties are not found in the ontology class. |
|        | TypeError | If the ontology structure differs from the expected format. |

### subset2graph { #tvbo.ontology.graph.subset2graph }

```python
ontology.graph.subset2graph(
    subset,
    add_object_properties=True,
    add_annotation_properties=True,
    add_individuals=True,
    individual_relationships=None,
    expand_nodes=False,
)
```

Build a directed multigraph from a subset of ontology classes.

Each class in `subset` becomes a node with `is_a` edges to its parent classes and, optionally, edges derived from object-property restrictions and links from individuals that reference the class.

#### Parameters {.doc-section .doc-section-parameters}

| Name                      | Type                | Description                                                                                                                       | Default    |
|---------------------------|---------------------|-----------------------------------------------------------------------------------------------------------------------------------|------------|
| subset                    |                     | Iterable of ontology classes (owlready2 `ThingClass`) to include as nodes; `Restriction` entries are skipped.                     | _required_ |
| add_object_properties     | bool                | If `True`, add edges for object-property restrictions found in each class's `is_a` list (data-property restrictions are ignored). | `True`     |
| add_annotation_properties | bool                | If `True`, attach each class's annotation properties as node attributes.                                                          | `True`     |
| add_individuals           | bool                | If `True`, add edges from individuals that reference a node via one of `individual_relationships`.                                | `True`     |
| individual_relationships  | list\[str\] \| None | Names of the properties linking individuals to the subset classes; matching links are added as `has_reference` edges.             | `None`     |
| expand_nodes              | bool                | Currently unused placeholder for restricting the result to the original subset.                                                   | `False`    |

#### Returns {.doc-section .doc-section-returns}

| Name   | Type            | Description                                                              |
|--------|-----------------|--------------------------------------------------------------------------|
|        | nx.MultiDiGraph | A `networkx.MultiDiGraph` of the subset with hierarchy, object-property, |
|        | nx.MultiDiGraph | and individual-reference edges.                                          |