Skip to content

AddSelfLoops

AddSelfLoops(fill_value: float = 1.0)

Bases: BaseTransform

Adds a self-loop to every node of a graph.

A self-loop is appended for every node, including the nodes that already have one (use RemoveSelfLoops first to avoid duplicates). Every per-edge attribute (e.g. edge_features, edge_weights) is extended with fill_value for the new edges.

Parameters:

Name Type Description Default
fill_value float

Value of the per-edge attributes of the added self-loops. Default: 1.0

1.0

Example:

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

Methods:

Name Description
process

Adds the self-loops to data.

Source code in mlx_graphs/transforms/structure.py
def __init__(self, fill_value: float = 1.0):
    self.fill_value = fill_value

process

process(data: GraphData) -> GraphData

Adds the self-loops to data.

Parameters:

Name Type Description Default
data GraphData

The graph to transform.

required

Returns:

Type Description
GraphData

The graph with self-loops.

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

    Args:
        data: The graph to transform.

    Returns:
        The graph with self-loops.
    """
    num_nodes = _num_nodes(data)
    _, edge_keys = _attribute_names(data, num_nodes)
    for key in edge_keys:
        values = getattr(data, key)
        # `mx.full` ignores an integer dtype for a float fill value.
        loop_values = mx.full(
            (num_nodes, *values.shape[1:]), self.fill_value, dtype=values.dtype
        ).astype(values.dtype)
        setattr(data, key, mx.concatenate([values, loop_values], axis=0))
    data.edge_index = add_self_loops(data.edge_index, num_nodes=num_nodes)
    data.num_nodes = num_nodes
    return data

from mlx_graphs.transforms import AddSelfLoops · mlx_graphs/transforms/structure.py