Beispiel #1
0
def network_simulation():
    from epipack import StochasticEpiModel
    from epipack.plottools import plot
    import matplotlib.pyplot as pl
    import networkx as nx

    k0 = 50
    R0 = 2.5
    rho = 1
    eta = R0 * rho / k0
    omega = 1 / 14
    N = int(1e4)
    edges = [ (e[0], e[1], 1.0) for e in \
              nx.fast_gnp_random_graph(N,k0/(N-1)).edges() ]

    SIRS = StochasticEpiModel(
                compartments=list('SIR'),
                N=N,
                edge_weight_tuples=edges
                )\
            .set_link_transmission_processes([
                ('I', 'S', eta, 'I', 'I'),
            ])\
            .set_node_transition_processes([
                ('I', rho, 'R'),
                ('R', omega, 'S'),
            ])\
            .set_random_initial_conditions({
                                            'S': N-100,
                                            'I': 100
                                           })
    t_s, result_s = SIRS.simulate(40)

    ax = plot(t_s, result_s)
    ax.get_figure().savefig('network_simulation.png', dpi=300)
Beispiel #2
0
    def test_network(self):
        N = 1000
        k = 4
        links = []
        for i in range(N):
            neighs = np.random.randint(0, N - 1, size=(k, ), dtype=int)
            neighs[neighs >= i] += 1
            for neigh in neighs:
                links.append((i, int(neigh), 1.0))

        network = get_random_layout(N, links, windowwidth=500)

        model = StochasticEpiModel(
            list("SIRXTQ"),
            N=len(network['nodes']),
            directed=True,
            edge_weight_tuples=links,
        )
        k0 = model.out_degree.mean()
        R0 = 10
        recovery_rate = 1 / 8
        quarantine_rate = 1 / 16
        tracing_rate = 1 / 2
        waning_immunity_rate = 1 / 14
        infection_rate = R0 * (recovery_rate) / k0
        model.set_node_transition_processes([
            ("I", recovery_rate, "R"),
            ("I", quarantine_rate, "T"),
            ("T", tracing_rate, "X"),
            ("Q", waning_immunity_rate, "S"),
            ("X", recovery_rate, "R"),
        ])
        model.set_link_transmission_processes([("I", "S", infection_rate, "I",
                                                "I")])
        model.set_conditional_link_transmission_processes({
            ("T", "->", "X"): [
                ("X", "I", 0.5, "X", "T"),
                #("X","S",0.5,"X","Q"),
            ],
        })
        model.set_random_initial_conditions({'I': 20, 'S': N - 20})

        sampling_dt = 0.08

        visualize(model,
                  network,
                  sampling_dt,
                  ignore_plot_compartments=['S'],
                  quarantine_compartments=['X', 'T', 'Q'])
Beispiel #3
0
    def test_temporal_gillespie(self,plot=False):

        infection_rate = 1.0
        recovery_rate = 0.2
        model = StochasticEpiModel(["S","I","R"],3)\
                    .set_link_transmission_processes([
                            ("I", "S", infection_rate, "I", "I"),
                        ])\
                    .set_node_transition_processes([
                            ("I", recovery_rate, "R"),
                        ])\
                    .set_node_statuses([1,0,0])

        edges = [ [ (0,1) ], [ (0,1), (0,2) ], [] ]
        temporal_network = TemporalNetwork(3,edges,[0,0.5,1.2],1.5)
        sim = TemporalNetworkSimulation(temporal_network, model)
        N_meas = 10000
        taus = []
        for meas in range(N_meas):
            sim.reset()
            t, res = sim.simulate(1000)
            if t[-1] == 0:
                continue
            else:
                taus.append(t[1])


        def rate(t):
            t = t % 1.5
            if t < 0.5:
                return infection_rate + recovery_rate
            elif t < 1.2:
                return 2*infection_rate + recovery_rate
            elif t < 1.5:
                return recovery_rate


        measured, bins = np.histogram(taus,bins=100,density=True)
        rates = np.array([rate(_t) for _t in bins])
        I2 = cumtrapz(rates,bins,initial=0.0)
        theory = [ np.exp(-I2[i-1])-np.exp(-I2[i]) for i in range(1,len(bins)) if measured[i-1] > 0]
        experi = [ measured[i-1] for i in range(1,len(bins)) if measured[i-1] > 0]
        # make sure the kullback-leibler divergence is below some threshold
        if plot: # pragma: no cover
            import matplotlib.pyplot as pl
            pl.figure()
            pl.hist(taus,bins=100,density=True)
            tt = np.linspace(0,max(taus),10000)
            rates = np.array([rate(_t) for _t in tt])
            I2 = cumtrapz(rates,tt,initial=0.0)
            pl.plot(tt, rates*np.exp(-I2))
            pl.yscale('log')
            pl.figure()
            pl.hist(taus,bins=100,density=True)
            pl.plot(tt, rates*np.exp(-I2))
            pl.show()
        assert(entropy(theory, experi) < 0.02)
Beispiel #4
0
def network_simulation_visualization():
    from epipack import StochasticEpiModel
    from epipack.plottools import plot
    import matplotlib.pyplot as pl
    import networkx as nx

    k0 = 50
    R0 = 2.5
    rho = 1
    eta = R0 * rho / k0
    omega = 1 / 14
    N = int(1e4)
    edges = [ (e[0], e[1], 1.0) for e in \
              nx.fast_gnp_random_graph(N,k0/(N-1)).edges() ]

    SIRS = StochasticEpiModel(
                compartments=list('SIR'),
                N=N,
                edge_weight_tuples=edges
                )\
            .set_link_transmission_processes([
                ('I', 'S', eta, 'I', 'I'),
            ])\
            .set_node_transition_processes([
                ('I', rho, 'R'),
                ('R', omega, 'S'),
            ])\
            .set_random_initial_conditions({
                                            'S': N-100,
                                            'I': 100
                                           })

    from epipack.vis import visualize
    from epipack.networks import get_random_layout
    layouted_network = get_random_layout(N, edges)
    visualize(SIRS,
              layouted_network,
              sampling_dt=0.1,
              config={'draw_links': False})
Beispiel #5
0
    I0 = 50
    k0 = 100
    R0 = 2.5
    Q0 = 0.5
    waning_quarantine_rate = omega = 1 / 14
    recovery_rate = rho = 1 / 2
    quarantine_rate = kappa = rho * Q0 / (1 - Q0)
    infection_rate = eta = R0 * (rho) / k0

    p = k0 / (N - 1)
    G = nx.fast_gnp_random_graph(N, p)
    edges = [(e[0], e[1], 1.0) for e in G.edges()]

    #model = StochasticEpiModel(list("SIXRQ"),N,edge_weight_tuples=edges)
    model = StochasticEpiModel(list("SIXRQ"),
                               N,
                               well_mixed_mean_contact_number=k0)

    model.set_node_transition_processes([
        ("I", rho, "R"),
        ("I", kappa, "X"),
        ("Q", omega, "S"),
    ])

    model.set_link_transmission_processes([
        ("I", "S", eta, "I", "I"),
    ])

    model.set_conditional_link_transmission_processes({
        ("I", "->", "X"): [
            ("X", "S", Q0, "X", "Q"),
Beispiel #6
0
result_int = model.integrate(tt)

for c, res in result_int.items():
    pl.plot(tt, res)


start = time()
t, result_sim = model.simulate(tmax,sampling_dt=1)
end = time()

print("numeric model needed", end-start, "s")

for c, res in result_sim.items():
    pl.plot(t, res, '--')

model = StochasticEpiModel([S,E,I,R],N)
model.set_link_transmission_processes([
        ( I, S, 2, I, E ),
    ])
model.set_node_transition_processes([
        ( I, 1, R),
        ( E, 1, I),
    ])
model.set_random_initial_conditions({S: N-100, I: 100})

start = time()
t, result_sim = model.simulate(tmax,sampling_dt=1)
end = time()

for c, res in result_sim.items():
    pl.plot(t, res, ':')
Beispiel #7
0
from epipack.vis import visualize
from epipack import StochasticEpiModel

# load network
network, config, _ = nw.load('./MHRN.json')

# get the network properties
N = len(network['nodes'])
edge_list = [(link['source'], link['target'], 1.0)
             for link in network['links']]

# define model
model = StochasticEpiModel(
    list("SIRXTQ"),
    N=N,
    edge_weight_tuples=edge_list,
)
k0 = model.out_degree.mean()
R0 = 5
recovery_rate = 1 / 8
quarantine_rate = 1.5 * recovery_rate
infection_rate = R0 * (recovery_rate) / k0

R0 = 3
recovery_rate = 1 / 8
quarantine_rate = 1 / 16
tracing_rate = 1 / 2
waning_immunity_rate = 1 / 14
infection_rate = R0 * (recovery_rate) / k0
Beispiel #8
0
        ('A', 'S', 0.5 * infection_rate * 0.7, 'A', 'I'),
        ('A', 'S', 0.5 * infection_rate * 0.3, 'A', 'A'),
    ]

    conditional_transmission = {
        ('I', '->', 'X'): [
            ('X', 'I', p, 'X', 'X'),
        ]
    }

    model = StochasticEpiModel(
               compartments=compartments,
               N=N,
               well_mixed_mean_contact_number=k0,
               )\
           .set_link_transmission_processes(link_transmission)\
           .set_node_transition_processes(node_transition)\
           .set_conditional_link_transmission_processes(conditional_transmission)\
           .set_random_initial_conditions({
                                           'S': N-100,
                                           'I': 100
                                          })

    t, result = model.simulate(80)

    from epipack.plottools import plot

    ax = plot(t, result)
    ax.set_yscale('log')
    ax.set_ylim([1, N])
    ax.set_xlabel('time [d]')
    ax.legend()
Beispiel #9
0
from epipack.vis import visualize
from epipack import StochasticEpiModel
from epipack.colors import palettes, colors, bg_colors, hex_bg_colors

# load network
network, config, _ = nw.load('/Users/bfmaier/pythonlib/facebook/FB.json')

# get the network properties
N = len(network['nodes'])
edge_list = [(link['source'], link['target'], 1.0)
             for link in network['links']]

# define model
model = StochasticEpiModel(
    list("SIRX"),
    N=N,
    edge_weight_tuples=edge_list,
)
k0 = model.out_degree.mean()
R0 = 5
recovery_rate = 1 / 8
quarantine_rate = 1.5 * recovery_rate
infection_rate = R0 * (recovery_rate) / k0

# usual infection process
model.set_link_transmission_processes([("I", "S", infection_rate, "I", "I")])

# standard SIR dynamic with additional quarantine of symptomatic infecteds
model.set_node_transition_processes([
    ("I", recovery_rate, "R"),
    ("I", quarantine_rate, "X"),
Beispiel #10
0
            break
        print(t, next_t, edge_list)

    print("Delta T =", temporal_network._Delta_t)
    for edge_list, t, next_t in temporal_network:
        print("DeltaT =", temporal_network._Delta_t)
        break

    from epipack import StochasticEpiModel

    infection_rate = 1.0
    recovery_rate = 0.2
    model = StochasticEpiModel(["S","I","R"],3)\
                .set_link_transmission_processes([
                        ("I", "S", infection_rate, "I", "I"),
                    ])\
                .set_node_transition_processes([
                        ("I", recovery_rate, "R"),
                    ])\
                .set_node_statuses([1,0,0])

    temporal_network = TemporalNetwork(3, edges, [0, 0.5, 1.2], 1.5)
    sim = TemporalNetworkSimulation(temporal_network, model)
    t, res = sim.simulate(100)
    print(t, res)
    sim.reset()
    print(sim.model.node_status)
    t, res = sim.simulate(100)
    print(t, res)

    import matplotlib.pyplot as pl
    from tqdm import tqdm
S, I, A, B, C0, C1, D, E, F = "S I A B C0 C1 D E F".split(" ")

rateA = 3.0
rateB = 2.0
rateE = 1.0

probAC0 = 0.2
probAC1 = 0.8

probBD = 0.2

N = 6
edges = [ (0, i, 1.0) for i in range(1,N) ]

model = StochasticEpiModel([S,I,A,B,C0,C1,D, E, F], N, edges)

model.set_node_transition_processes([
        (I, rateA, A),
        (I, rateB, B),
        (I, rateE, E),
    ])

model.set_conditional_link_transmission_processes({
    (I, "->", A) : [
            ( A, S, probAC0, A, C0),
            ( A, S, probAC1, A, C1),
        ],
    (I, "->", B): [
            ( B, S, probBD, B, D),
        ],
Beispiel #12
0
alpha = 1/5
rho = 1/8
eta = R0 * rho / k0
kappa = Q0/(1-Q0) * rho
chi = 1/2
xi = (1-Q0)/Q0 * chi
omega = 1/14

S, E, I, R, X, T_I, T_E, Q = "S E I R X T_I T_E Q".split(" ")

N = 20000

print("generating network")
edges = [(e[0],e[1],1.0) for e in (nx.fast_gnp_random_graph(N,k0/(N-1))).edges() ] 
agentmodel = StochasticEpiModel([S, E, I, R, X, T_I, T_E, Q], N, edges)
#model = StochasticEpiModel([S, E, I, R, X, T_I, T_E, Q], N, well_mixed_mean_contact_number=k0)

agentmodel.set_node_transition_processes([
        (E, alpha, I),
        (I, rho, R),
        (I, kappa, T_I),
        (T_I, chi, X),
        (T_E, xi, R),
        (T_E, chi, X),
        #(Q, omega, S),
    ])

agentmodel.set_link_transmission_processes([
        (I, S, R0*rho/k0, I, E),
    ])
Beispiel #13
0
import numpy as np
from epipack import StochasticEpiModel

S, S0, S1, I, A, B, C0, C1, D, E, F = "S S0 S1 I A B C0 C1 D E F".split(" ")

rateA = 3.0
rateB = 2.0
rateE = 1.0
rateF = 5.0
rateC = 10.0

N = 6
edges = [(0, i, 1.0) for i in range(1, N)]
edges.extend([(N + 1, 0, 1.0), (N, 0, 1.0), (N + 1, 1, 1.0), (N + 1, 2, 1.0)])

model = StochasticEpiModel([S, S0, S1, I, A, B, C0, C1, D, E, F], N + 2, edges)

model.set_node_transition_processes([
    (S0, rateC, E),
    (I, rateF, F),
])

model.set_link_transmission_processes([
    (S0, I, rateA, S0, A),
    (S0, I, rateB, S0, B),
    (S1, I, rateE, S1, E),
])

statuses = np.zeros(N + 2, dtype=int)
statuses[0] = model.get_compartment_id(I)
statuses[N] = model.get_compartment_id(S0)
Beispiel #14
0
if __name__ == "__main__":
    import netwulf as nw
    from epipack import StochasticEpiModel
    import networkx as nx

    N = 301 * 299
    network = get_grid_layout(N)

    edge_list = [(link['source'], link['target'], 1.0)
                 for link in network['links']]
    k0 = 25

    model = StochasticEpiModel(
        list("SIRXTQ"),
        N=N,
        well_mixed_mean_contact_number=k0,
    )
    Reff = 3
    R0 = 3
    recovery_rate = 1 / 8
    quarantine_rate = 1 / 32
    tracing_rate = 1 / 2
    waning_immunity_rate = 1 / 14
    infection_rate = Reff * (recovery_rate + quarantine_rate) / k0
    infection_rate = R0 * (recovery_rate) / k0
    model.set_node_transition_processes([
        ("I", recovery_rate, "R"),
        ("I", quarantine_rate, "T"),
        ("T", tracing_rate, "X"),
        ("Q", waning_immunity_rate, "S"),
Beispiel #15
0
        ('A', 'S', 0.5 * infection_rate * 0.7, 'A', 'I'),
        ('A', 'S', 0.5 * infection_rate * 0.3, 'A', 'A'),
    ]

    conditional_transmission = {
        ('I', '->', 'X'): [
            ('X', 'I', p, 'X', 'X'),
        ]
    }

    model = StochasticEpiModel(
               compartments=compartments,
               N=N,
               edge_weight_tuples=edges
               )\
           .set_link_transmission_processes(link_transmission)\
           .set_node_transition_processes(node_transition)\
           .set_conditional_link_transmission_processes(conditional_transmission)\
           .set_random_initial_conditions({
                                           'S': N-100,
                                           'I': 100
                                          })

    t, result = model.simulate(100)

    from epipack.plottools import plot
    from bfmplot import pl

    ax = plot(t, result)
    ax.set_yscale('log')
    ax.set_ylim([1, N])
    ax.set_ylim([1, N])
Beispiel #16
0
from epipack import StochasticEpiModel
import numpy as np

if __name__ == "__main__":
    N = 3
    edge_weight_tuples = [
        (0, 1, 1 / 3),
        (0, 2, 2 / 3),
    ]
    directed = False

    S, I, R = list("SIR")

    model = StochasticEpiModel(
        compartments=[S, I, R],
        N=N,
        edge_weight_tuples=edge_weight_tuples,
        directed=directed,
    )

    infection_rate = 3.0
    model.set_link_transmission_processes([
        ('I', 'S', infection_rate, 'I', 'I'),
    ])

    recovery_rate = 2.0
    model.set_node_transition_processes([
        ('I', recovery_rate, 'R'),
    ])

    model.set_random_initial_conditions({S: N - 1, I: 1})