<a id="skfolio-containers-graph"></a>

# skfolio.containers.Graph

<a id="skfolio.containers.Graph"></a>

### *class* skfolio.containers.Graph(adjacency, \*, nodes=None)

Weighted directed graph with named nodes.

Adjacency rows represent source nodes and columns represent target nodes. Zero
indicates no edge. Positive and negative weights, cycles, and self-loops are
supported. Estimators using the graph can impose additional restrictions.

Input arrays are copied and stored as read-only arrays.

* **Parameters:**
  **adjacency** *array-like or SciPy sparse array of shape (n_nodes, n_nodes)*
  : Adjacency matrix of finite real edge weights. Dense input is stored as a NumPy
    array. Sparse input is converted to compressed sparse row (CSR) format. In
    sparse input, the same edge cannot be specified more than once. For a pandas
    DataFrame, the index and columns must match `nodes` in order.

  **nodes** *array-like of shape (n_nodes,), optional*
  : Unique string identifiers, including nodes with no incoming or outgoing edges.
    Their order defines the rows and columns of the adjacency matrix. Missing values
    are not allowed. If None, `adjacency` must be a pandas DataFrame and its index
    is used.
* **Attributes:**
  [`nodes`](#skfolio.containers.Graph.nodes) *ndarray of shape (n_nodes,)*
  : Read-only node identifiers ordered as the adjacency rows and columns.

  [`adjacency`](#skfolio.containers.Graph.adjacency) *ndarray or scipy.sparse.csr_array of shape (n_nodes, n_nodes)*
  : Read-only adjacency matrix of edge weights.

  [`n_nodes`](#skfolio.containers.Graph.n_nodes) *int*
  : Number of nodes, including isolated nodes.

### Methods

| [`from_edges`](#skfolio.containers.Graph.from_edges)(edges, \*, nodes)      | Create a graph from weighted edges.               |
|------------------------------------------------------------------------------------|---------------------------------------------------|
| [`plot`](#skfolio.containers.Graph.plot)(\*[, groups, title])         | Plot the directed graph with an automatic layout. |
| [`to_dataframe`](#skfolio.containers.Graph.to_dataframe)(\*[, output_format]) | Convert the graph to a pandas DataFrame.          |

### Examples

```pycon
>>> from skfolio.containers import Graph
>>> graph = Graph.from_edges(
...     [("A", "Supplier", 1.0), ("B", "Supplier", 0.5)],
...     nodes=["A", "B", "Supplier"],
... )
>>> graph.n_nodes
3
```

<a id="skfolio.containers.Graph.adjacency"></a>

#### *property* adjacency

Read-only adjacency matrix of edge weights.

<a id="skfolio.containers.Graph.from_edges"></a>

#### *classmethod* from_edges(edges, \*, nodes)

Create a graph from weighted edges.

* **Parameters:**
  **edges** *iterable of (source, target, weight)*
  : Directed edges with finite real weights. Source and target must belong to
    `nodes`. The same edge cannot be specified more than once.

  **nodes** *array-like of shape (n_nodes,)*
  : Unique string identifiers for all nodes. Nodes absent from `edges` are
    included as isolated nodes. Their order defines the rows and columns of the
    adjacency matrix. Missing values are not allowed.
* **Returns:**
  **graph** *Graph*
  : Weighted directed graph.

### Examples

Node B has no incoming or outgoing edges:

```pycon
>>> from skfolio.containers import Graph
>>> graph = Graph.from_edges(
...     [("A", "Supplier", 1.0)],
...     nodes=["A", "B", "Supplier"],
... )
>>> graph.adjacency.toarray()
array([[0., 0., 1.],
       [0., 0., 0.],
       [0., 0., 0.]])
```

<a id="skfolio.containers.Graph.n_nodes"></a>

#### *property* n_nodes

Number of nodes, including isolated nodes.

<a id="skfolio.containers.Graph.nodes"></a>

#### *property* nodes

Read-only node identifiers ordered as the adjacency rows and columns.

<a id="skfolio.containers.Graph.plot"></a>

#### plot(\*, groups=None, title=None)

Plot the directed graph with an automatic layout.

Dependencies are arranged from left to right, with node ordering chosen to
reduce edge crossings. Graphs with many edges spanning several layers use a
spring layout. Edge weights do not affect node positions.

* **Parameters:**
  **groups** *mapping of str to str, optional*
  : Group labels keyed by node name. Each node has one string label, used for
    its color and legend entry. Nodes omitted from `groups` belong to the gray
    “Ungrouped” category. Entries for nodes outside the graph are ignored.
    Groups are ordered alphabetically for color assignment and the legend.
    If None, all nodes have the same color and no legend is displayed.

  **title** *str, optional*
  : Figure title. If None, no title is displayed.
* **Returns:**
  **figure** *plotly.graph_objects.Figure*
  : Interactive graph figure.

### Notes

Plotting supports up to 500 nodes and 5,000 edges. Larger graphs can be exported
with `to_dataframe` for visualization with other tools. Positions can change
between snapshots, so their coordinates do not represent changes in edge weights.

### Examples

Assets and suppliers shown in different colors:

```pycon
>>> from skfolio.containers import Graph
>>> graph = Graph.from_edges(
...     [("A", "Supplier", 1), ("B", "Supplier", 1)],
...     nodes=["A", "B", "Supplier"],
... )
>>> groups = {"A": "Assets", "B": "Assets", "Supplier": "Suppliers"}
>>> figure = graph.plot(groups=groups)
```

<a id="skfolio.containers.Graph.to_dataframe"></a>

#### to_dataframe(\*, output_format='edges')

Convert the graph to a pandas DataFrame.

* **Parameters:**
  **output_format** *{“edges”, “adjacency”}, default=”edges”*
  : With “edges”, return nonzero edges as `source`, `target` and `weight`
    columns, ordered by source and target positions in `nodes`. With
    “adjacency”, return the adjacency matrix with node identifiers as both
    index and columns. Sparse adjacency produces a pandas sparse DataFrame.
* **Returns:**
  **dataframe** *DataFrame*
  : Edge table or adjacency matrix, independent of the graph’s arrays.

### Examples

```pycon
>>> from skfolio.containers import Graph
>>> graph = Graph.from_edges([("A", "Supplier", 2)], nodes=["A", "Supplier"])
>>> graph.to_dataframe()
  source    target  weight
0      A  Supplier     2.0
```

