kikatuso
kikatuso

Reputation: 160

Python - Networkx create a random graph with a custom bond probability for each edge

I am just wondering if there is a way to implement a random graph of size N where the probability of a bond between each pair of nodes is given by the specific cell in the matrix of probabilities, say P of size NxN, where P_{ij} denotes the probability of a bond between node n_{i} and n_{j}.

Perhaps the function should be similar to the function networkx.generators.random_graphs.gnp_random_graph but with a possibility of adding a matrix of probabilities P, rather than a float p that denotes probability of a bond creation between any node pair.

Upvotes: 2

Views: 1594

Answers (3)

home284
home284

Reputation: 1

import networkx as nx
import matplotlib.pyplot as plt
import numpy as np

N = 8
m = np.random.random(N*N).reshape(N, N)
for i in range(N): m[i, i] = 0

nodes = range(N)
edges = {}
for i in range(N):
    for j in range(N):
        if np.random.random() < m[i, j]:
            edges[(i, j)] = round(m[i, j], 2)

G = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)
pos = nx.spring_layout(G)
nx.draw(G, pos)
nx.draw_networkx_edge_labels(G, pos, edge_labels=edges)
plt.show()

result

Upvotes: 0

Paul Brodersen
Paul Brodersen

Reputation: 13031

It is very easy to roll your own graph generator for this case.

#!/usr/bin/env python
import numpy as np
import networkx as nx

N = 10 # number of nodes
P = np.random.rand(10, 10) # your "matrix of probabilities"
adjacency = np.random.rand(*P.shape) <= P # adjacency[ii, jj] is True with probability P[ii, jj]
graph = nx.from_numpy_matrix(adjacency, nx.DiGraph) # assuming the graph is supposed to be directed, presumably if P[ii, jj] != P[jj, ii]

Upvotes: 4

Mortz
Mortz

Reputation: 4879

I think you just need to set up the nodes and edges as per your requirement and pass it to a Graph Constructor

For example -

import networkx as nx
import itertools
import random
def setup_nodes_edges(n, p_matrix):
    nodes = list(range(n))
    edges = set()
    for combination in itertools.combinations(nodes, 2):
        x, y = combination
        if p_matrix[x][y] <= random.random():
            edges.add(combination)
    return nodes, edges

nodes, edges = setup_nodes_edges(3, p_matrix) # I assume you have a p_matrix
G = nx.Graph()
G.add_nodes_from(nodes)
G.add_edges_from(edges)

Upvotes: 0

Related Questions