Skip to content

LargestConnectedComponents

LargestConnectedComponents(
    num_components: int = 1, connection: Literal["weak", "strong"] = "weak"
)

Bases: BaseTransform

Keeps only the largest connected components of a graph.

The nodes are relabeled to [0, num_remaining_nodes) in their original order, and every per-node and per-edge attribute is sliced accordingly. Requires scipy.

Parameters:

Name Type Description Default
num_components int

Number of largest components to keep. Default: 1

1
connection Literal['weak', 'strong']

"weak" to ignore the direction of the edges when looking for components, "strong" to require directed paths in both directions. Default: "weak"

'weak'

Example:

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

Methods:

Name Description
process

Restricts data to its largest connected components.

Source code in mlx_graphs/transforms/structure.py
def __init__(
    self,
    num_components: int = 1,
    connection: Literal["weak", "strong"] = "weak",
):
    if connection not in ("weak", "strong"):
        raise ValueError(
            f"Unknown connection type '{connection}', expected 'weak' or 'strong'"
        )
    self.num_components = num_components
    self.connection = connection

process

process(data: GraphData) -> GraphData

Restricts data to its largest connected components.

Parameters:

Name Type Description Default
data GraphData

The graph to transform.

required

Returns:

Type Description
GraphData

The graph restricted to its largest components.

Source code in mlx_graphs/transforms/structure.py
def process(self, data: GraphData) -> GraphData:
    """Restricts ``data`` to its largest connected components.

    Args:
        data: The graph to transform.

    Returns:
        The graph restricted to its largest components.
    """
    try:
        import scipy.sparse as sp
    except ImportError as error:
        raise ImportError(
            "scipy is required by LargestConnectedComponents, "
            "run `pip install scipy`"
        ) from error

    num_nodes = _num_nodes(data)
    edges = np.asarray(data.edge_index).astype(np.int64)
    adjacency = sp.coo_matrix(
        (np.ones(edges.shape[1], dtype=np.int8), (edges[0], edges[1])),
        shape=(num_nodes, num_nodes),
    )
    num_components, component = sp.csgraph.connected_components(
        adjacency, connection=self.connection
    )
    if num_components <= self.num_components:
        data.num_nodes = num_nodes
        return data

    _, count = np.unique(component, return_counts=True)
    largest = count.argsort()[-self.num_components :]
    return _node_subgraph(data, np.isin(component, largest), num_nodes)

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