bgneal@6: """This module contains the RandomGraph class. bgneal@6: bgneal@6: """ bgneal@6: import random bgneal@6: import itertools bgneal@6: bgneal@6: from Graph import Graph, Edge bgneal@6: bgneal@6: bgneal@6: class RandomGraph(Graph): bgneal@6: """A RandomGraph is a Graph that adds a method to generate random edges.""" bgneal@6: bgneal@6: def add_random_edges(self, p=0.5): bgneal@6: """This method first removes all edges, then adds edges at random such bgneal@6: that the probability is p that there is an edge between any two nodes. bgneal@6: bgneal@6: p must be a float between 0 and 1, inclusive. bgneal@6: bgneal@6: """ bgneal@6: self.remove_all_edges() bgneal@6: bgneal@6: # For each combination of 2 vertices, create an edge between them if we bgneal@6: # select a random number [0.0, 1.0) that is less than p. bgneal@6: for v, w in itertools.combinations(self.iterkeys(), 2): bgneal@6: if random.random() <= p: bgneal@6: self.add_edge(Edge(v, w)) bgneal@6: bgneal@6: bgneal@6: if __name__ == '__main__': bgneal@6: import string bgneal@6: import sys bgneal@6: from Graph import Vertex bgneal@6: from GraphWorld import GraphWorld, CircleLayout bgneal@6: bgneal@6: def main(script_name, n=10, p=0.5): bgneal@6: bgneal@6: n = int(n) bgneal@6: p = float(p) bgneal@6: bgneal@6: labels = string.ascii_lowercase + string.ascii_uppercase bgneal@6: vs = [Vertex(c) for c in labels[:n]] bgneal@6: bgneal@6: g = RandomGraph(vs) bgneal@6: g.add_random_edges(p) bgneal@6: layout = CircleLayout(g) bgneal@6: bgneal@6: gw = GraphWorld() bgneal@6: gw.show_graph(g, layout) bgneal@6: gw.mainloop() bgneal@6: bgneal@6: main(*sys.argv) bgneal@6: