In [1]:
import networkx as nx
import numpy as np
from random import randrange, choice, random
import math

In [2]:
import json
from networkx.readwrite import json_graph

Generate graph


In [3]:
n = 30
m = 2
p = 0.3

In [4]:
G = nx.barbell_graph(10,0)

In [5]:
G = nx.scale_free_graph(n)

In [6]:
G = nx.powerlaw_cluster_graph(n=n, m=m, p=p)

In [7]:
G = nx.cycle_graph(10)

Save and Plot Graph


In [8]:
d = json_graph.node_link_data(G)
for node in d['nodes']:
    node['name']=node['id']
    node['value']=G.degree(node['id'])

d['adjacency'] = json_graph.adjacency_data(G)['adjacency']
json.dump(d, open('graph.json','w'))

In [9]:
%%html
<div id="d3-example"></div>
<style>
.node {stroke: #fff; stroke-width: 1.5px;}
marker {stroke: #999;}
.link {stroke: #999; stroke-opacity: .3;}
</style>
<script src="force.js"></script>


Convert to DiGraph, if necessary


In [10]:
if G.is_multigraph():
    if G.is_directed():
        Gm = G.copy()
        G = nx.DiGraph()
        for (u,v) in Gm.edges_iter():
            G.add_edge(u,v)

Simulate Random Walks


In [11]:
frogs = 100

Fixed total time duration


In [12]:
# Life expectancy L. L should be the mean of a geometric distribution
L = int(math.ceil(10*math.log(G.order())))

In [13]:
L


Out[13]:
24

Count visits


In [14]:
frog_locations = np.random.randint(0, high = G.number_of_nodes(), size = frogs)
for node in G.nodes_iter():
    G.node[node]['visits'] = 0
for t in range(L):
    for f in range(frogs):
        loc = frog_locations[f]
        if len(G[loc])>0:
            frog_locations[f] = choice(G[loc].keys())
        else:
            frog_locations[f] = np.random.randint(0, high = G.number_of_nodes())
        G.node[frog_locations[f]]['visits'] +=1

In [15]:
fixed_visits = [G.node[node]['visits'] for node in G.nodes_iter() ]
norm_fixed_visits = np.array(fixed_visits)/float(sum(fixed_visits))
norm_fixed_visits


Out[15]:
array([ 0.09916667,  0.09541667,  0.10083333,  0.10541667,  0.11041667,
        0.105     ,  0.09791667,  0.095     ,  0.09166667,  0.09916667])

Death Process


In [16]:
# P_die is the probability that a frog dies at any given time
P_die = 1/L

Count Visits and Deaths


In [17]:
frog_locations = np.random.randint(0, high = G.number_of_nodes(), size = frogs)
for node in G.nodes_iter():
    G.node[node]['visits'] = 0
    G.node[node]['deaths'] = 0
frogs_left = frogs
time = 0
total_visits = 0
death_times_sum = 0
while frogs_left:
    time +=1
    for f in range(frogs):
        if frog_locations[f] == -1:
            continue
            
        if random() < P_die:
            G.node[frog_locations[f]]['deaths'] += 1
            death_times_sum += time
            frog_locations[f] = -1
            frogs_left -= 1
            continue
        
        total_visits +=1
        
        loc = frog_locations[f]
        if len(G[loc])>0:
            frog_locations[f] = choice(G[loc].keys())
        else:
            frog_locations[f] = np.random.randint(0, high = G.number_of_nodes())
        G.node[frog_locations[f]]['visits'] +=1


Traceback (most recent call last):
  File "/Users/migish/anaconda/lib/python2.7/site-packages/IPython/core/ultratb.py", line 970, in get_records
    return _fixed_getinnerframes(etb, number_of_lines_of_context, tb_offset)
  File "/Users/migish/anaconda/lib/python2.7/site-packages/IPython/core/ultratb.py", line 233, in wrapped
    return f(*args, **kwargs)
  File "/Users/migish/anaconda/lib/python2.7/site-packages/IPython/core/ultratb.py", line 267, in _fixed_getinnerframes
    records = fix_frame_records_filenames(inspect.getinnerframes(etb, context))
  File "/Users/migish/anaconda/lib/python2.7/inspect.py", line 1044, in getinnerframes
    framelist.append((tb.tb_frame,) + getframeinfo(tb, context))
  File "/Users/migish/anaconda/lib/python2.7/inspect.py", line 1004, in getframeinfo
    filename = getsourcefile(frame) or getfile(frame)
  File "/Users/migish/anaconda/lib/python2.7/inspect.py", line 454, in getsourcefile
    if hasattr(getmodule(object, filename), '__loader__'):
  File "/Users/migish/anaconda/lib/python2.7/inspect.py", line 497, in getmodule
    f = getabsfile(module)
  File "/Users/migish/anaconda/lib/python2.7/inspect.py", line 466, in getabsfile
    _filename = getsourcefile(object) or getfile(object)
  File "/Users/migish/anaconda/lib/python2.7/inspect.py", line 451, in getsourcefile
    if os.path.exists(filename):
  File "/Users/migish/anaconda/lib/python2.7/genericpath.py", line 18, in exists
    os.stat(path)
KeyboardInterrupt
ERROR: Internal Python error in the inspect module.
Below is the traceback from this internal error.


Unfortunately, your original traceback can not be constructed.

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/Users/migish/anaconda/lib/python2.7/site-packages/IPython/core/interactiveshell.pyc in run_code(self, code_obj, result)
   3050             if result is not None:
   3051                 result.error_in_exec = sys.exc_info()[1]
-> 3052             self.showtraceback()
   3053         else:
   3054             outflag = 0

/Users/migish/anaconda/lib/python2.7/site-packages/IPython/core/interactiveshell.pyc in showtraceback(self, exc_tuple, filename, tb_offset, exception_only)
   1849                     except Exception:
   1850                         stb = self.InteractiveTB.structured_traceback(etype,
-> 1851                                             value, tb, tb_offset=tb_offset)
   1852 
   1853                     self._showtraceback(etype, value, stb)

/Users/migish/anaconda/lib/python2.7/site-packages/IPython/core/ultratb.pyc in structured_traceback(self, etype, value, tb, tb_offset, number_of_lines_of_context)
   1238         self.tb = tb
   1239         return FormattedTB.structured_traceback(
-> 1240             self, etype, value, tb, tb_offset, number_of_lines_of_context)
   1241 
   1242 

/Users/migish/anaconda/lib/python2.7/site-packages/IPython/core/ultratb.pyc in structured_traceback(self, etype, value, tb, tb_offset, number_of_lines_of_context)
   1146             # Verbose modes need a full traceback
   1147             return VerboseTB.structured_traceback(
-> 1148                 self, etype, value, tb, tb_offset, number_of_lines_of_context
   1149             )
   1150         else:

/Users/migish/anaconda/lib/python2.7/site-packages/IPython/core/ultratb.pyc in structured_traceback(self, etype, evalue, etb, tb_offset, number_of_lines_of_context)
    998 
    999         formatted_exception = self.format_exception_as_a_whole(etype, evalue, etb, number_of_lines_of_context,
-> 1000                                                                tb_offset)
   1001 
   1002         colors = self.Colors  # just a shorthand + quicker name lookup

/Users/migish/anaconda/lib/python2.7/site-packages/IPython/core/ultratb.pyc in format_exception_as_a_whole(self, etype, evalue, etb, number_of_lines_of_context, tb_offset)
    949         records = self.get_records(etb, number_of_lines_of_context, tb_offset)
    950 
--> 951         frames = self.format_records(records)
    952         if records is None:
    953             return ""

/Users/migish/anaconda/lib/python2.7/site-packages/IPython/core/ultratb.pyc in format_records(self, records)
    722 
    723         abspath = os.path.abspath
--> 724         for frame, file, lnum, func, lines, index in records:
    725             #print '*** record:',file,lnum,func,lines,index  # dbg
    726             if not file:

TypeError: 'NoneType' object is not iterable

In [ ]:
print "Average death time:", death_times_sum / frogs
print "Expected death time:", L
print "Nominal death time STD:", math.sqrt((1-P_die)/P_die**2)

In [ ]:
visits = [G.node[node]['visits'] for node in G.nodes_iter() ]
norm_visits = np.array(visits)/float(total_visits)
norm_visits

In [ ]:
deaths = [G.node[node]['deaths'] for node in G.nodes_iter() ]
norm_deaths = np.array(deaths)/float(frogs)
norm_deaths

In [ ]:
if G.is_directed():
    degrees = [ G.in_degree(node) for node in G.nodes_iter() ]
    norm_degrees = np.array(degrees)/float(G.size())
else:
    degrees = [ G.degree(node) for node in G.nodes_iter() ]
    norm_degrees = np.array(degrees)/float(2*G.size())

norm_degrees

In [ ]:
import matplotlib.pyplot as plt
%matplotlib inline
%config InlineBackend.figure_format = 'svg'

In [ ]:
x = np.array([norm_fixed_visits, norm_visits, norm_deaths, norm_degrees]).T

plt.plot(np.array(range(G.order())).T,x)
plt.legend(['Visits (Fixed Time)', 'Visits', 'Deaths', 'Degree'], loc='best')
plt.axis([0, G.order()-1, 0, min([2*np.max(x),1])]);

In [203]:
import vincent

In [204]:
vincent.initialize_notebook()



In [205]:
multi_iter1 = {'index':range(G.order()), 'Visits (fixed duration)':norm_fixed_visits, 'Visits':norm_visits, 'Deaths':norm_deaths, 'Degree':norm_degrees}

In [206]:
line = vincent.Line(multi_iter1, iter_idx='index')
line.axis_titles(x='Vertex', y='Juice')
line.legend(title='Results')
line.width = 400
line.height = 300
#line.colors(range_=['#a6cee3','#1f78b4','#b2df8a','#33a02c'])
#line.colors(brew='Paired')
line.marks[0].marks[0].properties.enter.stroke_width.value = 6
line.marks[0].marks[0].properties.enter.stroke_opacity = vincent.ValueRef(value=0.7)

In [207]:
line.marks[0].marks[0].properties.update = vincent.PropertySet()
line.marks[0].marks[0].properties.update.stroke_opacity = vincent.ValueRef(value=0.7)
line.marks[0].marks[0].properties.hover = vincent.PropertySet()
line.marks[0].marks[0].properties.hover.stroke_opacity = vincent.ValueRef(value=1)

In [ ]:
line

In [209]:
line = vincent.Scatter(multi_iter1, iter_idx='index')
line.axis_titles(x='Vertex', y='Juice')
line.legend(title='Results')
line.width = 400
line.height = 300
line.marks[0].marks[0].properties.enter.opacity = vincent.ValueRef(value=1)

In [210]:
line.marks[0].marks[0].properties.update = vincent.PropertySet()
line.marks[0].marks[0].properties.update.size = vincent.ValueRef(value=100)
line.marks[0].marks[0].properties.hover = vincent.PropertySet()
line.marks[0].marks[0].properties.hover.size = vincent.ValueRef(value=200)

In [211]:
line.marks[0].marks[0].properties.update.size = vincent.ValueRef(value=100)
line.marks[0].marks[0].properties.hover = vincent.PropertySet()
line.marks[0].marks[0].properties.hover.size = vincent.ValueRef(value=200)

In [212]:
line


Out[212]:

In [213]:
line.scales['shape'] = vincent.Scale(name='shape', type='ordinal',
                      domain=vincent.DataRef(data='table', field='data.col'),
                      range=["square", "circle", "triangle-down", "triangle-up"])
line.marks[0].marks[0].properties.enter.shape = vincent.ValueRef(scale="shape", field="data.col")
line.legends[0].shape = "shape"

In [215]:
line


Out[215]:

In [216]:
line.to_json('scalefree.json')

In [ ]: