Skip to content

erdos_renyi_graph

erdos_renyi_graph(
    num_nodes: int, edge_prob: float, directed: bool = False
) -> array

Returns the edges of a random Erdos-Renyi graph: each possible edge (without self-loops) is present independently with probability edge_prob.

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
edge_prob float

Probability of each edge.

required
directed bool

If True, each ordered pair (i, j) is sampled independently. If False, each unordered pair is sampled once and returned in both directions. Default: False

False

Returns:

Type Description
array

The sorted int32 edge_index of the graph.

Example:

erdos_renyi_graph(4, 0.5)
# e.g. mx.array([[0, 1, 1, 2, 2, 3], [1, 0, 2, 1, 3, 2]])
Source code in mlx_graphs/utils/generators.py
def erdos_renyi_graph(
    num_nodes: int, edge_prob: float, directed: bool = False
) -> mx.array:
    """
    Returns the edges of a random Erdos-Renyi graph: each possible edge
    (without self-loops) is present independently with probability
    ``edge_prob``.

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

    Args:
        num_nodes: Number of nodes.
        edge_prob: Probability of each edge.
        directed: If ``True``, each ordered pair ``(i, j)`` is sampled
            independently. If ``False``, each unordered pair is sampled once
            and returned in both directions. Default: ``False``

    Returns:
        The sorted int32 ``edge_index`` of the graph.

    Example:

    .. code-block:: python

        erdos_renyi_graph(4, 0.5)
        # e.g. mx.array([[0, 1, 1, 2, 2, 3], [1, 0, 2, 1, 3, 2]])
    """
    if directed:
        row, col = _ordered_pairs(num_nodes)
    else:
        row, col = np.triu_indices(num_nodes, k=1)
    keep = _to_numpy(mx.random.uniform(shape=(row.size,))) < edge_prob
    edges = np.stack([row[keep], col[keep]])
    if directed:
        return mx.array(edges.astype(np.int32))
    return _undirected(edges, num_nodes)

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