Skip to content

Instantly share code, notes, and snippets.

@helloqiu
Created November 17, 2016 11:33
Show Gist options
  • Save helloqiu/b71e111bd268e9642a52b07810db7733 to your computer and use it in GitHub Desktop.
Save helloqiu/b71e111bd268e9642a52b07810db7733 to your computer and use it in GitHub Desktop.
small world generator
# -*- coding: utf-8 -*-
import networkx
import matplotlib.pyplot as plt
import random
import json
l = dict()
c = dict()
# Settings
start = 0
distance = 0.0005
def work(n, k, p):
G = networkx.Graph()
G.add_nodes_from(range(0, n))
for i in range(0, n):
for j in range(1, k + 1):
G.add_edges_from([(i, (i - j) % n), (i, (i + j) % n)], can_rewire=True)
for i in range(0, n):
nodes = G.neighbors(i)
for node in nodes:
if G[i][node]['can_rewire'] and p > random.random():
G.remove_edge(i, node)
new = random.randint(0, n - 1)
temp_neighbors = G.neighbors(i)
while new in temp_neighbors:
new = random.randint(0, n - 1)
G.add_edge(i, new, can_rewire=False)
plt.figure(3, figsize=(24, 24), dpi=480)
networkx.draw_circular(G, with_labels=False)
plt.savefig('final-%f.png' % p)
print('p=%f:' % p)
l[p] = networkx.average_shortest_path_length(G)
c[p] = networkx.average_clustering(G)
print('characteristic path: %f' % networkx.average_shortest_path_length(G))
print('clustering coefficient: %f' % networkx.average_clustering(G))
if __name__ == '__main__':
n = int(raw_input('Please input n:'))
k = int(raw_input('Please input k:'))
for i in range(0, 100):
p = start + distance * i
work(n, k, p)
with open('l_result.json', 'w') as f:
f.write(json.dumps(l))
with open('c_result.json', 'w') as f:
f.write(json.dumps(c))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment