Mercurial > public > think_complexity
diff ch5ex6-2.py @ 35:10db8c3a6b83
Chapter 5.5, exercise 6, #2: plot P(k) vs. k for a WS graph.
author | Brian Neal <bgneal@gmail.com> |
---|---|
date | Wed, 09 Jan 2013 20:51:16 -0600 |
parents | |
children |
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/ch5ex6-2.py Wed Jan 09 20:51:16 2013 -0600 @@ -0,0 +1,50 @@ +"""Chapter 5.5, exercise 6 in Allen Downey's Think Complexity book. + +2. Use the WS model to generate the largest graph you can in a reasonable amount + of time. Plot P(k) versus k and see if you can characterize the tail + behavior. + +""" +import sys + +from matplotlib import pyplot + +from Graph import Vertex +from SmallWorldGraph import SmallWorldGraph + + + +def main(script, n, k, p): + + # create a SmallWorldGraph with n vertices, k regular edges between + # vertices, and rewiring probability p. + + n, k, p = int(n), int(k), float(p) + vs = [Vertex() for i in xrange(n)] + + g = SmallWorldGraph(vs, k, p) + + # retrieve probabilities + p = g.get_p() + + # plot P(k) versus k on a log-log scale + + vals = p.items() + vals.sort(key=lambda t: t[0]) + x, y = zip(*vals) + + assert abs(sum(y) - 1.0) < 1e-6 + + pyplot.clf() + pyplot.xscale('log') + pyplot.yscale('log') + pyplot.title('P(k) versus k') + pyplot.xlabel('k') + pyplot.ylabel('P(k)') + pyplot.plot(x, y, label='P(k) vs. k', color='green', linewidth=3) + pyplot.legend(loc='upper right') + pyplot.show() + + +if __name__ == '__main__': + main(*sys.argv)