Skip to content

TwoHop

Bases: BaseTransform

Adds the two-hop edges to the graph, as PyG's TwoHop.

An edge \((i, k)\) is added for every path \(i \rightarrow j \rightarrow k\) with \(i \neq k\). The edges are then coalesced: sorted by source then destination node, without duplicates. Every per-edge attribute (e.g. edge_features) gets zeros for the new edges, and the values of merged duplicate edges are summed.

Example:

graph = GraphData(edge_index=mx.array([[0, 1], [1, 2]]))
graph = TwoHop()(graph)
graph.edge_index
# mx.array([[0, 0, 1], [1, 2, 2]])

Methods:

Name Description
process

Adds the two-hop edges to data.

process

process(data: GraphData) -> GraphData

Adds the two-hop edges to data.

Parameters:

Name Type Description Default
data GraphData

The graph to transform.

required

Returns:

Type Description
GraphData

The graph with the two-hop edges.

Source code in mlx_graphs/transforms/topology.py
def process(self, data: GraphData) -> GraphData:
    """Adds the two-hop edges to ``data``.

    Args:
        data: The graph to transform.

    Returns:
        The graph with the two-hop edges.
    """
    num_nodes = _num_nodes(data)
    _, edge_keys = _attribute_names(data, num_nodes)
    src, dst = _host_edges(data)
    ptr, order = _csr(src, dst, num_nodes)
    owner, position = _expand(ptr, dst)
    hop_src, hop_dst = src[owner], dst[order[position]]
    not_loop = hop_src != hop_dst
    hops = _unique_pairs(hop_src[not_loop], hop_dst[not_loop], num_nodes)

    dtype = data.edge_index.dtype
    edge_index = mx.concatenate(
        [data.edge_index, mx.array(hops, dtype=dtype)], axis=1
    )
    for key in edge_keys:
        value = getattr(data, key)
        zeros = mx.zeros((hops.shape[1], *value.shape[1:]), dtype=value.dtype)
        _, value = coalesce(
            edge_index, mx.concatenate([value, zeros]), num_nodes, "add"
        )
        setattr(data, key, value)
    data.edge_index = coalesce(edge_index, num_nodes=num_nodes)
    if _keeps_explicit_num_nodes(data):
        data.num_nodes = num_nodes
    return data

from mlx_graphs.transforms import TwoHop · mlx_graphs/transforms/topology.py