<jupyter_start><jupyter_text>Epidemiology 104Lecture        <NAME>        www.data4sci.com            @bgoncalves, @data4sci<jupyter_code>from collections import Counter
from pprint import pprint

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt 

import networkx as nx

import watermark

from NetworkEpiModel import *

%load_ext watermark
%matplotlib inline<jupyter_output><empty_output><jupyter_text>We start by print out the versions of the libraries we're using for future reference<jupyter_code>%watermark -n -v -m -g -iv<jupyter_output>json      2.0.9
numpy     1.18.1
pandas    1.0.1
networkx  2.4
watermark 2.0.2
autopep8  1.5
scipy     1.4.1
Mon Apr 27 2020 

CPython 3.7.3
IPython 6.2.1

compiler   : Clang 4.0.1 (tags/RELEASE_401/final)
system     : Darwin
release    : 19.4.0
machine    : x86_64
processor  : i386
CPU cores  : 8
interpreter: 64bit
Git hash   : afc8d87254a0d7946a0eabde181f736a93d48b8e<jupyter_text>Load default figure style<jupyter_code>plt.style.use('./d4sci.mplstyle')
colors = plt.rcParams['axes.prop_cycle'].by_key()['color']<jupyter_output><empty_output><jupyter_text>Start<jupyter_code>G = nx.erdos_renyi_graph(100, p=1.)
netSIR = NetworkEpiModel(G)
netSIR.add_interaction('S', 'I', 'I', 0.2)
netSIR.add_spontaneous('I', 'R', 0.1)
print(netSIR)
network = G
N = network.number_of_nodes()
timesteps = 10
population = np.zeros((timesteps, N), dtype='str')
comps = list(netSIR.transitions.nodes)
comps
time = np.arange(1, timesteps, 1, dtype='int')
susceptible = netSIR._get_susceptible()
susceptible
pos = {'S':0, 'I':1, 'R':2}
seeds = {10:'I'}
seeds
i = 0

for node in range(N):
    if node in seeds:
        population[i, node] = seeds[node]
    else:
        population[i, node] = susceptible
G.nodes()
node_i = 0
i = 1
state_i = population[i-1, node_i]
state_i
trans = netSIR.transitions.edges(state_i, data=True)
trans
node_i
list(G.neighbors(node_i))
?np.random.multinomial
kwargs = {'S':100000-1, 'I':1, 'R':0}

pos = {comp: i for i, comp in enumerate(kwargs)}
labels = [str(i) for i in range(len(pos))]

for comp in pos:
    labels[pos[comp]] = comp

counts = np.zeros(len(pos), dtype='float')

for comp in pos:
    counts[pos[comp]] = kwargs[comp]

N0 = counts.sum()

population=np.random.multinomial(N0, counts/N0)

order = np.arange(N0, dtype='int')
np.random.shuffle(order)

order
class NetworkEpiModel(EpiModel):
    def __init__(self, N, p):
        self.G = nx.erdos_renyi_graph(N, p)
        super(NetworkEpiModel, self).__init__()
        
    #def add_interaction(self, source, target, agent, rate):
        
    def _get_agents(self, labels):
        agents = {}
        
        for edge in self.transitions.edges(data=True):
            node_i, node_j, data = edge
            if "agent" in data:
                agent = labels[data['agent']]
                node_i = labels[node_i]
                
                if agent not in agents:
                    agents[agent] = set()
                    
                agents[agent].add(node_i)
                
        return agents
        
    def integrate(self, timesteps, **kwargs):
        N = self.G.number_of_nodes()
        
        population = kwargs['population']
        labels = kwargs['labels']

        order = np.arange(N)
        np.random.shuffle(order)

        agents = self._get_agents(labels)

        for time in np.arange(timestemps):
            new_pop = population.copy()

            for node_i in order:
                if population[node_i] in agents:
                    for node_j in self.G.edges(node_i):
                        if population[node_j] in agents[node_i]:
                            prob = np.random.random()
                            #rate = 



            np.random.shuffle(order)

        
#         pos = {comp: i for i, comp in enumerate(kwargs)}
#         labels = []*len(pos)
        
#         for comp in pos:
#             labels[pos[comp]] = comp
        
#         counts = np.zeros(len(pos), dtype='float')
        
#         for comp in pos:
#             counts[pos[comp]] = kwargs[comp]
        
#         N0 = counts.sum()

#         if N != N0:
#             raise PopulationMismatch('The initial population distribution must match the number of nodes in the graph')
        
#         population=np.random.multinomial(N, counts/N0)

        
#     def integrate(self, timesteps, **kwargs):
#         """Numerically integrate the epidemic model"""
#         pos = {comp: i for i, comp in enumerate(kwargs)}
#         population=np.zeros(len(pos))
        
#         for comp in pos:
#             population[pos[comp]] = kwargs[comp]
        
#         time = np.arange(1, timesteps, 1)

#         self.values_ = pd.DataFrame(scipy.integrate.odeint(self._new_cases, population, time, args=(pos,)), columns=pos.keys(), index=time)

net = NetworkEpiModel(1000, 1)
net.add_interaction('S', 'I', 'I', 0.2)
net.add_spontaneous('I', 'R', 0.1)
net._get_agents({'S':0, 'I':1, 'R':2})
net.transitions.edges('S', data=True)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12681087517364556, 'fraction_numerical': 0.026394125818614805, 'mean_word_length': 2.5294117647058822, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '656075', 'license': 'MIT', 'n_tokens_mistral': 1866, 'n_tokens_neox': 1763, 'n_words': 402, 'path': 'Epidemiology201.ipynb', 'repo_name': 'minrk/Epidemiology101', 'size': '5048'}