Skip to content

HeteroGraphData

HeteroGraphData(
    edge_index_dict: dict[Any, array],
    node_features_dict: Optional[dict[str, array]] = None,
    edge_features_dict: Optional[dict[Any, array]] = None,
    graph_features: Optional[array] = None,
    node_labels_dict: Optional[dict[str, array]] = None,
    edge_labels_dict: Optional[dict[Any, array]] = None,
    edge_labels_index_dict: Optional[dict[Any, array]] = None,
    graph_labels: Optional[array] = None,
    **kwargs,
)

Represents a graph structure with multiple node and edge types

Parameters:

Name Type Description Default
edge_index_dict dict[Any, array]

A dictionary mapping edge types to their corresponding edge indices. The edge indices are represented as a 2D array of shape [2, num_edges], where the first row contains the source node indices and the second row contains the destination node indices.

required
node_features_dict Optional[dict[str, array]]

A dictionary mapping node types to their corresponding node feature. Each node feature has shape [num_nodes, num_features].

None
edge_features_dict Optional[dict[Any, array]]

A dictionary mapping edge types to their corresponding edge feature matrices. Each edge feature matrix has shape [num_edges, num_features].

None
graph_features Optional[array]

A 1D array containing graph-level features.

None
node_labels_dict Optional[dict[str, array]]

A dictionary mapping node types to their corresponding node label arrays. Each node label array has shape [num_nodes].

None
edge_labels_dict Optional[dict[Any, array]]

A dictionary mapping edge types to their corresponding edge label arrays. Each edge label array has shape [num_edges].

None
edge_labels_index_dict Optional[dict[Any, array]]

A dictionary mapping edge types to their corresponding edge label index arrays. The edge label indices indicate the edges for which labels are available.

None
graph_labels Optional[array]

A 1D array containing graph-level labels.

None
**kwargs

Additional keyword arguments to store custom attributes. Pass num_nodes_dict={"node_type": count} to set the number of nodes of node types that have no features.

{}

Example:

edge_index_dict = {
    ("user", "rates", "movie"): mx.array([[0, 1], [0, 1]]),
    ("movie", "rev_rates", "user"): mx.array([[0, 1], [0, 1]]),
}
node_features_dict = {
    "user": mx.array([[0.2], [0.8]]),
    "movie": mx.array([[0.5], [0.3]]),
}
data = HeteroGraphData(edge_index_dict, node_features_dict)

Methods:

Name Description
to_dict

Converts the Data object to a dictionary.

metadata

Returns the heterogeneous metadata (node_types, edge_types) of

to_homogeneous

Converts the heterogeneous graph to a homogeneous GraphData,

to_csc_dict

Converts every edge type to CSC format (edges grouped by destination).

has_isolated_nodes

Returns a boolean of whether the graph has isolated nodes of the

has_self_loops

Returns a boolean of whether the graph

is_undirected

Returns a boolean indicating whether all edge types in the graph are undirected.

is_directed

Returns a boolean of whether all

Attributes:

Name Type Description
node_types list[str]

All node types: those with features, those appearing in any edge

edge_types list[tuple]

All edge types (src_node_type, relation, dst_node_type), in the

num_nodes dict[str, int]

Number of nodes per node type.

num_graph_features int

Returns the number of graph features.

num_edges dict[Any, int]

dictionary of number of edges for each edge type in the graph.

num_node_classes Union[dict[str, int], None]

Returns a dictionary of the number of node classes

num_edge_classes dict[Any, int]

Returns a dictionary of the number of edge classes

num_node_features dict[str, int]

Returns a dictionary of the number of node features for each node type.

num_edge_features dict[str, int]

Returns a dictionary of the number of edge features for each edge type.

Source code in mlx_graphs/data/data.py
def __init__(
    self,
    edge_index_dict: dict[Any, mx.array],
    node_features_dict: Optional[dict[str, mx.array]] = None,
    edge_features_dict: Optional[dict[Any, mx.array]] = None,
    graph_features: Optional[mx.array] = None,
    node_labels_dict: Optional[dict[str, mx.array]] = None,
    edge_labels_dict: Optional[dict[Any, mx.array]] = None,
    edge_labels_index_dict: Optional[dict[Any, mx.array]] = None,
    graph_labels: Optional[mx.array] = None,
    **kwargs,
) -> None:
    self.edge_index_dict = edge_index_dict
    self.node_features_dict = node_features_dict
    self.edge_features_dict = edge_features_dict
    self.graph_features = graph_features
    self.node_labels_dict = node_labels_dict
    self.edge_labels_index_dict = edge_labels_index_dict
    self.edge_labels_dict = edge_labels_dict
    self.graph_labels = graph_labels
    for key, value in kwargs.items():
        setattr(self, key, value)

node_types property

node_types: list[str]

All node types: those with features, those appearing in any edge type, and those listed in an optional num_nodes_dict attribute.

edge_types property

edge_types: list[tuple]

All edge types (src_node_type, relation, dst_node_type), in the order of edge_index_dict.

num_nodes property

num_nodes: dict[str, int]

Number of nodes per node type.

For each node type, the first available source is used:

  1. an explicit num_nodes_dict attribute, e.g. HeteroGraphData(..., num_nodes_dict={"conference": 20}), for node types without features;
  2. the number of rows of its node features;
  3. the largest node id used by any edge type touching it, plus one.

num_graph_features property

num_graph_features: int

Returns the number of graph features.

num_edges property

num_edges: dict[Any, int]

dictionary of number of edges for each edge type in the graph.

num_node_classes property

num_node_classes: Union[dict[str, int], None]

Returns a dictionary of the number of node classes for each node type in the current graph.

num_edge_classes property

num_edge_classes: dict[Any, int]

Returns a dictionary of the number of edge classes for each edge type in the current graph.

num_node_features property

num_node_features: dict[str, int]

Returns a dictionary of the number of node features for each node type.

num_edge_features property

num_edge_features: dict[str, int]

Returns a dictionary of the number of edge features for each edge type.

to_dict

to_dict() -> dict

Converts the Data object to a dictionary.

Returns:

Type Description
dict

A dictionary with all attributes of the HeteroGraphData object.

Source code in mlx_graphs/data/data.py
def to_dict(self) -> dict:
    """Converts the Data object to a dictionary.

    Returns:
        A dictionary with all attributes of the `HeteroGraphData` object.
    """
    return {k: v for k, v in self.__dict__.items() if v is not None}

metadata

metadata() -> tuple[list[str], list[tuple]]

Returns the heterogeneous metadata (node_types, edge_types) of the graph, as in PyG's HeteroData.metadata().

Returns:

Type Description
tuple[list[str], list[tuple]]

A tuple with the list of node types and the list of edge types.

Source code in mlx_graphs/data/data.py
def metadata(self) -> tuple[list[str], list[tuple]]:
    """Returns the heterogeneous metadata ``(node_types, edge_types)`` of
    the graph, as in PyG's ``HeteroData.metadata()``.

    Returns:
        A tuple with the list of node types and the list of edge types.
    """
    return self.node_types, self.edge_types

to_homogeneous

to_homogeneous(
    node_attrs: Optional[list[str]] = None,
    edge_attrs: Optional[list[str]] = None,
    add_node_type: bool = True,
    add_edge_type: bool = True,
    dummy_values: bool = True,
) -> GraphData

Converts the heterogeneous graph to a homogeneous GraphData, as PyG's HeteroData.to_homogeneous().

Nodes are stacked by node type in the order of node_types, and the edges of every edge type (in the order of edge_types) are offset accordingly and concatenated.

Per-type attributes are the dict attributes named <name>_dict whose keys are node types (e.g. node_features_dict, node_labels_dict, train_mask_dict) or edge types (e.g. edge_features_dict). They are merged into a single <name> attribute (e.g. node_features) if every type has them with the same number of dimensions and the same shape beyond the first one (2D node attributes of different widths are zero-padded to the widest one). With dummy_values, types missing an attribute are first filled with NaN (floats), False (booleans) or -1 (integers), provided the types that have it agree on its shape.

If edge_labels_index_dict is set, edge_labels_dict is aligned with it rather than with the edges: both are then offset and concatenated into edge_labels_index and edge_labels. Graph-level attributes (e.g. graph_labels) are copied as they are, and the other dict attributes are dropped.

Parameters:

Name Type Description Default
node_attrs Optional[list[str]]

Names (without _dict) of the node attributes to merge. All mergeable ones if None. Default: None

None
edge_attrs Optional[list[str]]

Names (without _dict) of the edge attributes to merge. All mergeable ones if None. Default: None

None
add_node_type bool

Whether to add a node_type array holding the index of the type of each node in node_types. Default: True

True
add_edge_type bool

Whether to add an edge_type array holding the index of the type of each edge in edge_types. Default: True

True
dummy_values bool

Whether to fill missing attributes with dummy values. Default: True

True

Returns:

Type Description
GraphData

The homogeneous graph, with an explicit num_nodes.

Example:

data = HeteroGraphData(
    edge_index_dict={
        ("user", "rates", "movie"): mx.array([[0, 1], [0, 1]]),
    },
    node_features_dict={
        "user": mx.array([[0.2], [0.8]]),
        "movie": mx.array([[0.5], [0.3]]),
    },
)
graph = data.to_homogeneous()
graph.edge_index
# mx.array([[0, 1], [2, 3]])
graph.node_type
# mx.array([0, 0, 1, 1])
Source code in mlx_graphs/data/data.py
def to_homogeneous(
    self,
    node_attrs: Optional[list[str]] = None,
    edge_attrs: Optional[list[str]] = None,
    add_node_type: bool = True,
    add_edge_type: bool = True,
    dummy_values: bool = True,
) -> GraphData:
    """Converts the heterogeneous graph to a homogeneous :class:`GraphData`,
    as PyG's ``HeteroData.to_homogeneous()``.

    Nodes are stacked by node type in the order of :attr:`node_types`, and
    the edges of every edge type (in the order of :attr:`edge_types`) are
    offset accordingly and concatenated.

    Per-type attributes are the dict attributes named ``<name>_dict`` whose
    keys are node types (e.g. ``node_features_dict``,
    ``node_labels_dict``, ``train_mask_dict``) or edge types (e.g.
    ``edge_features_dict``). They are merged into a single ``<name>``
    attribute (e.g. ``node_features``) if every type has them with the
    same number of dimensions and the same shape beyond the first one
    (2D node attributes of different widths are zero-padded to the widest
    one). With ``dummy_values``, types missing an attribute are first
    filled with ``NaN`` (floats), ``False`` (booleans) or ``-1``
    (integers), provided the types that have it agree on its shape.

    If ``edge_labels_index_dict`` is set, ``edge_labels_dict`` is aligned
    with it rather than with the edges: both are then offset and
    concatenated into ``edge_labels_index`` and ``edge_labels``.
    Graph-level attributes (e.g. ``graph_labels``) are copied as they are,
    and the other dict attributes are dropped.

    Args:
        node_attrs: Names (without ``_dict``) of the node attributes to
            merge. All mergeable ones if ``None``. Default: ``None``
        edge_attrs: Names (without ``_dict``) of the edge attributes to
            merge. All mergeable ones if ``None``. Default: ``None``
        add_node_type: Whether to add a ``node_type`` array holding the
            index of the type of each node in :attr:`node_types`.
            Default: ``True``
        add_edge_type: Whether to add an ``edge_type`` array holding the
            index of the type of each edge in :attr:`edge_types`.
            Default: ``True``
        dummy_values: Whether to fill missing attributes with dummy
            values. Default: ``True``

    Returns:
        The homogeneous graph, with an explicit ``num_nodes``.

    Example:

    .. code-block:: python

        data = HeteroGraphData(
            edge_index_dict={
                ("user", "rates", "movie"): mx.array([[0, 1], [0, 1]]),
            },
            node_features_dict={
                "user": mx.array([[0.2], [0.8]]),
                "movie": mx.array([[0.5], [0.3]]),
            },
        )
        graph = data.to_homogeneous()
        graph.edge_index
        # mx.array([[0, 1], [2, 3]])
        graph.node_type
        # mx.array([0, 0, 1, 1])
    """
    node_types, edge_types = self.metadata()
    num_nodes_dict = self.num_nodes
    offsets, total = {}, 0
    for node_type in node_types:
        offsets[node_type] = total
        total += num_nodes_dict[node_type]
    num_edges_dict = self.num_edges

    node_dicts, edge_dicts = self._typed_attributes()
    if self.edge_labels_index_dict:
        edge_dicts.pop("edge_labels", None)

    def merge(
        dicts: dict[str, dict],
        types: list,
        sizes: dict,
        keys: Optional[list[str]],
        pad_2d: bool,
    ) -> dict[str, mx.array]:
        merged = {}
        for name, values in dicts.items():
            if keys is not None and name not in keys:
                continue
            trailing = {tuple(v.shape[1:]) for v in values.values()}
            ndims = {v.ndim for v in values.values()}
            if len(values) < len(types):
                if not dummy_values or len(trailing) != 1:
                    continue
                ref = next(iter(values.values()))
                if mx.issubdtype(ref.dtype, mx.floating):
                    dummy: Any = float("nan")
                elif ref.dtype == mx.bool_:
                    dummy = False
                else:
                    dummy = -1
                values = {
                    t: values.get(t)
                    if t in values
                    else mx.full((sizes[t], *ref.shape[1:]), dummy, ref.dtype)
                    for t in types
                }
            if len(ndims) != 1:
                continue
            arrays = [values[t] for t in types]
            if len(trailing) != 1:
                if not (pad_2d and ndims == {2}):
                    continue
                width = max(a.shape[1] for a in arrays)
                arrays = [
                    mx.pad(a, [(0, 0), (0, width - a.shape[1])]) for a in arrays
                ]
            merged[name] = mx.concatenate(arrays, axis=0)
        return merged

    attributes: dict[str, Any] = {}
    handled = {f"{name}_dict" for name in (*node_dicts, *edge_dicts)}
    handled |= {"edge_index_dict", "edge_labels_index_dict", "num_nodes_dict"}
    if self.edge_labels_index_dict:
        handled.add("edge_labels_dict")
    for key, value in vars(self).items():
        if key in handled or key.startswith("_"):
            continue
        # Other dicts cannot be merged nor batched as graph attributes.
        if value is not None and not isinstance(value, dict):
            attributes[key] = value

    attributes.update(
        merge(node_dicts, node_types, num_nodes_dict, node_attrs, pad_2d=True)
    )
    attributes.update(
        merge(edge_dicts, edge_types, num_edges_dict, edge_attrs, pad_2d=False)
    )

    def offset(edge_type: tuple, edge_index: mx.array) -> mx.array:
        src, _, dst = edge_type
        shift = mx.array([[offsets[src]], [offsets[dst]]], dtype=edge_index.dtype)
        return edge_index + shift

    if len(edge_types) > 0:
        edge_index = mx.concatenate(
            [offset(et, self.edge_index_dict[et]) for et in edge_types], axis=1
        )
    else:
        edge_index = mx.zeros((2, 0), dtype=mx.int32)

    if self.edge_labels_index_dict:
        label_types = list(self.edge_labels_index_dict.keys())
        attributes["edge_labels_index"] = mx.concatenate(
            [offset(et, self.edge_labels_index_dict[et]) for et in label_types],
            axis=1,
        )
        labels = self.edge_labels_dict or {}
        if all(et in labels for et in label_types):
            attributes["edge_labels"] = mx.concatenate(
                [labels[et] for et in label_types], axis=0
            )

    if add_node_type:
        attributes["node_type"] = mx.array(
            np.repeat(
                np.arange(len(node_types)),
                [num_nodes_dict[t] for t in node_types],
            ).astype(np.int32)
        )
    if add_edge_type:
        attributes["edge_type"] = mx.array(
            np.repeat(
                np.arange(len(edge_types)),
                [num_edges_dict[t] for t in edge_types],
            ).astype(np.int32)
        )

    graph = GraphData(edge_index=edge_index, **attributes)
    graph.num_nodes = total
    return graph

to_csc_dict

to_csc_dict() -> tuple[dict[Any, array], dict[Any, array], dict[Any, array]]

Converts every edge type to CSC format (edges grouped by destination).

This is the input format of mlx_cluster.hetero_neighbor_sample.

Returns:

Type Description
dict[Any, array]

A tuple (colptr_dict, row_dict, perm_dict), each keyed by edge

type `(src, rel, dst)`
- `colptr_dict[et]`

int64 array of length num_dst_nodes + 1; the incoming edges of destination node v are at positions colptr[v] to colptr[v + 1].

- `row_dict[et]`

int64 source node of each edge, in CSC order.

- `perm_dict[et]`

int64 original position (column in edge_index_dict[et]) of each edge in CSC order, used to look up edge features of sampled edges.

Source code in mlx_graphs/data/data.py
def to_csc_dict(
    self,
) -> tuple[dict[Any, mx.array], dict[Any, mx.array], dict[Any, mx.array]]:
    """Converts every edge type to CSC format (edges grouped by destination).

    This is the input format of ``mlx_cluster.hetero_neighbor_sample``.

    Returns:
        A tuple ``(colptr_dict, row_dict, perm_dict)``, each keyed by edge
        type ``(src, rel, dst)``:

        - ``colptr_dict[et]``: ``int64`` array of length ``num_dst_nodes + 1``;
            the incoming edges of destination node ``v`` are at positions
            ``colptr[v]`` to ``colptr[v + 1]``.
        - ``row_dict[et]``: ``int64`` source node of each edge, in CSC order.
        - ``perm_dict[et]``: ``int64`` original position (column in
            ``edge_index_dict[et]``) of each edge in CSC order, used to look up
            edge features of sampled edges.
    """
    num_nodes = self.num_nodes
    colptr_dict, row_dict, perm_dict = {}, {}, {}
    for edge_type, edge_index in self.edge_index_dict.items():
        src_node_type, _, dst_node_type = edge_type
        src = np.asarray(edge_index[0]).astype(np.int64)
        dst = np.asarray(edge_index[1]).astype(np.int64)
        n_src = num_nodes[src_node_type]
        n_dst = num_nodes[dst_node_type]
        if src.size > 0 and (src.min() < 0 or src.max() >= n_src):
            raise ValueError(
                f"Edge type {edge_type} has source ids outside [0, {n_src}) "
                f"for node type '{src_node_type}'"
            )
        if dst.size > 0 and (dst.min() < 0 or dst.max() >= n_dst):
            raise ValueError(
                f"Edge type {edge_type} has destination ids outside [0, {n_dst}) "
                f"for node type '{dst_node_type}'"
            )

        order = np.argsort(dst, kind="stable")
        colptr = np.zeros(n_dst + 1, dtype=np.int64)
        np.cumsum(np.bincount(dst, minlength=n_dst), out=colptr[1:])

        colptr_dict[edge_type] = mx.array(colptr)
        row_dict[edge_type] = mx.array(src[order])
        perm_dict[edge_type] = mx.array(order.astype(np.int64))
    return colptr_dict, row_dict, perm_dict

has_isolated_nodes

has_isolated_nodes(node_type: str) -> bool

Returns a boolean of whether the graph has isolated nodes of the given type (i.e., nodes that don't have a link to any other nodes)

Source code in mlx_graphs/data/data.py
def has_isolated_nodes(self, node_type: str) -> bool:
    """Returns a boolean of whether the graph has isolated nodes of the
    given type
    (i.e., nodes that don't have a link to any other nodes)"""
    num_nodes = self.num_nodes[node_type]
    for edge_type, edge_index in self.edge_index_dict.items():
        src_node_type, _, dst_node_type = edge_type
        if src_node_type == node_type or dst_node_type == node_type:
            if has_isolated_nodes(edge_index, num_nodes):
                return True
    return False

has_self_loops

has_self_loops() -> bool

Returns a boolean of whether the graph contains self loops for the given edge type.

Source code in mlx_graphs/data/data.py
def has_self_loops(self) -> bool:
    """
    Returns a boolean of whether the graph
    contains self loops for the given edge type.
    """

    return all(
        has_self_loops(self.edge_index_dict[edge_type])
        for edge_type in self.edge_index_dict
    )

is_undirected

is_undirected() -> bool

Returns a boolean indicating whether all edge types in the graph are undirected.

Source code in mlx_graphs/data/data.py
def is_undirected(self) -> bool:
    """
    Returns a boolean indicating whether all edge types in the graph are undirected.
    """
    return all(
        is_undirected(
            self.edge_index_dict[edge_type],
            (
                self.edge_features_dict.get(edge_type, None)  # type: ignore
                if self.edge_features_dict
                else None
            ),
        )
        for edge_type in self.edge_index_dict
    )

is_directed

is_directed() -> bool

Returns a boolean of whether all edges are directed or not.

Source code in mlx_graphs/data/data.py
def is_directed(self) -> bool:
    """
    Returns a boolean of whether all
    edges are directed or not.
    """
    return all(
        not is_undirected(self.edge_index_dict[edge_type])
        for edge_type in self.edge_index_dict
    )

from mlx_graphs.data.data import HeteroGraphData · mlx_graphs/data/data.py