Skip to content

to_pyg

to_pyg(graph: GraphData) -> Data

Converts a mlx_graphs.data.GraphData to a torch_geometric.data.Data object.

The attributes are renamed as follows:

  • node_features -> x
  • edge_features -> edge_attr
  • edge_weights -> edge_weight
  • node_labels -> y, or graph_labels -> y if the graph has no node labels (if it has both, graph_labels keeps its name)

Every other array attribute is converted to a tensor and kept under the same name, and plain Python scalars and strings are carried over as they are. num_nodes is always set explicitly. Integer arrays (indices and labels) become int64 tensors, as PyG expects.

torch and torch_geometric are optional dependencies, imported when the function is called.

Parameters:

Name Type Description Default
graph GraphData

The graph to convert.

required

Returns:

Type Description
Data

The converted PyG graph.

Example:

graph = GraphData(
    edge_index=mx.array([[0, 1], [1, 2]]),
    node_features=mx.ones((3, 4)),
    node_labels=mx.array([0, 1, 0]),
)
to_pyg(graph)
# Data(edge_index=[2, 2], x=[3, 4], y=[3], num_nodes=3)
Source code in mlx_graphs/utils/pyg.py
def to_pyg(graph: "GraphData") -> "Data":
    """
    Converts a :class:`mlx_graphs.data.GraphData` to a
    :class:`torch_geometric.data.Data` object.

    The attributes are renamed as follows:

    - ``node_features`` -> ``x``
    - ``edge_features`` -> ``edge_attr``
    - ``edge_weights`` -> ``edge_weight``
    - ``node_labels`` -> ``y``, or ``graph_labels`` -> ``y`` if the graph has
      no node labels (if it has both, ``graph_labels`` keeps its name)

    Every other array attribute is converted to a tensor and kept under the
    same name, and plain Python scalars and strings are carried over as they
    are. ``num_nodes`` is always set explicitly. Integer arrays (indices and
    labels) become int64 tensors, as PyG expects.

    ``torch`` and ``torch_geometric`` are optional dependencies, imported when
    the function is called.

    Args:
        graph: The graph to convert.

    Returns:
        The converted PyG graph.

    Example:

    .. code-block:: python

        graph = GraphData(
            edge_index=mx.array([[0, 1], [1, 2]]),
            node_features=mx.ones((3, 4)),
            node_labels=mx.array([0, 1, 0]),
        )
        to_pyg(graph)
        # Data(edge_index=[2, 2], x=[3, 4], y=[3], num_nodes=3)
    """
    torch, Data = _import_pyg()

    def to_torch(array: mx.array) -> Any:
        array_np = np.array(array)
        if np.issubdtype(array_np.dtype, np.integer):
            array_np = array_np.astype(np.int64)
        return torch.from_numpy(array_np)

    num_nodes = graph.num_nodes
    if graph.edge_index.size > 0:
        num_nodes = max(num_nodes, int(graph.edge_index.max().item()) + 1)

    attributes = graph.to_dict()
    label_key = "node_labels" if "node_labels" in attributes else "graph_labels"

    data = Data()
    for key, value in attributes.items():
        if key.startswith("_"):
            continue
        if key == label_key:
            key = "y"
        key = _MLX_TO_PYG_NAMES.get(key, key)
        if isinstance(value, mx.array):
            data[key] = to_torch(value)
        elif isinstance(value, _SCALAR_TYPES):
            data[key] = value
    data.num_nodes = num_nodes
    return data

from mlx_graphs.utils import to_pyg · mlx_graphs/utils/pyg.py