view RandomGraph.py @ 24:5c2c4ce095ef

A stab at the L(p)/L(0) plot. I still don't quite get how the graphs in the Watts and Strogatz paper were generated. My results have basically the same shape, but don't converge to 0. I'm not sure how this is possible if the rewire function does not remove edges.
author Brian Neal <bgneal@gmail.com>
date Thu, 03 Jan 2013 18:41:13 -0600
parents 950a34c7e26b
children
line wrap: on
line source
"""This module contains the RandomGraph class.

"""
import random
import itertools

from Graph import Graph, Edge


class RandomGraph(Graph):
    """A RandomGraph is a Graph that adds a method to generate random edges."""

    def add_random_edges(self, p=0.5):
        """This method first removes all edges, then adds edges at random such
        that the probability is p that there is an edge between any two nodes.

        p must be a float between 0 and 1, inclusive.

        """
        self.remove_all_edges()

        # For each combination of 2 vertices, create an edge between them if we
        # select a random number [0.0, 1.0) that is less than p.
        for v, w in itertools.combinations(self.iterkeys(), 2):
            if random.random() <= p:
                self.add_edge(Edge(v, w))


if __name__ == '__main__':
    import string
    import sys
    from Graph import Vertex
    from GraphWorld import GraphWorld, CircleLayout

    def main(script_name, n=10, p=0.5):

        n = int(n)
        p = float(p)

        labels = string.ascii_lowercase + string.ascii_uppercase
        vs = [Vertex(c) for c in labels[:n]]

        g = RandomGraph(vs)
        g.add_random_edges(p)
        layout = CircleLayout(g)

        gw = GraphWorld()
        gw.show_graph(g, layout)
        gw.mainloop()

    main(*sys.argv)