def sin_test(n=8,text_position='start'): """Test the stuff from the modules""" from bfmplot import pl import bfmplot as bp import numpy as np #bp.set_color_cycle(bp.cccs_colors) #pl.figure(figsize=bp.phys_rev_column()) pl.figure(figsize=bp.golden_ratio(5)) x = np.linspace(1,5*np.pi,100) for i in range(n): pl.plot(x, 1-np.sin(x[::-1]/np.sqrt(i+1)), marker=bp.markers[i],mfc='w',label='$i=%d$'%i) bp.strip_axis(pl.gca()) leg = pl.legend() bp.align_legend_right(leg) bp.arrow(pl.gca(), r'$i$', (3, 1.8), (6, 0.8), text_position=text_position) pl.xlabel('hello') pl.ylabel('hello') bp.set_n_ticks(pl.gca(), 3, 2) #pl.xscale('log') pl.gcf().tight_layout()
def sin_test(n=8,text_position='start'): pl.figure(figsize=bp.golden_ratio(5)) x = np.linspace(0,5*np.pi,100) for i in range(n): pl.plot(x, 1-np.sin(x[::-1]/np.sqrt(i+1)), marker=bp.markers[i],mfc='w',label='$i=%d$'%i) bp.strip_axis(pl.gca()) leg = pl.legend() bp.align_legend_right(leg) bp.arrow(pl.gca(), r'$i$', (14, 0.8), (10, 0.15), text_position=text_position, rad=0.3) pl.xlabel('this is the x-label') pl.ylabel('this is the y-label') pl.gcf().tight_layout()
def sin_test(n=8, text_position='start', with_legend=True): pl.figure(figsize=bp.golden_ratio(5)) x = np.linspace(0, 5 * np.pi, 100) for i in range(n): pl.plot(x, 1 - np.sin(x[::-1] / np.sqrt(i + 1)), marker=bp.markers[i], mfc='w', label='$i=%d$' % i) bp.strip_axis(pl.gca()) if with_legend: leg = pl.legend() bp.align_legend_right(leg) pl.xlabel('this is the x-label') pl.ylabel('this is the y-label') pl.gca().set_title(name) pl.gcf().tight_layout()
}) print(agentmodel.conditional_link_transmission_events) agentmodel.set_random_initial_conditions({ S: N - int(0.01*N), I: int(0.005*N), E: int(0.005*N), }) print("simulating") t, result = agentmodel.simulate(800) from bfmplot import pl for c, res in result.items(): pl.plot(t, res,label=c) model = EpiModel([S, E, I, R, X, T_I, T_E, Q],N) model.add_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), ]) model.add_transmission_processes([
t = solve_t(np.mean(k), n) rho = solve_rho(np.mean(k), np.mean(k**2), n) ax = fig.add_subplot(1, 3, 1) pl.hist(k, bins=np.arange(0, kmax, 2), density=True, alpha=1, align='left', color=bp.brewer_qualitative[1], label='data', histtype='step') p = pk(n, t, rho, kmax, X, W) pl.plot(np.arange(kmax), p, lw=1, c=bp.brewer_qualitative[2], label='model fit') pl.xlim(0, 30) ax.text(0.04, 0.95, '(a)', va='top', ha='left', transform=ax.transAxes) bp.strip_axis(ax) leg = pl.legend() bp.align_legend_right(leg) ax.set_ylabel('probability density $p_k$') ax.set_xlabel('node degree $k$') #pl.show() #sys.exit(0) ### collab network print("loading", 'degree_sequences/cond-mat.degree_sequence', '...')
dtype=float), np.array(self.cascade_size, dtype=float) / self.N if __name__ == "__main__": from sixdegrees.utils import to_networkx_graph from sixdegrees import small_world_network, modular_hierarchical_network import sixdegrees as sixd from bfmplot import pl import netwulf B = 10 L = 3 N = B**L k = 10 mu = -0.8 thresholds = [0.1] * N initially_infected = np.arange(10) #G = to_networkx_graph(*modular_hierarchical_network(B,L,k,mu)) G = to_networkx_graph(*sixd.random_geometric_kleinberg_network(N, k, mu)) Thresh = ThreshModel(G, initially_infected, thresholds) t, a = Thresh.simulate() pl.plot(t, a) pl.ylim([0, 1]) pl.show()
x = np.arange(1, max(k1pos)) a0 = 2.30753 a1 = 0.27061 b1 = 0.9929 fac = (a1 - a0 * b1 - 1) s = np.sqrt(2 * x / (N - 1)) s = np.sqrt(np.log(1 / (1 - x / (N - 1))**2)) #pl.plot(x, 1/(N-1)*np.sqrt((1-covariance)/covariance) * np.exp(-t**2/2/covariance+np.sqrt(2)*t*a0)* np.exp(np.sqrt(2)*fac*t*np.sqrt(2*x/(N-1)))) #pl.plot(x, 1/(N-1)*np.sqrt((1-covariance)/covariance) * np.exp(-t**2/2/covariance+np.sqrt(2)*t*a0)* np.exp(-np.sqrt(2)*fac*t*s)) #pl.plot(x, 1/(N-1)*np.sqrt((1-covariance)/covariance) * np.exp(-t**2/2/covariance)*\ # np.exp(-fac*np.sqrt(2*np.log((N-1)/x))) # ) rho = covariance prefac = 1 / (N - 1) * np.sqrt((1 - rho) / rho) * np.exp(-t**2 / 2 / rho) pl.plot(x, pk(x, N, t, covariance), label='asymptotic solution Eq. (29)') pl.plot(x, 1 / x**(np.sqrt(2)) * 0.1, label='$1/k^{\sqrt{2}}$') #pl.plot(x, prefac*np.exp(np.sqrt(2)*t*1/(x/(N-1))**0.5/3.25),label='stretched exponential') pl.plot(x, prefac * np.exp(np.sqrt(2) * t * np.sqrt(2 * np.log( (N - 1) / x))) / 15, label='mu log') pl.legend() pl.xscale('log') pl.yscale('log') pl.xlabel('degree $k$') pl.ylabel('probability') fig.tight_layout()
zorder=-1000, ) ax[i].text(0.7, 0.03, titlemap[province], transform=ax[i].transAxes, ha='right', va='bottom', bbox={ 'facecolor': 'w', 'edgecolor': 'w', 'pad': 0 }) pl.plot(t, cases, marker=markers[i + 2], c=colors[i + 2], label='data', mfc='None') pl.plot(tt, f(tt, *p), c='k', lw=1, label='$Q_I$') _c = i % (n_col) _r = i // (n_col) if _r == n_row - 1: pl.xlabel('days since Jan. 20th') if _c == 0 and _r == 0: pl.ylabel('confirmed cases', ) pl.gca().yaxis.set_label_coords(-0.3, -0.2) pl.xlim([1, 30]) pl.xscale('log') pl.yscale('log')
tt2 = tt[tt > tswitch] result = model.SIRX( tt, cases[0], params['eta'], params['rho'], params['kappa'], params['kappa0'], N, params['I0_factor'], ) X = result[2, :] * N I = result[1, :] * N #S = result[0,:]*N pl.plot(t, cases, marker=markers[i], c=colors[i], label='data', mfc='None') pl.plot(t2, cases2, marker=markers[i], c='grey', label='data', mfc='None') pl.plot(tt1, X[tt <= tswitch], '-', c='k', label='$Q_I$ (detected and quarantined)') pl.plot(tt2, X[tt > tswitch], '-.', c='k', label='$Q_I$ (detected and quarantined)') pl.plot(tt, I, '--', c=colors[2], lw=1.5, label='$I$ (undected infected)') #pl.plot(tt, S,label='model')
rho = np.linspace(0, 0.5, 200) k = 2**np.arange(0, 10, 2) k = np.array(k, dtype=float) variances = np.zeros((200, 5)) for i in range(200): for j in range(5): t = solve_t(k[j], n) variances[i, j] = variance(t, rho[i], n, NMAX) fig = plt.figure(2, figsize=(6, 6)) ax = fig.add_subplot(1, 1, 1) plt.xlabel(r'$\rho$', size=16) plt.ylabel(r'Var[k]', size=14) for i in range(5): plt.plot(rho, variances[:, i], label=r'$k=$' + str(k[i])) ax.set_yscale('log') #ax.set_xscale('log') plt.legend(loc=4) plt.savefig('figures/variance.pdf') ### triangle plots n = 10**5 NMAX = 20 # increase this if needed k = 10**np.linspace(0, 4.99, 20) rho = np.linspace(0, 0.5, 6) triangle_density = np.zeros((20, 6))
import numpy as np from scipy.interpolate import interp1d from bfmplot import pl import bfmplot as bp x = np.linspace(0, 6, 9) y = 2 + np.sin(x) x2 = np.linspace(0, 6, 1000) for _x, _y in zip(x, y): print(_x, _y) interp_modes = ['zero', 'linear', 'nearest', 'quadratic'] pl.figure() pl.plot(x, y, 's', label='data') for kind in interp_modes: f = interp1d(x, y, kind=kind) pl.plot(x2, f(x2), label=kind) pl.legend() bp.strip_axis(pl.gca()) pl.xlabel('time') pl.ylabel('value') pl.gcf().tight_layout() pl.show()
model.set_processes(quadratic_processes + linear_processes) initial_conditions = {(node, "S"): 1.0 for node in nodes} initial_conditions[(nodes[0], "S")] = 0.8 initial_conditions[(nodes[0], "I")] = 0.2 model.set_initial_conditions(initial_conditions, allow_nonzero_column_sums=True) # set compartments for which you want to obtain the # result plot_compartments = [(node, "I") for node in nodes] # integrate import numpy as np t = np.linspace(0, 12, 1000) result = model.integrate(t, return_compartments=plot_compartments) # plot result from bfmplot import pl as plt plt.figure() for (node, _), concentration in result.items(): plt.plot(t, concentration, label='node: ' + str(node)) plt.xlabel("time") plt.ylabel("I") plt.legend() plt.gcf().tight_layout() plt.gcf().savefig("chain_I.png", dpi=300) plt.show()
tau_new = [] N_meas = 10000 for meas in tqdm(range(N_meas)): tau_con.append(conservative_method(t0, y0)) tau_new.append(new_method(t0, y0)) from bfmplot import pl from scipy.integrate import cumtrapz pl.hist(tau_con, bins=200, density=True, histtype='step') pl.hist(tau_new, bins=200, density=True, histtype='step') t = np.linspace(0, 120, 1000) lamb = np.array([get_event_rates(_t, y0).sum() for _t in t]) integral = cumtrapz(lamb, x=t, initial=0) p = lamb * np.exp(-integral) pl.plot(t, p) pl.xlabel('tau') pl.ylabel('pdf') #pl.yscale('log') pl.gcf().tight_layout() pl.figure() pl.plot(*cum_hist(tau_con)) pl.plot(*cum_hist(tau_new)) pl.plot(t, np.exp(-integral)) pl.ylabel('P(t>tau)') pl.xlabel('tau') #pl.yscale('log') pl.gcf().tight_layout()
model.set_processes([ (S, I, alpha, I, I), (I, beta, R), (None, gamma, S), (None, 1e-3, I), ]) model.set_initial_conditions({S: N - I0, I: I0}) t, result_sim = model.simulate(4000) from bfmplot import pl import bfmplot as bp for iC, (C, res) in enumerate(result_sim.items()): pl.plot(t, res, label=C, lw=1.5, c=bp.colors[iC]) model.set_processes([ (S, I, alpha, I, I), (I, beta, R), (None, gamma, S), ]) result = model.integrate(t) for iC, (C, res) in enumerate(result.items()): pl.plot(t, res, c=bp.colors[iC], ls='-.') bp.strip_axis(pl.gca()) pl.xlim([0, 150]) pl.ylim([0, 1000])
initial_conditions = {(node, "S"): 1.0 for node in range(N)} initial_conditions[(0, "S")] = 0.99 initial_conditions[(0, "I")] = 0.01 model.set_initial_conditions(initial_conditions, allow_nonzero_column_sums=True) t = np.linspace(0, 20, 100) from bfmplot import pl return_compartments = [(node, "I") for node in range(N)] print("integrate") result = model.integrate_and_return_by_index( t, return_compartments=return_compartments, ) print("plot") pl.figure() for iC, C in enumerate(return_compartments): pl.plot(t, result[iC, :]) end = time() print("needed", end - start, "seconds") pl.show()
pl.sca(ax[i]) tt = np.logspace(np.log(t[0]), np.log(35), base=np.exp(1)) result = model.SIRX(tt, cases[0], params['eta'], params['rho'], params['kappa'], params['kappa0'], N, params['I0_factor'], ) X = result[2,:]*N I = result[1,:]*N #S = result[0,:]*N pl.plot(t, cases,marker=markers[i],c=colors[i],label='data',mfc='None') pl.plot(tt, X,c='k',label='$Q_I$ (detected and quarantined)') pl.plot(tt, I,'--',c=colors[2],lw=1.5,label='$I$ (undected infected)') #pl.plot(tt, S,label='model') _c = i % n_col _r = i // n_col if _r == n_row-1: pl.xlabel('days since Jan. 21st') if _c == 0: pl.ylabel('confirmed') #pl.title(titlemap[province]) ax[i].text(0.03,0.97, "{}.{}".format(letter[_r], roman[_c]), transform=ax[i].transAxes,
set_lims[_ax](Ticks.lim) set_ticks[_ax](Ticks.ticks) if __name__ == "__main__": import numpy as np import bfmplot as bp fig, ax = pl.subplots(1, 1) x = np.linspace(1, 10, 100) mus = np.linspace(1, 4, 4) for mu in mus: y = x**mu pl.plot(x, y, c=bp.brewer_qualitative[0]) #pl.xscale('log') bp.strip_axis(ax, horizontal='left') pl.yscale('log') ax.set_xlabel('x') ax.set_ylabel('y') pl.gcf().tight_layout() pl.xlim([1, 10]) for mu in mus: label = r'$\mu={:d}$'.format(int(mu)) y = x**mu add_curve_label(ax, x, y, label, label_pos_rel=0.5 + mu / 50)
expected_counts[model.get_compartment_id(C0)] = N_measurements * ((N-1)*rateA / (rateB + rateE + rateA) * probAC0) expected_counts[model.get_compartment_id(C1)] = N_measurements * ((N-1)*rateA / (rateB + rateE + rateA) * probAC1) expected_counts[model.get_compartment_id(D)] = N_measurements * ((N-1)*rateB / (rateB + rateE + rateA) * probBD) expected_counts[model.get_compartment_id(F)] = (N-1) * expected_counts[model.get_compartment_id(E)] expected_counts[model.get_compartment_id(S)] = N_measurements * N - expected_counts.sum() pl.bar(x+width/2, expected_counts, width) pl.xticks(x) pl.gca().set_xticklabels(model.compartments) pl.figure() ndx = np.where(expected_counts==0) counts[ndx] = 1 expected_counts[ndx] = 1 pl.plot(x, np.abs(1-counts/expected_counts)) from scipy.stats import entropy _counts = np.delete(counts,1) _exp_counts = np.delete(expected_counts,1) print(entropy(_counts, _exp_counts)) pl.show()
import bfmplot as bp data = np.array([ (0.0, 2.00), (0.75, 2.68), (1.5, 3.00), (2.25, 2.78), (3.0, 2.14), (3.75, 1.43), (4.5, 1.02), (5.25, 1.14), (6.0, 1.72), ]) times, rates = data[:, 0], data[:, 1] x2 = np.linspace(times[0], times[-1], 1000) interp_modes = ['zero', 'linear', 'nearest', 'quadratic'] pl.figure() pl.plot(times, rates, 's', label='data') for kind in interp_modes: f = interp1d(times, rates, kind=kind) pl.plot(x2, f(x2), label=kind) pl.legend(frameon=False) bp.strip_axis(pl.gca()) pl.xlabel('time') pl.ylabel('value') pl.gcf().tight_layout() pl.gcf().savefig('interp1d.png', dpi=300) pl.show()
(I, rho, None), ]) model.set_initial_conditions({ S: 190, I: 10, }) model.set_parameter_values({ eta: 4, rho: 1, }) def print_status(): print(model.t0/50*100) t, result = model.simulate(50,sampling_dt=0.1,sampling_callback=print_status) pl.plot(t, result[S],label='S') pl.plot(t, result[I],label='I') model.set_initial_conditions({ S: 190, I: 10, }) #tt = np.linspace(0,100,1000) tt = t result = model.integrate(tt) pl.plot(tt, result[S],label='S') pl.plot(tt, result[I],label='I') pl.show()
(I, quarantine_rate, Q), ]) I0 = 0.01 model.set_initial_conditions({S: 1 - I0, I: I0}) import numpy as np from bfmplot import pl as plt import bfmplot as bp t = np.linspace(0, 100, 1000) result = model.integrate(t) plt.figure() for compartment, incidence in result.items(): plt.plot(t, incidence, label=compartment) plt.xlabel('time [days]') plt.ylabel('incidence') plt.legend() bp.strip_axis(plt.gca()) plt.gcf().tight_layout() plt.savefig('SEIRQ.png', dpi=300) N = 1000 I0 = 100 model = epk.EpiModel([S, E, I, R, Q], initial_population_size=N) model.set_processes([ (S, I, infection_rate, E, I),
N = 200000 tmax = 50 model = EpiModel([S,E,I,R],N) model.set_processes([ ( S, I, 2, E, I ), ( I, 1, R), ( E, 1, I), ]) model.set_initial_conditions({S: N-100, I: 100}) tt = np.linspace(0,tmax,10000) 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 ), ])
params['kappa0'], N, params['I0_factor'], ) X = result[2,:]*N I = result[1,:]*N imax = np.argmax(I) print(imax) max_date = tt_dates[imax] max_tt = tt[imax] print(max_date) #S = result[0,:]*N pl.plot(t, cases,marker=markers[i+2],c=colors[i+2],label='data',mfc='None') pl.plot(t2, cases2,marker='o',ms=5,c='grey',label='data',mfc='None') pl.plot(tt, X,'-',c='k') #pl.plot(tt1, X[tt<=tswitch],'-',c='k') #pl.plot(tt2, X[tt>tswitch],'-',c='k') pl.plot(tt, I,'--',c=colors[2],lw=1.5) pl.plot([max_tt]*2, [0,max_dates_pos[i]],':',c=colors[0],lw=1.5) pl.text(max_tt-1, max_dates_pos[i], max_dates[i], transform=ax[i].transData, ha='left', va=max_dates_va[i], color=colors[0], fontsize=9, bbox={'facecolor':'w','edgecolor':'w','pad':0} ) ax[i].plot([22.5,22.5], [0,cases[-1]],':',c=colors[0],lw=1.5)
}) print(model.conditional_link_transmission_events) model.set_random_initial_conditions({"S": N - I0, "I": I0}) print(model.node_and_link_events) start = time() t, result = model.simulate(300, sampling_dt=1) end = time() print("simulation took", end - start, "seconds") from bfmplot import pl for comp, series in result.items(): pl.plot(t, series, label=comp) kw = { 'R0': R0, 'Q0': Q0, 'k0': k0, 'I0': I0 / N, 'waning_quarantine_rate': waning_quarantine_rate, 'recovery_rate': recovery_rate, 'infection_rate': infection_rate, 'app_participation_ratio': 1.0, 't': t, } t, result = mean_field_SIRX_tracing(kw)
if i == 0: _d = 7 else: _d = 4 pexp, _ = curve_fit(fexp, _t[_t <= _d], _cases[_t <= _d], [1, 1.]) print("pexp =", pexp) print(p) tt = np.logspace(np.log(t[0]), np.log(t[-1]), base=np.exp(1)) pl.sca(ax[i]) growth_rate = (6.2 - 1) / 8 pl.plot(t, cases, marker=markers[i], c=colors[i], label='data', mfc='None') pl.plot(tt, f(tt, *p), c='k', lw=1, label='$Q_I$') pl.plot(tt, fexp(tt, growth_rate * 1.1, _cases[0] * 2.3), c=colors[2], lw=1, label='$Q_I$', ls='--') _c = i % (n_col) _r = i // (n_col) if _r == n_row - 1: pl.xlabel('days since Jan. 20th') if _c == 0 and _r == 0: pass #pl.ylabel('confirmed cases',)
k = 2**np.arange(0, 10, 2) k = np.array(k, dtype=float) if not data_exists: variances = np.zeros((len(rho), len(k))) for i in range(len(rho)): for j in range(len(k)): t = solve_t(k[j], n) variances[i, j] = variance(t, rho[i], n, NMAX) fig, ax = pl.subplots(1, 1, figsize=(4, 2.5)) pl.xlabel(r'local edge weight correlation $\rho$') pl.ylabel(r'node degree variance $\mathrm{Var}(k)$') for i in range(len(k)): pl.plot(rho, variances[:, i], c=bp.brewer_qualitative[1]) bp.strip_axis(ax) ax.set_yscale('log') #ax.set_xscale('log') ax.set_xlim([0, 0.5]) fig.tight_layout() for i in range(len(k)): bp.add_curve_label(ax, rho, variances[:, i], r'$\left\langle k\right\rangle={:d}$'.format(int(k[i])), label_pos_rel=0.4) if not data_exists:
b = p['rho'].value a = p['eta'].value I0f = p['I0_factor'].value N = pdata['population'] / 1e6 print(p['kappa0'],p['kappa']) Q = (k+k0)/(b+k+k0) P = k0/(k+k0) R0eff = a / (b+k+k0) tabledata.append([titlemap[province], N, Q, P, R0eff, k, k0, I0f, ]) ks.append(k) k0s.append(k0) for i, (_k0, _ks) in enumerate(zip(k0s, ks)): pl.plot([_k0],[_ks],marker=markers[i],color=colors[i],markersize=7) pl.xlim([0,0.14]) pl.ylim([-.05,0.55]) pl.gcf().savefig('model_fit_figures/'+fn+'.png',dpi=300) pl.show() headers = [ 'Province', '$N/10^6$','$Q$', '$P$', '$R_{0,\mathrm{eff}}$', '$\kappa$ [$\mathrm{d}^{-1}$]', '$\kappa_{0}$ [$\mathrm{d}^{-1}$]', '$I_0/X_0$',