def continuous(save = False, name = 'img/parameters/incubation.png'): """Plot incubation period distributions. After call, use `plt.show()` to show the figure. Args: save (bool, optional): Whether to save the figure, defaultly not. name (str, optional): Path to save the plot to. """ def _pars(a,b): return '%.3f,%.3f' % (a,b) # grid xgrid = np.linspace(0, 14, 1000) # distributions distr = continuous() lognorm_pdf = lognorm.pdf(xgrid, *distr['lognorm']) gamma_pdf = gamma.pdf(xgrid, *distr['gamma']) weibull_pdf = weibull.pdf(xgrid, *distr['weibull']) erlang_pdf = erlang.pdf(xgrid, *distr['erlang']) # plot fig1, ax1 = plt.subplots() ax1.plot(xgrid, lognorm_pdf, label=f"LN({_pars(np.log(distr['lognorm'][2]),distr['lognorm'][0])}^2)")#'LN(1.621,0.418)') ax1.plot(xgrid, gamma_pdf, label=f"Gamma({_pars(distr['gamma'][0],1/distr['gamma'][2])})") ax1.plot(xgrid, weibull_pdf, label=f"W({_pars(*distr['weibull'])})") ax1.plot(xgrid, erlang_pdf, label=f"E({_pars(distr['erlang'][0],distr['erlang'][2])})") ax1.set_xlabel('Incubation period') ax1.set_ylabel('Density') ax1.legend() if save: fig1.savefig(name)
def _pdf(self, value: float): """ Defines the K-Erlang distribution :param value: :return: Function value at point x """ if self._research_mode: return erlang.pdf(value, a=self._k, scale=1 / self.rate) else: if value >= 0: return math.pow(self.rate * value, self.k - 1) / (math.factorial(self.k - 1)) \ * self.rate * math.exp(-self.rate * value) else: return 0
def update_custom_data(attrname, old, new): xmin, xmax = slider_cust_xminmax.value k = slider_cust_k.value teta = slider_cust_teta.value x = np.linspace(xmin, xmax, d_N) y_cust_pdf = erlang.pdf(x, a=k, scale=teta) y_cust_cdf = erlang.cdf(x, a=k, scale=teta) data_custom = { 'x': x, 'y_pdf': y_cust_pdf, 'y_cdf': y_cust_cdf } source_custom.data = data_custom
def exp_erl(rate, rate_exp, k, y0=1, neval=35): tspan = [0, 16.] t_eval = np.linspace(*tspan, neval) # Exp pdf_exp = expon.pdf(t_eval, scale=1. / rate_exp) survival_exp = y0 * expon.sf(t_eval, scale=1. / rate_exp) pdf_erlang = erlang.pdf(t_eval, a=k, scale=1. / rate) survival_erlang = y0 * erlang.sf(t_eval, a=k, scale=1. / rate) fig, axs = plt.subplots(2, 1, figsize=(15, 15), sharex=True) pdf_idx = 0 survival_idx = 1 exp_label = 'Exp(x; $r$={:5.3f})'.format(rate_exp) erlang_label = 'Erlang(x; $r$={:5.3f},$k$={})'.format(rate, k) axs[pdf_idx].plot(t_eval, pdf_exp, 'k-', label='PDF {}'.format(exp_label)) axs[pdf_idx].plot(t_eval, pdf_erlang, 'k--', label='PDF {}'.format(erlang_label)) axs[survival_idx].plot(t_eval, survival_exp, 'k-', label='{}'.format(exp_label)) axs[survival_idx].plot(t_eval, survival_erlang, 'k--', label='{}'.format(erlang_label)) # Styling font_size = 16 for ax in axs: ax.legend(fontsize=font_size) ax.tick_params(axis='x', labelsize=font_size) ax.tick_params(axis='y', labelsize=font_size) axs[-1].set_xlabel('x', fontsize=font_size) plt.show()
def calc_mdelays_hist(d, ich=0, m=10, period=(0, -1), bins_s=(0, 10, 0.02), ph_sel=Ph_sel('all'), bursts=False, bg_fit=True, bg_F=0.8): """Compute histogram of m-photons delays (or waiting times). Arguments: dx (Data object): contains the burst data to process. ich (int): the channel number. Default 0. m (int): number of photons used to compute each delay. period (int or 2-element tuple): index of the period to use. If tuple, the period range between period[0] and period[1] (included) is used. bins_s (3-element tuple): start, stop and step for the bins ph_sel (Ph_sel object): photon selection to use. Returns: Tuple of values: * bin_x (array): array of bins centers * histograms_y (array): arrays of histograms, contains 1 or 2 histograms (when `bursts` is False or True) * bg_dist (random distribution): erlang distribution with same rate as background (kcps) * a, rate_kcps (floats, optional): amplitude and rate for an Erlang distribution fitted to the histogram for bin_x > bg_mean*bg_F. Returned only if `bg_fit` is True. """ assert ph_sel in [Ph_sel('all'), Ph_sel(Dex='Dem'), Ph_sel(Dex='Aem')] if np.size(period) == 1: period = (period, period) periods = slice(d.Lim[ich][period[0]][0], d.Lim[ich][period[1]][1] + 1) bins = np.arange(*bins_s) if ph_sel == Ph_sel('all'): ph = d.ph_times_m[ich][periods] if bursts: phb = ph[d.ph_in_burst[ich][periods]] elif ph_sel == Ph_sel(Dex='Dem'): donor_ph_period = -d.A_em[ich][periods] ph = d.ph_times_m[ich][periods][donor_ph_period] if bursts: phb = ph[d.ph_in_burst[ich][periods][donor_ph_period]] elif ph_sel == Ph_sel(Dex='Aem'): accept_ph_period = d.A_em[ich][periods] ph = d.ph_times_m[ich][periods][accept_ph_period] if bursts: phb = ph[d.ph_in_burst[ich][periods][accept_ph_period]] ph_mdelays = np.diff(ph[::m])*d.clk_p*1e3 # millisec if bursts: phb_mdelays = np.diff(phb[::m])*d.clk_p*1e3 # millisec phb_mdelays = phb_mdelays[phb_mdelays < 5] # Compute the PDF through histograming hist_kwargs = dict(bins=bins, normed=True) mdelays_hist_y, _ = np.histogram(ph_mdelays, **hist_kwargs) bin_x = bins[:-1] + 0.5*(bins[1] - bins[0]) if bursts: mdelays_b_hist_y, _ = np.histogram(phb_mdelays, **hist_kwargs) mdelays_b_hist_y *= phb_mdelays.size/ph_mdelays.size if bursts: histograms_y = np.vstack([mdelays_hist_y, mdelays_b_hist_y]) else: histograms_y = mdelays_hist_y results = [bin_x, histograms_y] # Compute the BG distribution bg_dist = _get_bg_distrib_erlang(d, ich=ich, m=m, period=period, ph_sel=ph_sel) bg_mean = bg_dist.mean() results.append(bg_dist) if bg_fit: ## Fitting the BG portion of the PDF to an Erlang _x = bin_x[bin_x > bg_mean*bg_F] _y = mdelays_hist_y[bin_x > bg_mean*bg_F] fit_func = lambda x, a, rate_kcps: a*erlang.pdf(x, a=m, scale=1./rate_kcps) err_func = lambda p, x, y: fit_func(x, p[0], p[1]) - y p, flag = leastsq(err_func, x0=[0.9, 3.], args=(_x, _y)) print(p, flag) a, rate_kcps = p results.extend([a, rate_kcps]) return results
def Erlang(x, k, lam): """ 爱尔兰分布概率密度函数. """ return erlang.pdf(x, k) * np.exp(-k * lam * x) * pow(k * lam, k) / np.exp(-x)
def example(rate, rate_exp, k, neval=35): tspan = [0, 16.] t_eval = np.linspace(*tspan, neval) y0 = [ 1, ] # k = 5 # scale to same mean # scale = 1.5 # r = 1./scale # Exp pdf_exp = expon.pdf(t_eval, scale=1. / rate_exp) survival_exp = y0[0] * expon.sf(t_eval, scale=1. / rate_exp) y0_lct = np.zeros(k) y0_lct[0] = y0[0] sol_lct = solve_ivp(dydt_lct, tspan, y0_lct, t_eval=t_eval, args=(rate, k), method='Radau') # print('mean exp: ', 1/rate_exp) # print('rate erlang: ', rate) # print('scale erlang: ', 1./rate) # print('mean erlang: ', k/rate) pdf_erlang = erlang.pdf(t_eval, a=k, scale=1. / rate) survival_erlang = y0[0] * erlang.sf(t_eval, a=k, scale=1. / rate) fig, axs = plt.subplots(2, 1, figsize=(15, 15), sharex=True) pdf_idx = 0 survival_idx = 1 exp_label = 'Exp(x; $r$={:5.3f})'.format(rate_exp) erlang_label = 'Erlang(x; $r$={:5.3f},$k$={})'.format(rate, k) axs[pdf_idx].plot(t_eval, pdf_exp, 'k-', label='PDF {}'.format(exp_label)) axs[pdf_idx].plot(t_eval, pdf_erlang, 'k--', label='PDF {}'.format(erlang_label)) axs[survival_idx].plot(t_eval, survival_exp, 'k-', label='{}'.format(exp_label)) axs[survival_idx].plot(t_eval, survival_erlang, 'k--', label='{}'.format(erlang_label)) axs[survival_idx].plot(t_eval, np.sum(sol_lct.y, axis=0), marker='o', linewidth=0, markeredgecolor='k', markerfacecolor='none', label=r'$I = I_1 + I_2 + I_3 + I_4 + I_5$') for istage in range(k): axs[survival_idx].plot(t_eval, sol_lct.y[istage], ':', label='$I_{}$'.format(istage + 1)) # Styling font_size = 16 for ax in axs: ax.legend(fontsize=font_size) ax.tick_params(axis='x', labelsize=font_size) ax.tick_params(axis='y', labelsize=font_size) axs[-1].set_xlabel('x', fontsize=font_size) plt.show()
from scipy.stats import erlang import numpy as np import matplotlib.pyplot as plt k = 47 laba = 1 x = np.arange(1, 100) print(x) temp1 = erlang.cdf(x, k, laba) temp2 = erlang.pdf(x, k, laba) print(temp2) plt.plot(x, temp1, 'o-', color='orange') plt.plot(x, temp2, 'o-', color='green') plt.xlabel('$x$') plt.ylabel('$y$') plt.grid() plt.show()
def fit_func(x, a, rate_kcps): return a * erlang.pdf(x, a=m, scale=1./rate_kcps)
###-----------------------------------------------------------------------### ###------------------DATA SOURCES AND INITIALIZATION----------------------### ### This section defines the data sources which will be used in the Bokeh ### ### plots. To update a Bokeh plot in the server, each of the sources will ### ### be modified in the CALLBACKS section. ("Model") ### ###-----------------------------------------------------------------------### # x data d_x = np.linspace(d_xmin, d_xmax, d_N) # uniform distribution d_y_uni_pdf = uniform.pdf(d_x, loc=d_uni_a, scale=(d_uni_b - d_uni_a)) d_y_uni_cdf = uniform.cdf(d_x, loc=d_uni_a, scale=(d_uni_b - d_uni_a)) # custom distribution d_y_cust_pdf = erlang.pdf(d_x, a=d_cust_k, scale=d_cust_teta) d_y_cust_cdf = erlang.cdf(d_x, a=d_cust_k, scale=d_cust_teta) d_data_uniform = { 'x': d_x, 'y_pdf': d_y_uni_pdf, 'y_cdf': d_y_uni_cdf } source_uniform = ColumnDataSource(data=d_data_uniform) d_data_custom = { 'x': d_x, 'y_pdf': d_y_cust_pdf, 'y_cdf': d_y_cust_cdf } source_custom = ColumnDataSource(data=d_data_custom)
def f_z_smaller__x(aa, n, A, a, UL=30): return erlang.pdf(aa, n, loc=0, scale=1) * quad( f_z_smaller_x_, aa, UL, args=(aa, n, A, a))[0]