Skip to content

barabasi_albert_graph

barabasi_albert_graph(num_nodes: int, num_edges: int) -> array

Returns the edges of a random Barabasi-Albert graph (preferential attachment): each new node is connected to num_edges existing nodes, chosen with a probability proportional to their degree.

Randomness comes from mx.random, so results are reproducible with mx.random.seed.

Parameters:

Name Type Description Default
num_nodes int

Number of nodes.

required
num_edges int

Number of edges added for each new node.

required

Returns:

Type Description
array

The sorted, undirected int32 edge_index of the graph, without

array

self-loops and duplicates.

Example:

barabasi_albert_graph(5, 2)
# e.g. mx.array([[0, 0, 1, 1, 2, 2, 3, 3, 4, 4],
#                [2, 3, 3, 4, 0, 4, 0, 1, 1, 2]])
Source code in mlx_graphs/utils/generators.py
def barabasi_albert_graph(num_nodes: int, num_edges: int) -> mx.array:
    """
    Returns the edges of a random Barabasi-Albert graph (preferential
    attachment): each new node is connected to ``num_edges`` existing nodes,
    chosen with a probability proportional to their degree.

    Randomness comes from ``mx.random``, so results are reproducible with
    ``mx.random.seed``.

    Args:
        num_nodes: Number of nodes.
        num_edges: Number of edges added for each new node.

    Returns:
        The sorted, undirected int32 ``edge_index`` of the graph, without
        self-loops and duplicates.

    Example:

    .. code-block:: python

        barabasi_albert_graph(5, 2)
        # e.g. mx.array([[0, 0, 1, 1, 2, 2, 3, 3, 4, 4],
        #                [2, 3, 3, 4, 0, 4, 0, 1, 1, 2]])
    """
    if not 0 < num_edges < num_nodes:
        raise ValueError(
            "`num_edges` must be positive and smaller than `num_nodes` "
            f"(got num_edges={num_edges}, num_nodes={num_nodes})"
        )
    rng = _host_rng()
    row = list(range(num_edges))
    col = rng.permutation(num_edges).tolist()
    for i in range(num_edges, num_nodes):
        choice = rng.choice(np.array(row + col), num_edges)
        row.extend([i] * num_edges)
        col.extend(choice.tolist())

    edges = np.array([row, col], dtype=np.int64)
    edges = edges[:, edges[0] != edges[1]]
    return _undirected(edges, num_nodes)

from mlx_graphs.utils import barabasi_albert_graph · mlx_graphs/utils/generators.py