I want to extract two nodes from a graph, the catch being that they shouldnt be connected i.e. no direct edge exists between them. i know i can get random edges using "random.choice(g.edges())" but this would give me random nodes that are connected. I want pairs of nodes that are NOT connected (a pair of unconnected edges). help me out guys...thanx
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
None of the solutions proposed here so far will sample the non-edges (v1,v2) uniformly. Consider the example graph with 4 nodes and 2 edges:
There are 4 non-edges to choose from: (1,4),(2,3),(2,4),(3,4). Using either Maria's or Philip's method of randomly choosing the first vertex from all 4 vertices and then choosing the second vertex from the restricted set of vertices so as not to create any edges (or self-loops) will give the following probabilities for each non-edge to be chosen:
p(1,4) = 1/4 * 1 + 1/4 * 1/3 = 8/24
p(2,3) = 1/4 * 1/2 + 1/4 * 1/2 = 6/24
p(3,4) = p(2,4) = 1/4 * 1/2 + 1/4 * 1/3 = 5/24
So the procedure is not uniform.
That means if you want uniformly sampled non-edges, you will have to choose both vertices unrestricted and reject the sample (both vertices) whenever they form an existing edge (or are equal). In NetworkX:
I don't know that library, but I'd guess you could do the following:
Cheers
If the graph is small, you can collect
nx.non_edges()
into annp.array
andrandom.choice
from it:Beware that
non_edges()
itself returns you the generator, not the actual list. But if you turn it into annp.array
you acutally collects all the items in the generator. If your graph is large and sparse, this may raise a memory error, but for small graphs it would the most straightforward way to do it.Simple! :)
Grab a random node - then pick a random node from the list of nodes excluding neighbours and itself. Code to illustrate is below. :)