comparison 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
comparison
equal deleted inserted replaced
34:66a5e7f7c10f 35:10db8c3a6b83
1 """Chapter 5.5, exercise 6 in Allen Downey's Think Complexity book.
2
3 2. Use the WS model to generate the largest graph you can in a reasonable amount
4 of time. Plot P(k) versus k and see if you can characterize the tail
5 behavior.
6
7 """
8 import sys
9
10 from matplotlib import pyplot
11
12 from Graph import Vertex
13 from SmallWorldGraph import SmallWorldGraph
14
15
16
17 def main(script, n, k, p):
18
19 # create a SmallWorldGraph with n vertices, k regular edges between
20 # vertices, and rewiring probability p.
21
22 n, k, p = int(n), int(k), float(p)
23 vs = [Vertex() for i in xrange(n)]
24
25 g = SmallWorldGraph(vs, k, p)
26
27 # retrieve probabilities
28 p = g.get_p()
29
30 # plot P(k) versus k on a log-log scale
31
32 vals = p.items()
33 vals.sort(key=lambda t: t[0])
34 x, y = zip(*vals)
35
36 assert abs(sum(y) - 1.0) < 1e-6
37
38 pyplot.clf()
39 pyplot.xscale('log')
40 pyplot.yscale('log')
41 pyplot.title('P(k) versus k')
42 pyplot.xlabel('k')
43 pyplot.ylabel('P(k)')
44 pyplot.plot(x, y, label='P(k) vs. k', color='green', linewidth=3)
45 pyplot.legend(loc='upper right')
46 pyplot.show()
47
48
49 if __name__ == '__main__':
50 main(*sys.argv)