<jupyter_start><jupyter_text>**Data Fitting**Reads files raw data of growth, nucleation and lifetimes, then fits corresponding distribution and plots the mean obtained from the parameters.<jupyter_code>def gaussian(x, mu, sig):
    return (np.exp(-np.power(x - mu, 2.) / (2 * np.power(sig, 2.))) )/(sig*np.sqrt(2*np.pi))

def exponential(x, scale):
    return ((np.exp(-x/scale) )/(scale))

def gamma(x, shape, scale):
    return (np.power(x,shape-1)*np.exp(-x/ scale))/(sp.special.gamma(shape) * np.power(scale,shape))

name = ['growth','time2nuc','lifetime']
dataG = pd.read_csv(path/('joint_'+name[0]+'_'+jointdate+'.csv'),sep=',');
dataN = pd.read_csv(path/('joint_'+name[1]+'_'+jointdate+'.csv'),sep=',');
dataC = pd.read_csv(path/('joint_'+name[2]+'_'+jointdate+'.csv'),sep=',');
def gaussian_fit(data):
    r = {'[tub]':np.empty(0),'mu':np.empty(0) ,'sigma':np.empty(0)}
    results = pd.DataFrame(data=r)
    
    for i in list(data):
        y = data[i].dropna().values
        
        n, bins, patches = plt.hist(y, bins=np.arange(0, 3 + 0.05, 0.05), density=True);
        plt.clf()

        coeff, var_matrix = sp.optimize.curve_fit(gaussian,bins[:-1],n)
        
        variance = np.diagonal(var_matrix) #Refer [3]
        SE = np.sqrt(variance) #Refer [4]

#======Making a data frame========
        r = {'[tub]':[float(i),float(i)],'mu':[coeff[0],SE[0]],'sigma':[coeff[1],SE[1]]}
        results0 = pd.DataFrame(data=r, index=(['Value','SE']))
        results = pd.concat([results, results0], sort=False)
    
    return results

def exponential_fit(data):
    r = {'scale e':np.empty(0)}
    results = pd.DataFrame(data=r)
    
    for i in list(data):
        y = data[i].dropna().values
        
        n, bins, patches = plt.hist(y, bins=np.arange(0, 60 + 0.5, 0.5), density=True);
        plt.clf()

        coeff, var_matrix = sp.optimize.curve_fit(exponential,bins[:-1],n)
        
        variance = np.diagonal(var_matrix) #Refer [3]
        SE = np.sqrt(variance) #Refer [4]

#======Making a data frame========
        r = {'scale e':[coeff[0],SE[0]]}
        results0 = pd.DataFrame(data=r, index=(['Value','SE']))
        results = pd.concat([results, results0], sort=False)
    
    return results

def gamma_fit(data):
    r = {'shape':np.empty(0) ,'scale g':np.empty(0)}
    results = pd.DataFrame(data=r)
    
    for i in list(data):
        y = data[i].dropna().values
        
        n, bins, patches = plt.hist(y, bins=np.arange(0, 60 + 0.5, 0.5), density=True);
        plt.clf()

        coeff, var_matrix = sp.optimize.curve_fit(gamma,bins[:-1],n,[1.1,1])
        
        variance = np.diagonal(var_matrix) #Refer [3]
        SE = np.sqrt(variance) #Refer [4]

#======Making a data frame========
        r = {'shape':[coeff[0],SE[0]],'scale g':[coeff[1],SE[1]]}
        results0 = pd.DataFrame(data=r, index=(['Value','SE']))
        results = pd.concat([results, results0], sort=False)
    
    return results
fitdata = pd.concat([gaussian_fit(dataG), exponential_fit(dataN),gamma_fit(dataC)], axis=1, sort=False)
fitdata.to_csv(path.parents[0]/('joint_fitdata_'+jointdate+'.csv'), encoding='utf-8', index=True)
fitdata
font = {'family' : 'normal',
        'weight' : 'normal',
        'size'   : 17}
plt.rc('font', **font)

legnd0 = []
legnd1 = []
legnd2 = []

titles = ('Growth','Nucleation','Lifetime','Correlation')
xlables = ('Growth Rate ' r'$(\mu m / min)$','Time to Nucleate ' r'$(min)$','Lifetime ' r'$(min)$','Time to Nucleate ' r'$(min)$')

fig, axs = plt.subplots(1,3,figsize=(25,5))
fig.suptitle('Analysis of joint data'+micscp, fontsize=16)

for i in ['14','8']:#tub_concs:#['6']:#list(data):
    
    datos = dataG[i].dropna()
    mu0 = fitdata.loc[fitdata['[tub]'] == float(i)]['mu']['Value']
    sigma0 = fitdata.loc[fitdata['[tub]'] == float(i)]['sigma']['Value']
    n, bins, patches = axs[0].hist(datos, bins=np.arange(0, 2 + 0.05, 0.05), density=True, alpha=0.55);
    x = np.linspace(0, bins[-1], 100)
    axs[0].plot(x, sp.stats.norm.pdf(x,mu0,sigma0),'--', lw=3, alpha=0.85)
    legnd0 = legnd0 + [i+'uM, '+r'$\mu =$'+ str(round(mu0,3))+r', $\sigma =$'+ str(round(sigma0,3))]
    
    datos = dataN[i].dropna()
    scale0 = fitdata.loc[fitdata['[tub]'] == float(i)]['scale e']['Value']
    n, bins, patches = axs[1].hist(datos, bins=np.arange(0, 60 + 0.5, 0.5), density=True, alpha=0.55);
    x = np.linspace(0, bins[-1], 100)
    axs[1].plot(x, sp.stats.expon.pdf(x,0,scale0),'--', lw=3, alpha=0.85)
    legnd1 = legnd1 + [i+'uM, '+r'$\beta =$'+ str(round(scale0,3))]
    
    datos = dataC[i].dropna()
    shape0 = fitdata.loc[fitdata['[tub]'] == float(i)]['shape']['Value']
    scale0 = fitdata.loc[fitdata['[tub]'] == float(i)]['scale g']['Value']
    n, bins, patches = axs[2].hist(datos, bins=np.arange(0, 60 + 0.5, 0.5), density=True, alpha=0.55);
    x = np.linspace(0, bins[-1], 100)
    axs[2].plot(x, sp.stats.gamma.pdf(x, shape0, 0 , scale0),'--', lw=3, alpha=0.85)
    legnd2 = legnd2 + [i+'uM, '+r'$k =$'+ str(round(shape0,2))+r'$, \theta =$'+ str(round(scale0,3))+r'$, \mu =$'+ str(round(scale0*shape0,3))]

for j in np.arange(len(axs)):
    axs[j].set_ylabel('Relative Frequency')
    axs[j].set_xlabel(xlables[j])
    axs[j].set_title(titles[j]);
    axs[j].grid(True)

axs[0].legend(legnd0,loc='upper right')
axs[1].legend(legnd1,loc='upper right')
axs[2].legend(legnd2,loc='upper right')
plt.savefig(path.parents[0]/('joint_histogramsfit_'+jointdate+'.png'))
plt.savefig(path.parents[0]/('joint_histogramsfit_'+jointdate+'.pdf'))
plt.show()
titles = ('Growth','Nucleation','Lifetime','Correlation')
ylables = ('Growth Rate ' r'$(\mu m / min)$','Time to Nucleate ' r'$(min)$','Lifetime ' r'$(min)$','Lifetime ' r'$(min)$')

conc = fitdata['[tub]']['Value'].values
gamma_mu = np.multiply(fitdata['scale g']['Value'].values,fitdata['shape']['Value'].values)
gamma_muSE = np.add(np.multiply(fitdata['scale g']['Value'].values,fitdata['shape']['SE'].values),np.multiply(fitdata['scale g']['SE'].values,fitdata['shape']['Value'].values))

a1 , a0 = np.polyfit(conc, fitdata['mu']['Value'].values, 1)
y_int = -a0/a1
x_range = np.arange(0,17,0.1)
 
plt.figure(figsize=(30,5))
plt.suptitle('Analysis of '+micscp+' FITTED data', fontsize=16)

plt.subplot(1,4,1)
plt.errorbar(conc, fitdata['mu']['Value'].values, yerr=fitdata['sigma']['Value'].values, fmt='o')
plt.plot(x_range, a1*x_range+a0)
plt.ylim(0,2.5)
plt.legend(('Linear Fit:  'r'$K_a$'' = %.2f 'r'$\frac{dimers}{\mu M \; s}$''\n 'r'$C_c$'' = %.2f 'r'$\mu M$' %(a1*27.1, y_int),'Mean from Parameters'),loc='upper left')

plt.subplot(1,4,2)
plt.errorbar(conc, fitdata['scale e']['Value'].values, yerr=fitdata['scale e']['SE'].values, fmt='o')
plt.ylim(0,12)
plt.legend(( 'Mean from Parameters',r'$\sigma$'),loc='upper left')

plt.subplot(1,4,3)
plt.errorbar(conc, gamma_mu, yerr=gamma_muSE, fmt='o')
plt.ylim(0,12)
plt.legend(('Mean from Parameters', r'$\sigma$'),loc='upper left')

plt.subplot(1,4,4)
plt.errorbar( fitdata['scale e']['Value'].values,gamma_mu, yerr=gamma_muSE , xerr=fitdata['scale e']['SE'].values, fmt='o')
plt.ylim(0,12)
plt.legend(('Mean from Parameters', r'$\sigma$'),loc='upper right')


for i in [0,1,2,3] :
    plt.subplot(1,4,i+1)
    plt.xlabel('[Tub] ' r'$(\mu M)$')
    plt.ylabel(ylables[i])
    plt.title(titles[i]);
    plt.xlim(0,16)
    plt.grid(True)

plt.xlabel('Time to Nucleate ' r'$(min)$') 
plt.xlim(0,12)
plt.savefig(path.parents[0]/('joint_graphsFit_'+jointdate+'.png'))
plt.savefig(path.parents[0]/('joint_graphsFit_'+jointdate+'.pdf'))<jupyter_output>C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\figure.py:98: MatplotlibDeprecationWarning: 
Adding an axes using the same arguments as a previous axes currently reuses the earlier instance.  In a future version, a new instance will always be created and returned.  Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.
  "Adding an axes using the same arguments as a previous axes "
C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\figure.py:98: MatplotlibDeprecationWarning: 
Adding an axes using the same arguments as a previous axes currently reuses the earlier instance.  In a future version, a new instance will always be created and returned.  Meanwhile, this warning can be suppressed, and the future behavior ensured, by passing a unique label to each axes instance.
  "Adding an axes using the same arguments as a previous axes "
C:\ProgramData\Anaconda3\lib\site-packages\matplotlib\figure.py:98: Matplotlib[...]
{'fraction_non_alphanumeric': 0.22003514938488578, 'fraction_numerical': 0.03022847100175747, 'mean_word_length': 4.464788732394366, 'pattern_counts': {'":': 0, '<': 4, '<?xml version=': 0, '>': 4, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '566936', 'license': 'MIT', 'n_tokens_mistral': 3494, 'n_tokens_neox': 3302, 'n_words': 616, 'path': 'notebooks/Sofia/Past Version/2019-GRC/join_data_and_fit.ipynb', 'repo_name': 'brouhardlab/brouhardlab-scripts', 'size': '8535'}