Fastest possible contagion algorithm with iGraph
--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5
--
Chapters
00:00 Fastest Possible Contagion Algorithm With Igraph
01:25 Accepted Answer Score 1
02:17 Thank you
--
Full question
https://stackoverflow.com/questions/3360...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #igraph
#avk47
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 5
--
Chapters
00:00 Fastest Possible Contagion Algorithm With Igraph
01:25 Accepted Answer Score 1
02:17 Thank you
--
Full question
https://stackoverflow.com/questions/3360...
--
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