<jupyter_start><jupyter_text>Simulative approach to calculate SIR curves<jupyter_code>SIR=np.array([S0,I0,R0])
propagation_rates=pd.DataFrame(columns={'susceptible':S0,
                                        'infected':I0,
                                        'recoverd':R0})



for each_t in np.arange(100):
   
    new_delta_vec=SIR_model(SIR,beta,gamma)
   
    SIR=SIR+new_delta_vec
    
    propagation_rates=propagation_rates.append({'susceptible':SIR[0],
                                                'infected':SIR[1],
                                                'recovered':SIR[2]}, ignore_index=True)

fig, ax1 = plt.subplots(1, 1)

ax1.plot(propagation_rates.index,propagation_rates.infected,label='infected',color='k')
ax1.plot(propagation_rates.index,propagation_rates.recovered,label='recovered')
ax1.plot(propagation_rates.index,propagation_rates.susceptible,label='susceptible')

ax1.set_ylim(10,1000000)
ax1.set_yscale('linear')
ax1.set_title('Szenario SIR simulations  (demonstration purposes only)',size=16)
ax1.set_xlabel('time in days',size=16)
ax1.legend(loc='best',
           prop={'size': 16});<jupyter_output><empty_output><jupyter_text>Fitting the parameters of SIR model<jupyter_code>ydata = np.array(df_data.Spain[35:])
t=np.arange(len(ydata))
# ensure re-initialization 
I0=ydata[0]
S0=N0-I0
R0=0
def SIR_model_t(SIR,t,beta,gamma):
    ''' Simple SIR model
        S: susceptible population
        t: time step, mandatory for integral.odeint
        I: infected people
        R: recovered people
        beta: 
        
        overall condition is that the sum of changes (differnces) sum up to 0
        dS+dI+dR=0
        S+I+R= N (constant size of population)
    
    '''
    
    S,I,R=SIR
    dS_dt=-beta*S*I/N0          #S*I is the 
    dI_dt=beta*S*I/N0-gamma*I
    dR_dt=gamma*I
    return dS_dt,dI_dt,dR_dt
def fit_odeint(t, beta, gamma):
    '''
    helper function for the integration
    '''
    return integrate.odeint(SIR_model_t, (S0, I0, R0), t, args=(beta, gamma))[:,1] # we only would like to get dI
# example curve of our differential equationa
popt=[0.4,0.1]
fit_odeint(t, *popt)
# the resulting curve has to be fitted
# free parameters are here beta and gamma
popt, pcov = optimize.curve_fit(fit_odeint, t, ydata)
perr = np.sqrt(np.diag(pcov))
    
print('standard deviation errors : ',str(perr), ' start infect:',ydata[0])
print("Optimal parameters: beta =", popt[0], " and gamma = ", popt[1])


# get the final fitted curve
fitted=fit_odeint(t, *popt)
fitted
plt.semilogy(t, ydata, 'o')
plt.semilogy(t, fitted)
plt.title("Fit of SIR model for Italy cases")
plt.ylabel("Population infected")
plt.xlabel("Days")
plt.show()
print("Optimal parameters: beta =", popt[0], " and gamma = ", popt[1])
print("Basic Reproduction Number R0 " , popt[0]/ popt[1])
print("This ratio is derived as the expected number of new infections (these new infections are sometimes called secondary infections from a single infection in a population where all subjects are susceptible. @wiki")<jupyter_output><empty_output><jupyter_text>Fitting SIR curve for all top 100 countries<jupyter_code>df_data=pd.read_csv('../data/processed/COVID_full_flat_table.csv',sep=';') 
df_pop=pd.read_csv('../data/processed/world_population.csv',sep=";")  

df_data=df_data.iloc[60:,:] #removing first 50 days of covid spread as the data is inconsistent
df_data=df_data.drop(['Taiwan*'], axis= 1) # dropping taiwan as the data is inconsistent
df_data=df_data.reset_index()
df_data=df_data.drop(['index'], axis=1)
df_data=df_data.rename(columns={'level_0':'index'})
df_data=df_data.reset_index()
df_data=df_data.drop(['index'], axis=1)
df_data=df_data.rename(columns={'level_0':'index'})
    
    
df= pd.DataFrame(df_data.loc[0])
df=df.reset_index()
df = df.iloc[1:]
country_list= list(df[df[0]>38]['index']) #finding countries with significant number of covid cases i.e,>38
country_list.insert(0, 'Date')
df_data=df_data[country_list] # confining data frame to that perticular countries
    
for each in country_list[1:]:
        ydata = np.array(df_data[each])
        t=np.arange(len(ydata))
        N0= df_pop[df_pop['country']== each]['population']
        I0=ydata[0]
        S0 = N0-I0
        R0=0
        popt, pcov = optimize.curve_fit(fit_odeint, t, ydata)
        perr = np.sqrt(np.diag(pcov))
        fitted = fit_odeint(t, *popt).reshape((-1,1))
        df_data[each+'_SIR']= fitted
    
df_data.to_csv('../data/processed/COVID_SIR_model.csv',sep=';',index=False)<jupyter_output><empty_output><jupyter_text>Dynamic beta in SIR (infection rate)<jupyter_code>df_data=pd.read_csv('../data/processed/COVID_full_flat_table.csv',sep=';') 
df_pop=pd.read_csv('../data/processed/world_population.csv',sep=";")  
ydata = np.array(df_data.Spain[35:])
t=np.arange(len(ydata))
t_initial=30
t_intro_measures=10
t_hold=50
t_relax=30

beta_max=0.4
beta_min=0.1
gamma=0.1
pd_beta=np.concatenate((np.array(t_initial*[beta_max]),
                       np.linspace(beta_max,beta_min,t_intro_measures),
                       np.array(t_hold*[beta_min]),
                        np.linspace(beta_min,beta_max,t_relax),
                       ))




pd_beta
SIR=np.array([S0,I0,R0])
propagation_rates=pd.DataFrame(columns={'susceptible':S0,
                                        'infected':I0,
                                        'recoverd':R0})



for each_beta in pd_beta:
   
    new_delta_vec=SIR_model(SIR,each_beta,gamma)
   
    SIR=SIR+new_delta_vec
    
    propagation_rates=propagation_rates.append({'susceptible':SIR[0],
                                                'infected':SIR[1],
                                                'recovered':SIR[2]}, ignore_index=True)
fig, ax1 = plt.subplots(1, 1)

ax1.plot(propagation_rates.index,propagation_rates.infected,label='infected',linewidth=3)

t_phases=np.array([t_initial,t_intro_measures,t_hold,t_relax]).cumsum()
ax1.bar(np.arange(len(ydata)),ydata, width=0.8,label=' current infected Spain',color='r')
ax1.axvspan(0,t_phases[0], facecolor='b', alpha=0.2,label='no measures')
ax1.axvspan(t_phases[0],t_phases[1], facecolor='b', alpha=0.3,label='hard measures introduced')
ax1.axvspan(t_phases[1],t_phases[2], facecolor='b', alpha=0.4,label='hold measures')
ax1.axvspan(t_phases[2],t_phases[3], facecolor='b', alpha=0.5,label='relax measures')
ax1.axvspan(t_phases[3],len(propagation_rates.infected), facecolor='b', alpha=0.6,label='repead hard measures')

ax1.set_ylim(10, 100*max(propagation_rates.infected))
ax1.set_yscale('log')
ax1.set_title('Szenario SIR simulations  (demonstration purposes only)',size=16)
ax1.set_xlabel('time in days',size=16)
ax1.legend(loc='best',
           prop={'size': 16});<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14459800861940852, 'fraction_numerical': 0.02541239411502452, 'mean_word_length': 3.8803480783176214, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 19, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 12, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '4', 'dir': 'jupyter-structured-clean-dedup', 'id': '378886', 'license': 'FTL', 'n_tokens_mistral': 2587, 'n_tokens_neox': 2434, 'n_words': 413, 'path': 'notebooks/Step.4 Modeling_spread_SIR_part-3.ipynb', 'repo_name': 'sohailsameer1994/EDS_COVID_-19-20-', 'size': '6729'}