Source

CCP2011 / grafodin.py

# Disponivel no pacote de programas como: grafodin.py
import networkx as NX
from numpy import array
import threading,random, pylab as P

class Contagio:
    def __init__(self,nome):
        self.nome = nome
        self.doente = 0
        #self.transmite()
    def transmite(self):
        '''
        Tenta transmitir a doenca a tres alvos aleatorios
        '''
        if G.doentes == G.order():
            return
        for alvo in random.sample(G.nodes(),3):
            if not alvo.doente:
                G.add_edge(self,alvo)
                print "%s infectou %s"%(self.nome, alvo.nome)
                t = threading.Thread(target=alvo.contraiu)
                t.start()
        #t.join()
                
    def contraiu(self):
        """
        atualiza estado
        """
        self.doente +=1
        G.doentes +=1
        self.transmite()

G = NX.DiGraph()
G.doentes = 0
nos = set([Contagio(n) for n in xrange(100)])
G.add_nodes_from(list(nos)) 
caso_indice = G.nodes()[0]
caso_indice.contraiu()

nomes = dict([(no,no.nome) for no in G.nodes()])
NX.draw_spring(G,prog='twopi',labels=nomes, alpha=0.7,width=2, style='dotted', node_size=450, font_size=14)
P.savefig('contagio.png',dpi=400)
print "usamos %s das arestas possiveis"%(NX.density(G))
print NX.degree_histogram(G), G.doentes
am = NX.adj_matrix(G)
print G.number_of_nodes(),G.number_of_edges()

P.figure()
P.pcolor(array(am))
P.colorbar()
P.title('adjacency matrix')
P.show()