Skip to content

AddRemainingSelfLoops

AddRemainingSelfLoops(attr: str = 'edge_weights', fill_value: FillValue = 1.0)

Bases: BaseTransform

Adds a self-loop to every node of a graph that does not already have one (see add_remaining_self_loops()).

The self-loops are placed after the other edges, in node order. The existing self-loops keep their attributes. The attribute attr of the new self-loops is computed from fill_value; the other per-edge attributes (e.g. edge_features, edge_labels) also follow the edges, with fill_value for the new self-loops.

Parameters:

Name Type Description Default
attr str

Name of the per-edge attribute (e.g. edge weights) filled with fill_value. Default: "edge_weights"

'edge_weights'
fill_value FillValue

Value of the attributes of the added self-loops: a number, an array, or a reduction ("add", "mean", "max", "min") of the attributes of the incoming edges of each node. Default: 1.0

1.0

Example:

graph = GraphData(
    edge_index=mx.array([[0, 1, 1], [1, 0, 1]]),
    edge_weights=mx.array([0.5, 0.5, 2.0]),
    num_nodes=3,
)
graph = AddRemainingSelfLoops()(graph)
graph.edge_index
# mx.array([[0, 1, 0, 1, 2], [1, 0, 0, 1, 2]])
graph.edge_weights
# mx.array([0.5, 0.5, 1.0, 2.0, 1.0])

Methods:

Name Description
process

Adds the missing self-loops to data.

Source code in mlx_graphs/transforms/edge_cleanup.py
def __init__(
    self,
    attr: str = "edge_weights",
    fill_value: FillValue = 1.0,
):
    self.attr = attr
    self.fill_value = fill_value

process

process(data: GraphData) -> GraphData

Adds the missing self-loops to data.

Parameters:

Name Type Description Default
data GraphData

The graph to transform.

required

Returns:

Type Description
GraphData

The graph with a self-loop on every node.

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

    Args:
        data: The graph to transform.

    Returns:
        The graph with a self-loop on every node.
    """
    num_nodes = _num_nodes(data)
    _, edge_keys = _attribute_names(data, num_nodes)
    if getattr(data, self.attr, None) is not None and self.attr not in edge_keys:
        edge_keys.append(self.attr)
    edge_index = data.edge_index
    for key in edge_keys:
        _, values = add_remaining_self_loops(
            edge_index, getattr(data, key), self.fill_value, num_nodes
        )
        setattr(data, key, values)
    data.edge_index, _ = add_remaining_self_loops(edge_index, num_nodes=num_nodes)
    data.num_nodes = num_nodes
    return data

from mlx_graphs.transforms import AddRemainingSelfLoops · mlx_graphs/transforms/edge_cleanup.py