Skip to content

to_networkx

to_networkx(data: GraphData, remove_self_loops: bool = False) -> DiGraph

Converts a mlx_graphs.data.GraphData instance to a a directed networkx.DiGraph otherwise.

Parameters:

Name Type Description Default
data GraphData

Graph data object

required
remove_self_loops bool

If set to True, will not include self-loops in the resulting graph. (default: False)

False

Returns:

Type Description
DiGraph

A networkx graph

Examples:

import mlx.core as mx

edge_index = mx.array(
    [
        [0, 1, 1, 2, 2, 3],
        [1, 0, 2, 1, 3, 2],
    ]
)
node_features = mx.array([[1], [1], [1], [1]])
data = GraphData(node_features=node_features, edge_index=edge_index)
G = to_networkx(data)
print(G.edges)
>>> OutEdgeView([(0, 0), (0, 1), (1, 0), (1, 2), (2, 1), (2, 3), (3, 2)])
Source code in mlx_graphs/utils/convert.py
def to_networkx(
    data: GraphData,
    remove_self_loops: bool = False,
) -> nx.DiGraph:
    r"""Converts a :class:`mlx_graphs.data.GraphData` instance to a
    a directed :obj:`networkx.DiGraph` otherwise.

    Args:
        data: Graph data object
        remove_self_loops: If set to :obj:`True`, will not
            include self-loops in the resulting graph. (default: :obj:`False`)

    Returns:
        A networkx graph

    Examples:

    .. code-block:: python

        import mlx.core as mx

        edge_index = mx.array(
            [
                [0, 1, 1, 2, 2, 3],
                [1, 0, 2, 1, 3, 2],
            ]
        )
        node_features = mx.array([[1], [1], [1], [1]])
        data = GraphData(node_features=node_features, edge_index=edge_index)
        G = to_networkx(data)
        print(G.edges)
        >>> OutEdgeView([(0, 0), (0, 1), (1, 0), (1, 2), (2, 1), (2, 3), (3, 2)])

    """

    G = nx.DiGraph()

    if data.graph_features is not None:
        G.graph["graph_features"] = data.graph_features.tolist()

    if data.graph_labels is not None:
        G.graph["graph_labels"] = data.graph_labels.tolist()

    if data.num_nodes is None:
        return G

    node_attrs = {}
    for i in range(data.num_nodes):
        if data.node_features is not None:
            node_attrs["features"] = data.node_features[i].tolist()
        if data.node_labels is not None:
            node_attrs["label"] = data.node_labels[i].item()
        G.add_node(i, **node_attrs)

    edge_attrs = {}
    for i, (v, w) in enumerate(data.edge_index.T.tolist()):
        if remove_self_loops and v == w:
            continue
        if data.edge_features is not None:
            edge_attrs["features"] = data.edge_features[i].tolist()
        G.add_edge(v, w, **edge_attrs)

    return G

from mlx_graphs.utils.convert import to_networkx · mlx_graphs/utils/convert.py