The Python Oracle

Fastest possible contagion algorithm with iGraph

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Music Box Puzzles

--

Chapters
00:00 Question
02:00 Accepted answer (Score 1)
03:18 Thank you

--

Full question
https://stackoverflow.com/questions/3360...

Question links:
http://www.ncbi.nlm.nih.gov/pmc/articles.../

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #igraph

#avk47



ACCEPTED ANSWER

Score 1


I think you are duplicating your work. At each time step you check whether the vertex at hand infects others or not, namely you run countSimilarNeigh only for the vertex at hand. Instead you run it for all the neighbors of the vertex. Here is what I think the following code might work well. I have also changed the logic of the code. Now it's focused on the susceptibles and iterate through them. It's faster now but one has to check the results for integrity. My change in the countSimilarNeigh might have also made it a little bit faster.

from igraph import *
from random import *
from time import *

def countSimilarNeigh(g,v):
    return float(g.vs(g.neighbors(v))['state'].count(True))/g.degree(v)

def contagion(g):
    contagious = True
    while contagious:
        for v in g.vs():
            contagious = False
            if v['contagious'] == False:
                if countSimilarNeigh(g,v.index) > 0.1:
                    v['state'] = True
                    v['contagious'] = True
                    contagious = True

def init_graph(n = 60, p = .1):
    g = Graph.Erdos_Renyi(n,p)                
    while g.is_connected == False:
        g = Graph.Erdos_Renyi(n,p)
    g.simplify(multiple=True, loops=True)
    return g


def score(g,repl = 200):
    for c in range(repl):
        cc = 0
        for i in g.vs():
            i['contagious'] = False
            i['state'] = False
            if random() < .1 and cc < 4:
                i['state'] = True
                i['contagious'] = True
                cc += 1
        contagion(g)

t0 = time()    
score(init_graph())
print time()-t0