bgneal@35: """Chapter 5.5, exercise 6 in Allen Downey's Think Complexity book. bgneal@35: bgneal@35: 2. Use the WS model to generate the largest graph you can in a reasonable amount bgneal@35: of time. Plot P(k) versus k and see if you can characterize the tail bgneal@35: behavior. bgneal@35: bgneal@35: """ bgneal@35: import sys bgneal@35: bgneal@35: from matplotlib import pyplot bgneal@35: bgneal@35: from Graph import Vertex bgneal@35: from SmallWorldGraph import SmallWorldGraph bgneal@35: bgneal@35: bgneal@35: bgneal@35: def main(script, n, k, p): bgneal@35: bgneal@35: # create a SmallWorldGraph with n vertices, k regular edges between bgneal@35: # vertices, and rewiring probability p. bgneal@35: bgneal@35: n, k, p = int(n), int(k), float(p) bgneal@35: vs = [Vertex() for i in xrange(n)] bgneal@35: bgneal@35: g = SmallWorldGraph(vs, k, p) bgneal@35: bgneal@35: # retrieve probabilities bgneal@35: p = g.get_p() bgneal@35: bgneal@35: # plot P(k) versus k on a log-log scale bgneal@35: bgneal@35: vals = p.items() bgneal@35: vals.sort(key=lambda t: t[0]) bgneal@35: x, y = zip(*vals) bgneal@35: bgneal@35: assert abs(sum(y) - 1.0) < 1e-6 bgneal@35: bgneal@35: pyplot.clf() bgneal@35: pyplot.xscale('log') bgneal@35: pyplot.yscale('log') bgneal@35: pyplot.title('P(k) versus k') bgneal@35: pyplot.xlabel('k') bgneal@35: pyplot.ylabel('P(k)') bgneal@35: pyplot.plot(x, y, label='P(k) vs. k', color='green', linewidth=3) bgneal@35: pyplot.legend(loc='upper right') bgneal@35: pyplot.show() bgneal@35: bgneal@35: bgneal@35: if __name__ == '__main__': bgneal@35: main(*sys.argv)