def rayleigh_noise_signal_error(bins, param_s1,param_s2,param_n1, param_n2, flag): pdf_fitted1 = rayleigh.pdf(bins,loc=param_s1,scale=param_s2) pdf_fitted2 = rayleigh.pdf(bins,loc=param_n1,scale=param_n2) mean_square_err =mean_squared_error(pdf_fitted1, pdf_fitted2) rmse = sqrt(mean_square_err) return rmse
def error_calculation(bins, param_s1,param_s2,param_n1, param_n2, flag): if flag==1: pdf_fitted1 = rayleigh.pdf(bins,loc=param_s1,scale=param_s2) # fitted distribution - rayleigh pdf_fitted2 = rayleigh.pdf(bins,loc=param_n1,scale=param_n2) # fitted distribution - rayleigh elif flag==0: pdf_fitted1 = expon.pdf(bins,loc=param_s1,scale=param_s2) # fitted distribution - exponential pdf_fitted2 = expon.pdf(bins,loc=param_n1,scale=param_n2) # fitted distribution - exponential l1_norm=0 mean_square_err =mean_squared_error(pdf_fitted1, pdf_fitted2) l1_norm = sum(abs(pdf_fitted1 - pdf_fitted2)) root_mean_square_err = sqrt(mean_square_err) mean_l1_norm = 1.0*l1_norm/len(pdf_fitted1) print "Root Mean Square Error= ", root_mean_square_err print "Mean L1 norm= ", mean_l1_norm
def compute_array_ar(ruv): x = np.linspace(0, ruv.max() + 100., 1000) param = rayleigh.fit(ruv) pdf_fitted = rayleigh.pdf(x, loc=param[0], scale=param[1]) interval = rayleigh.interval(0.992, loc=param[0], scale=param[1]) linea = min(interval[1], ruv.max()) return 61800 / (100. * linea)
def returnDistData(cls, self): gammaParam = gamma.fit(10**(self.data / 10)) gammaDist = gamma.pdf(self.data, *gammaParam) rayleighParam = rayleigh.fit(self.data) rayleighDist = rayleigh.pdf(self.data, *rayleighParam) normParam = norm.fit(self.data) normDist = norm.pdf(self.data, *normParam) logNormParam = lognorm.fit(self.data) lognormDist = lognorm.pdf(self.data, *logNormParam) nakagamiParam = nakagami.fit(self.data) nakagamiDist = nakagami.pdf(self.data, *nakagamiParam) exponParam = expon.fit(self.data) exponDist = expon.pdf(self.data, *exponParam) exponweibParam = exponweib.fit(self.data) weibDist = exponweib.pdf(self.data, *exponweibParam) distDF = pd.DataFrame(np.column_stack([ gammaDist, rayleighDist, normDist, lognormDist, nakagamiDist, exponDist, weibDist ]), columns=[ 'gammaDist', 'rayleighDist', 'normDist', 'lognormDist', 'nakagamiDist', 'exponDist', 'weibDist' ]) self.distDF = distDF
def plot_distrib_distance(list_values, name, dt, xmax, ymax, color): #print(list_values) fig = matplotlib.pyplot.figure() ax = fig.add_subplot(1, 1, 1) ax.set_xlim([0, xmax]) n, bins, patches = matplotlib.pyplot.hist(list_values, 50, normed=1, facecolor=color, alpha=0.5) param = rayleigh.fit(sorted(list_values)) pdf_fitted = rayleigh.pdf(sorted(list_values), loc=param[0], scale=param[1]) mean_rayleigh = rayleigh.mean(loc=param[0], scale=param[1]) std_rayleigh = rayleigh.std(loc=param[0], scale=param[1]) / math.sqrt( float(len(list_values))) print('mean = ' + str(mean_rayleigh)) print('std error = ' + str(std_rayleigh)) #chi_value = chisquare(sorted(list_values), f_exp=pdf_fitted) #print('chi_square = '+str(chi_value[0])) #print('p_value = '+str(chi_value[1])) matplotlib.pyplot.plot(sorted(list_values), pdf_fitted, 'g-') matplotlib.pyplot.savefig(str(name) + '_' + str(dt) + '.svg') #matplotlib.pyplot.show() matplotlib.pyplot.close() return (mean_rayleigh, std_rayleigh)
def plot_pdf_fit(self, label=None): import matplotlib.pyplot as plt from scipy.stats import exponweib, rayleigh from scipy import linspace, diff plt.bar(self.pdf[1][:len(self.pdf[0])], self.pdf[0], width=diff(self.pdf[1]), label=label, alpha=0.5, color='k') x = linspace(0, 50, 1000) plt.plot(x, exponweib.pdf(x, a=self.weibull_params[0], c=self.weibull_params[1], scale=self.weibull_params[3]), 'b--', label='Exponential Weibull pdf') plt.plot(x, rayleigh.pdf(x, scale=self.rayleigh_params[1]), 'r--', label='Rayleigh pdf') plt.title('Normalized distribution of wind speeds') plt.grid() plt.legend()
def compute_initial_figure(self, ruv): x = np.linspace(0, ruv.max() + 100., 1000) param = rayleigh.fit(ruv) pdf_fitted = rayleigh.pdf(x, loc=param[0], scale=param[1]) self.axes.hist(ruv, bins=30, normed=True) self.axes.plot(x, pdf_fitted, 'r-') ylims = self.axes.get_ylim() self.interval = rayleigh.interval(0.992, loc=param[0], scale=param[1]) linea = min(self.interval[1], ruv.max()) self.axes.vlines(linea, 0, ylims[1], linestyles='dashed') self.axes.set_ylim(ylims)
def getPDF(self, points=None): """ A Rayleigh probability density function. :param Rayleigh self: An instance of the Rayleigh class. :param array points: Points at which the PDF needs to be evaluated. :return: Probability density values along the support of the Rayleigh distribution. """ return rayleigh.pdf(points, loc=0, scale=self.scale )
def get_pdf(self, points=None): """ A Rayleigh probability density function. :param Rayleigh self: An instance of the Rayleigh class. :param array points: Points at which the PDF needs to be evaluated. :return: Probability density values along the support of the Rayleigh distribution. """ return rayleigh.pdf(points, loc=0, scale=self.scale)
def _update_canvas(self): """ Update the figure when the user changes an input value. :return: """ # Get the parameters from the form loc = float(self.loc.text()) scale = float(self.scale.text()) shape_factor = float(self.shape_factor.text()) # Get the selected distribution from the form distribution_type = self.distribution_type.currentText() if distribution_type == 'Gaussian': x = linspace(norm.ppf(0.001, loc, scale), norm.ppf(0.999, loc, scale), 200) y = norm.pdf(x, loc, scale) elif distribution_type == 'Weibull': x = linspace(weibull_min.ppf(0.001, shape_factor), weibull_min.ppf(0.999, shape_factor), 200) y = weibull_min.pdf(x, shape_factor, loc, scale) elif distribution_type == 'Rayleigh': x = linspace(rayleigh.ppf(0.001, loc, scale), rayleigh.ppf(0.999, loc, scale), 200) y = rayleigh.pdf(x, loc, scale) elif distribution_type == 'Rice': x = linspace(rice.ppf(0.001, shape_factor), rice.ppf(0.999, shape_factor), 200) y = rice.pdf(x, shape_factor, loc, scale) elif distribution_type == 'Chi Squared': x = linspace(chi2.ppf(0.001, shape_factor), chi2.ppf(0.999, shape_factor), 200) y = chi2.pdf(x, shape_factor, loc, scale) # Clear the axes for the updated plot self.axes1.clear() # Display the results self.axes1.plot(x, y, '') # Set the plot title and labels self.axes1.set_title('Probability Density Function', size=14) self.axes1.set_xlabel('x', size=12) self.axes1.set_ylabel('Probability p(x)', size=12) # Set the tick label size self.axes1.tick_params(labelsize=12) # Turn on the grid self.axes1.grid(linestyle=':', linewidth=0.5) # Update the canvas self.my_canvas.draw()
def rayleigh_statistic(data,bins): rayleigh_param[-1,-1] rayleigh_pdf=[-1] try : rayleigh_param = rayleigh.fit(data) except: rayleigh_param[-2,-2] try: pdf_rayleigh_fitted = rayleigh.pdf(bins, *rayleigh_param[:-2],loc=rayleigh_param[0],scale=rayleigh_param[1]) # fitted distribution except : rayleigh_pdf=[-1] return [rayleigh_param, rayleigh_pdf]
def super_hist(data_name): wind = data[data_name] support = np.linspace(wind.min(), wind.max(), 100) p0, p1, p2 = scipy.stats.weibull_min.fit(wind, floc=0) plt.plot(support, scipy.stats.weibull_min.pdf(support, p0, p1, p2), 'r-', lw=2, label = 'Weibull') data[data_name].plot.hist( weights=np.ones_like(data.index)/len(data.index), bins=25) param = rayleigh.fit(wind) # distribution fitting plt.plot(support, rayleigh.pdf(support, loc=param[0],scale=param[1]),lw=2, label = 'Rayleigh') plt.legend() plt.xlabel("Mean wind speed [m/s]") plt.ylabel("Frequency [%]") #figure_path = Directory + '\ ' + data_name + '.png' plt.savefig(Directory + '\ ' + 'Super_' + data_name[17:19] + '.png') plt.show() return
def approximating_dists(data,bins): try : rayleigh_param = rayleigh.fit(data) except: print "screwed raleigh fit " print "params for rayleigh " ,rayleigh_param try: pdf_rayleigh_fitted = rayleigh.pdf(bins, *rayleigh_param[:-2],loc=rayleigh_param[0],scale=rayleigh_param[1]) # fitted distribution except : print " returning as nothing to plot " try : exp_param = expon.fit(data) except: print "screwed expon fit " print "params for exponential ", exp_param try: pdf_exp_fitted = expon.pdf(bins, *exp_param[:-2],loc=exp_param[0],scale=exp_param[1]) # fitted distribution except : print " returning as nothing to plot " return [exp_param, pdf_exp_fitted, rayleigh_param, pdf_rayleigh_fitted]
def rayleighStretch(hist): h = {} bot = hist.argmin() if bot == 0: bot = np.percentile(hist, 1) top = hist.argmax() if top == 255: top = np.percentile(hist, 99) newhist = hist #print(bot, top) for pixel in newhist: #print(pixel[0]) if pixel[0] < bot: pixel[0] = 0 elif pixel[0] > top: pixel[0] = 255 else: pixel[0] = (255 * ((pixel[0] - bot) / (top - bot))) # print(pixel) #print(newhist) val = rayleigh.pdf(newhist, scale=256) print(val) return h
def plot_band_histgram(blrms,scale=0.9,loc=0,suffix=''): blrms.override_unit('m/s') blrms = blrms/amp*c2v/1000*1e6 # #hist,bins = np.histogram(blrms ,density=False,bins=3000,range=(1e-2,10)) #hist,bins = np.histogram(blrms ,density=True,bins=3000,range=(1e-2,10)) hist,bins = np.histogram(blrms ,density=True,bins=3000,range=(1e-2,10)) # fig, ax = plt.subplots(1,1,figsize=(7,7)) plt.title('BLRMS Histgram') from scipy.stats import rayleigh x = np.logspace(-3,1,1000) model = rayleigh.pdf(x,loc=2e-2,scale=0.1) ax.step(bins[:-1],hist,where='post',color='k',label='200mHz') #ax.plot(x,model,'r-') #ax.set_ylim(0,100) ax.set_ylim(0,10) ax.set_xlabel('Horizontal motion [um/sec]') ax.set_xscale('log') ax.set_xlim(1e-2,1e1) #ax.set_ylabel('Normarized Counts') ax.set_ylabel('Counts') ax.legend() ax2 = ax.twinx() ax2.set_ylabel('Cumulative Probability') ax2.plot(bins[:-1],np.cumsum(hist)/np.float(np.sum(hist)),'k--',linewidth=2) ax2.set_ylim(0,1) ax2.set_yticks([0,0.1,0.5,0.9,1.0]) ax2.axhline(y=0.01, color='k', linestyle=':',zorder=0) ax2.axhline(y=0.10, color='k', linestyle=':',zorder=0) ax2.axhline(y=0.50, color='k', linestyle=':',zorder=0) ax2.axhline(y=0.90, color='k', linestyle=':',zorder=0) ax2.axhline(y=0.99, color='k', linestyle=':',zorder=0) fname = './results/histgram_{0}.png'.format(suffix) print(fname) plt.savefig(fname) plt.close()
def update_histogram(price_chart, slider_value, auto_state): price = [] try: # Check to see whether price-chart has been plotted if price_chart is not None: price = price_chart["data"][0]["y"] if "Auto" in auto_state: bin_val = np.histogram( price, bins=range(int(round(min(price))), int(round(max(price)))), ) else: bin_val = np.histogram(price, bins=slider_value) except Exception as error: raise PreventUpdate avg_val = float(sum(price)) / len(price) median_val = np.median(price) pdf_fitted = rayleigh.pdf(bin_val[1], loc=(avg_val) * 0.55, scale=(bin_val[1][-1] - bin_val[1][0]) / 3) y_val = (pdf_fitted * max(bin_val[0]) * 20, ) y_val_max = max(y_val[0]) bin_val_max = max(bin_val[0]) trace = go.Bar( x=bin_val[1], y=bin_val[0], marker={"color": app_color["graph_line"]}, showlegend=False, hoverinfo="x+y", ) traces_scatter = [ { "line_dash": "dash", "line_color": "#2E5266", "name": "Average" }, { "line_dash": "dot", "line_color": "#BD9391", "name": "Median" }, ] scatter_data = [ go.Scatter( x=[bin_val[int(len(bin_val) / 2)]], y=[0], mode="lines", line={ "dash": traces["line_dash"], "color": traces["line_color"] }, marker={"opacity": 0}, visible=True, name=traces["name"], ) for traces in traces_scatter ] # trace3 = go.Scatter( # mode="lines", # line={"color": "#42C4F7"}, # y=y_val[0], # x=bin_val[1][: len(bin_val[1])], # name="Rayleigh Fit", # ) data = [trace, scatter_data[0], scatter_data[1]] return { "data": data, "layout": go.Layout( height=300, plot_bgcolor=app_color["graph_bg"], paper_bgcolor=app_color["graph_bg"], font={"color": "#fff"}, margin={ 't': 5, 'b': 20, 'l': 60, 'r': 60 }, autosize=True, xaxis={ #"title": "Price", "showgrid": False, "showline": False, "fixedrange": True, }, yaxis={ "showgrid": False, "showline": False, "zeroline": False, "title": "Number of Samples", "fixedrange": True, }, bargap=0.01, bargroupgap=0, hovermode="closest", legend={ "orientation": "h", "yanchor": "bottom", "xanchor": "center", "y": 1, "x": 0.5, }, shapes=[ { "xref": "x", "yref": "y", "y1": int(max(bin_val_max, y_val_max)) + 0.5, "y0": 0, "x0": avg_val, "x1": avg_val, "type": "line", "line": { "dash": "dash", "color": "#2E5266", "width": 5 }, }, { "xref": "x", "yref": "y", "y1": int(max(bin_val_max, y_val_max)) + 0.5, "y0": 0, "x0": median_val, "x1": median_val, "type": "line", "line": { "dash": "dot", "color": "#BD9391", "width": 5 }, }, ], ) }
def density(self, x): return rayleigh.pdf(x, loc=self.mu, scale=self.sigma)
for j in range(3) : sigma[j] += pow(v[i][j]-mu[j],2) sigma[3] += pow(vel[i]-mu[3],2) for j in range(3) : sigma[j] = sqrt(sigma[j]/len(v)) sigma[3] = sqrt(2/pi)*mu[3] range = np.arange(-5, 5, 0.01) plt.figure(1) plt.plot(range, norm.pdf(range, mu[0], sigma[0])) plt.xlabel('$v_x$ [angstrom/ps]') plt.ylabel('probability') plt.title('$\mu$=%g, $\sigma$=%g'%(mu[0],sigma[0])) plt.figure(2) plt.plot(range, norm.pdf(range, mu[1], sigma[1])) plt.xlabel('$v_y$ [angstrom/ps]') plt.ylabel('probability') plt.title('$\mu$=%g, $\sigma$=%g'%(mu[1],sigma[1])) plt.figure(3) plt.plot(range, norm.pdf(range, mu[2], sigma[2])) plt.xlabel('$v_z$ [angstrom/ps]') plt.ylabel('probability') plt.title('$\mu$=%g, $\sigma$=%g'%(mu[2],sigma[2])) plt.figure(4) range = np.arange(0, 6, 0.01) plt.plot(range, rayleigh.pdf(range, scale=sigma[3])) plt.xlabel('$v$ [angstrom/ps]') plt.ylabel('probability') plt.title('mean=%g, $\sigma$=%g'%(mu[3],sigma[3])) plt.show()
fontsize=MEDIUM_SIZE) plt.gcf().text(0.21 + 0.275, 0.2 - 0.04 - 6 / yr, '$\mathregular{10^{-10}}$', fontsize=MEDIUM_SIZE) # Graph parameters weight = ones_like(star_xir) / float( len(star_xir)) # Weight to normalize graph sub8.errorbar(x, y, yerr=ye, fmt='k|', mfc='none') sub8.hist(star_xir, bins=30, range=(0, 4.5), weights=weight, edgecolor='#08088A', linewidth=0.5, fc=(0, 0, 0, 0), orientation='horizontal') # Rayleigh distribution mean = sum(star_xir) / len(star_xir) y = linspace(0.0, 4.5, 100) param = rayleigh.fit(star_xir) pdf_fitted = rayleigh.pdf(y) * 0.15 sub8.plot(pdf_fitted, y, 'black', linestyle='--', linewidth=0.5) # ========== Output ========== # fig.savefig('fig6.eps', format='eps', bbox_inches='tight', pad_inches=0.02, dpi=1000)
def adjustar_Ray(mid_pointa, histoa): a_ajustar_ray = lambda x,l,s: rayleigh.pdf(x, l, s) popt_wei, pcov = curve_fit(a_ajustar_ray, mid_pointa, histoa) print(popt_wei, pcov) ajustado_ray = a_ajustar_ray(mid_pointa, popt_wei[0], popt_wei[1]) return(ajustado_ray)
def plot_statistical_analysis(R, V, time_step, filename): # Total kinetic energy and total velocity V_calc1 = np.linalg.norm(V, axis=1) # Calculating sumations and norms accordingly V_calc2 = (V_calc1 ** 2) # by the given exercise E_k = np.sum(V_calc2, axis=1) / 2 V_tot = np.sum(V, axis=2) V_tot = np.linalg.norm(V_tot, axis=1) print(R.shape) dists = R[:, :, np.newaxis, :] - R[:, :, :, np.newaxis] # Creating another axis to be able to compare the values # And calculate the distances between particles dists = np.linalg.norm(dists, axis=1) # Calculating norm dists = np.reshape(dists, (400*400*1000, 1)) # Putting every value in a row R = np.reshape(R, [400*1000, 2]) # reshape the matrixes so they can be plotted R_x = R[:, 0] # Creating x and y vectors R_y = R[:, 1] V = np.reshape(V, [400*1000, 2]) V_x = V[:, 0] # Creating x and y vectors V_y = V[:, 1] V = np.linalg.norm(V, axis=1) # Creating the norm vector needed for plotting time = "time" t = np.arange(0, 20, time_step) # Predefinitions plt.figure(tight_layout=True, figsize=[9., 6.]) # Average time plt.subplot(421) plt.plot(t, V_tot) # Everything here is pretty self explanatory plt.xlabel(time) # plot time with wanted vector, V, dists and E_k plt.ylabel("Average speed") # Kinetic energy plt.subplot(422) plt.plot(t, E_k) plt.ylabel("Kinetic energy") plt.ylim([min(E_k)-0.2, max(E_k)+0.2]) plt.xlabel(time) # Distance plt.subplot(423) plt.xlabel("distance") # Create the histograms with hist plt.ylabel("Pair distribution\n probability") # and then input the wanted vectors plt.xlim([-0.5, max(dists)+1]) plt.hist(dists, bins=50, density="True") # Speed plt.subplot(424) plt.xlabel("speed") plt.ylabel("Velocity norm\n probability") plt.hist(V, bins="auto", density="True") x = np.linspace(min(V), max(V), 100) # The vector needed to plot the pdf and reg. plot needs together with loc_V, scale_V = rayleigh.fit(V) # Creating the values pdf needs plt.plot(x, rayleigh.pdf(x, loc_V, scale_V)) # All the other pdfs are done # x position # the same way plt.subplot(425) # also am creating x.lims and y.lims plt.xlabel("x position") # where they are needed plt.ylabel("Probability") plt.hist(R_x, bins="auto", density="True") x = np.linspace(min(R_x)-0.5, max(R_x)+0.5, 100) loc_R_x, scale_R_x = uniform.fit(R_x) plt.plot(x, uniform.pdf(x, loc_R_x, scale_R_x)) # y position plt.subplot(426) plt.xlabel("y position") plt.ylabel("Probability") plt.hist(R_y, bins="auto", density="True") x = np.linspace(min(R_y)-0.5, max(R_y)+0.5, 100) loc_R_y, scale_R_y = uniform.fit(R_y) plt.plot(x, uniform.pdf(x, loc_R_y, scale_R_y)) # x velocity plt.subplot(427) plt.xlabel("x velocity") plt.ylabel("Probability") plt.hist(V_x, bins="auto", density="True") x = np.linspace(min(V_x)-0.2, max(V_x)+0.2, 100) loc_v_x, scale_v_x = norm.fit(V_x) plt.plot(x, norm.pdf(x, loc_v_x, scale_v_x)) # y velocity plt.subplot(428) plt.xlabel("y velocity") plt.ylabel("Probability") plt.hist(V_y, bins="auto", density="True") x = np.linspace(min(V_y)-0.2, max(V_y)+0.2, 100) loc_v_y, scale_v_y = norm.fit(V_y) plt.plot(x, norm.pdf(x, loc_v_y, scale_v_y)) plt.savefig(filename) plt.show()
norm.pdf(x, loc=2.5, scale=1.0) * 0.7, label="Normal Mixture", alpha=0.8, color="tab:orange", linewidth=1.4, ) # Plot Laplace plt.plot( x, laplace.pdf(x, loc=0.5, scale=1.5), label="Laplace", alpha=0.8, color="tab:green", linewidth=1.4, ) # Plot Rayleigh plt.plot( x, rayleigh.pdf(x, scale=2), label="Rayleigh", alpha=0.8, color="tab:red", linewidth=1.4, ) plt.legend() plt.tight_layout() plt.savefig("img/distributions.png")
def power_demand_histogram(json_data, resolution, sliderValue, auto_state): power_val = [] df_data = pd.read_json(json_data, orient='split') power_val = df_data['power_inst'].round(int(-np.log10(int(resolution)))) if 'Auto' in auto_state: bin_val = np.histogram(power_val, bins=range(int(round(min(power_val))), int(round(max(power_val))))) else: bin_val = np.histogram(power_val, bins=sliderValue) avg_val = float(sum(power_val.values)) / len(power_val.index) median_val = np.median(power_val) pdf_fitted = rayleigh.pdf(bin_val[1], loc=(avg_val) * 0.55, scale=(bin_val[1][-1] - bin_val[1][0]) / 3) y_val = pdf_fitted * max(bin_val[0]) * 20, y_val_max = max(y_val[0]) bin_val_max = max(bin_val[0]) trace = Bar(x=bin_val[1], y=bin_val[0], marker=Marker(color='gray'), showlegend=False, hoverinfo='x+y') trace1 = Scatter(x=[bin_val[int(len(bin_val) / 2)]], y=[0], mode='lines', line=Line(dash='dash', color='blue'), marker=Marker(opacity=1, ), visible=True, name='Average') trace2 = Scatter(x=[bin_val[int(len(bin_val) / 2)]], y=[0], line=Line(dash='dot', color='black'), mode='lines', marker=Marker(opacity=1, ), visible=True, name='Median') trace3 = Scatter(mode='lines', line=Line(color='magenta'), y=y_val[0], x=bin_val[1][:len(bin_val[1])], name='Rayleigh Fit') layout = Layout(xaxis=dict(title='Power Demand (W)', showgrid=False, showline=False, fixedrange=True), yaxis=dict(showgrid=False, showline=False, zeroline=False, title='Number of Samples', fixedrange=True), margin=Margin(t=50, b=20, r=50), autosize=True, bargap=0.01, bargroupgap=0, hovermode='closest', legend=Legend(x=0.175, y=-0.2, orientation='h'), shapes=[ dict(xref='x', yref='y', y1=int(max(bin_val_max, y_val_max)) + 0.5, y0=0, x0=avg_val, x1=avg_val, type='line', line=Line(dash='dash', color='blue', width=5)), dict(xref='x', yref='y', y1=int(max(bin_val_max, y_val_max)) + 0.5, y0=0, x0=median_val, x1=median_val, type='line', line=Line(dash='dot', color='black', width=5)) ]) return Figure(data=[trace, trace1, trace2], layout=layout)
from numpy import linspace from pylab import plot, show, hist, figure, title """ here we try to fit rayleigh distribution to data reference: glowingpython.blogspot.it""" #generate 150 samples from a rayleigh distribution of mean 5 and std dev 2 samp = rayleigh.rvs(loc=5, scale=2, size=150) #fit rayleigh distibution to generated samples #param[0] & param[1] are mean and std. dev of fitted distribution param = rayleigh.fit(samp) #generate points on x-axis to plot x = linspace(5, 13, 100) #get the points on y-axis for fitted distribution pdf_fitted = rayleigh.pdf(x, loc=param[0], scale=param[1]) #get the points on y-axis for original distribution pdf = rayleigh.pdf(x, loc=5, scale=2) title('Rayleigh distribution') #plot the fitted distribution and original distribution plot(x, pdf_fitted, 'r-', x, pdf, 'b-') #histogram of normalized samples generated from rayleigh distribution hist(samp, normed=1, alpha=0.3) show()
def downtime_accepted_models(D=list(), alpha=.05): params = list() params.append(uniform.fit(D)) params.append(expon.fit(D)) params.append(rayleigh.fit(D)) params.append(weibull_min.fit(D)) params.append(gamma.fit(D)) params.append(gengamma.fit(D)) params.append(invgamma.fit(D)) params.append(gompertz.fit(D)) params.append(lognorm.fit(D)) params.append(exponweib.fit(D)) llf_value = list() llf_value.append(log(product(uniform.pdf(D, *params[0])))) llf_value.append(log(product(expon.pdf(D, *params[1])))) llf_value.append(log(product(rayleigh.pdf(D, *params[2])))) llf_value.append(log(product(weibull_min.pdf(D, *params[3])))) llf_value.append(log(product(gamma.pdf(D, *params[4])))) llf_value.append(log(product(gengamma.pdf(D, *params[5])))) llf_value.append(log(product(invgamma.pdf(D, *params[6])))) llf_value.append(log(product(gompertz.pdf(D, *params[7])))) llf_value.append(log(product(lognorm.pdf(D, *params[8])))) llf_value.append(log(product(exponweib.pdf(D, *params[9])))) AIC = list() AIC.append(2 * len(params[0]) - 2 * llf_value[0]) AIC.append(2 * len(params[1]) - 2 * llf_value[1]) AIC.append(2 * len(params[2]) - 2 * llf_value[2]) AIC.append(2 * len(params[3]) - 2 * llf_value[3]) AIC.append(2 * len(params[4]) - 2 * llf_value[4]) AIC.append(2 * len(params[5]) - 2 * llf_value[5]) AIC.append(2 * len(params[6]) - 2 * llf_value[6]) AIC.append(2 * len(params[7]) - 2 * llf_value[7]) AIC.append(2 * len(params[8]) - 2 * llf_value[8]) AIC.append(2 * len(params[9]) - 2 * llf_value[9]) model = list() model.append( ["uniform", params[0], kstest(D, "uniform", params[0])[1], AIC[0]]) model.append( ["expon", params[1], kstest(D, "expon", params[1])[1], AIC[1]]) model.append( ["rayleigh", params[2], kstest(D, "rayleigh", params[2])[1], AIC[2]]) model.append([ "weibull_min", params[3], kstest(D, "weibull_min", params[3])[1], AIC[3] ]) model.append( ["gamma", params[4], kstest(D, "gamma", params[4])[1], AIC[4]]) model.append( ["gengamma", params[5], kstest(D, "gengamma", params[5])[1], AIC[5]]) model.append( ["invgamma", params[6], kstest(D, "invgamma", params[6])[1], AIC[6]]) model.append( ["gompertz", params[7], kstest(D, "gompertz", params[7])[1], AIC[7]]) model.append( ["lognorm", params[8], kstest(D, "lognorm", params[8])[1], AIC[8]]) model.append( ["exponweib", params[9], kstest(D, "exponweib", params[9])[1], AIC[9]]) accepted_models = [i for i in model if i[2] > alpha] if accepted_models: aic_values = [i[3] for i in accepted_models] final_model = min(range(len(aic_values)), key=aic_values.__getitem__) return accepted_models, accepted_models[final_model] elif not accepted_models: aic_values = [i[3] for i in model] final_model = min(range(len(aic_values)), key=aic_values.__getitem__) return model, model[final_model]
# python3 import math import random import numpy as np from scipy.stats import rayleigh from matplotlib import pyplot as plt def inv_rayleigh_cdf(u): return math.sqrt(-2 * math.log(1 - u)) random.seed(1001) # random samples from Unif(0, 1) random_numbers = [random.random() for _ in range(10000)] # random samples of Rayleigh Dist. through the inverse transform random_numbers_from_rayleigh = [inv_rayleigh_cdf(random_number) for random_number in random_numbers] x = np.linspace(rayleigh.ppf(0), rayleigh.ppf(0.999), 100) plt.hist(random_numbers_from_rayleigh, 60, facecolor='green', normed=True, alpha=0.6, label='random numbers') plt.plot(x, rayleigh.pdf(x), lw=2, alpha=0.7, label='Rayleigh pdf') plt.legend(loc='best')
def run(): my_distribution = rayleigh() np.random.seed(747) num_points = 25 test_data = my_distribution.rvs(size=num_points) exact_mean = my_distribution.stats(moments='m') mean_val = np.mean(test_data) print("Distribution mean: ", exact_mean) print("Sample mean: ", mean_val) # Add some bad datapoints: test_data[0] = max(test_data) * 5 test_data[1] = max(test_data) * 3.5 print("Sample mean after data corruption: ", np.mean(test_data)) MyAnalysis = ResampleAnalysis(test_data) jackknifed_means, distances, conf_min, conf_max = MyAnalysis.jackknife( analysis_func=np.mean, conf_lvl=.95) print("np.std(jackknifed_means): ", np.std(jackknifed_means)) histo = TophatKDE(jackknifed_means) spread = max(jackknifed_means) - min(jackknifed_means) xvals = np.linspace( min(jackknifed_means) - spread * .1, max(jackknifed_means) + spread * .1, num_points * 5) plt.plot(xvals, histo(xvals), drawstyle='steps-post', color='b', lw=1) plt.scatter(jackknifed_means, np.zeros(len(jackknifed_means)), marker='+', color='k') plt.annotate("Found a couple outliers...", xy=(1.7, .33), xytext=(2, 2), arrowprops=dict(arrowstyle="->", connectionstyle="arc3, rad=.3")) plt.annotate("", xy=(2.9, .33), xytext=(2.5, 1.9), arrowprops=dict(arrowstyle="->", connectionstyle="arc3, rad=-.3")) plt.title("Distribution of jackknifed samples") plt.xlabel("Jackknifed distribution mean value") plt.ylabel("Counts") plt.show() rejected_points = MyAnalysis.remove_outliers_by_jackknife_sigma_testing( np.mean, 1) print("Rejected points from analysis based on outlier status: ", rejected_points) print("Sample mean after outlier rejection: ", MyAnalysis.apply_function(np.mean)) num_resamples = 1000 resampled_means, conf_min, conf_max = MyAnalysis.bootstrap( num_resamples, analysis_func=np.mean, conf_lvl=.95) print("Mean of resampled means: ", np.mean(resampled_means)) print("Minimum estimate of mean within 95% confidence: ", conf_min) print("Maximum estimate of mean within 95% confidence: ", conf_max) plt.hist(resampled_means) plt.title("Distribution of bootstrap resamples after outlier removal") plt.xlabel("Resampled mean values") plt.ylabel("Counts") plt.show() # ============================================================= # test_data = my_distribution.rvs(size=50) xvals = np.linspace(0, max(test_data) * 1.25, 500) MyKDEAnalysis = ResampleKDEAnalysis(test_data, xvals, kde=GaussianKDE, kde_bandwidth='silverman') xvals, computed_kde = MyKDEAnalysis.compute_kde() conf_lvls = [.6, .9] resampled_kde, confidence_intervals = MyKDEAnalysis.bootstrap_with_kde( num_resamples, conf_lvl=conf_lvls) print("resampled_kde.shape: ", resampled_kde.shape) print("confidence_intervals.shape: ", confidence_intervals.shape) visualize.plot_signal_w_uncertainty( xvals, computed_kde, confidence_intervals[:, 1, :], confidence_intervals[:, 0, :], y_data_2=rayleigh.pdf(xvals), y_axis_label="PDF", color_2='darkblue', y_label_1="KDE", y_label_2="Exact solution", plt_title="Computed KDE and uncertainty", uncertainty_color=['cadetblue', 'slategray'], uncertainty_label=[str(ci * 100) + "%" for ci in conf_lvls])
from scipy.stats import norm, rayleigh import matplotlib.pyplot as plt import matplotlib.mlab as mlab import numpy as np samp = rayleigh.rvs(loc=5, scale=2, size=150) # samples generation print(samp) param = rayleigh.fit(samp) # distribution fitting x = np.linspace(5, 13, 100) # fitted distribution pdf_fitted = rayleigh.pdf(x, loc=param[0], scale=param[1]) # original distribution pdf = rayleigh.pdf(x, loc=5, scale=2) plt.title('Rayleigh distribution') plt.plot(x, pdf_fitted, 'r-', x, pdf, 'b-') plt.hist(samp, normed=1, alpha=.3) plt.show()
from scipy.stats import rayleigh import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) # Calculate a few first moments: mean, var, skew, kurt = rayleigh.stats(moments='mvsk') # Display the probability density function (``pdf``): x = np.linspace(rayleigh.ppf(0.01), rayleigh.ppf(0.99), 100) ax.plot(x, rayleigh.pdf(x), 'r-', lw=5, alpha=0.6, label='rayleigh pdf') # Alternatively, the distribution object can be called (as a function) # to fix the shape, location and scale parameters. This returns a "frozen" # RV object holding the given parameters fixed. # Freeze the distribution and display the frozen ``pdf``: rv = rayleigh() ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf') # Check accuracy of ``cdf`` and ``ppf``: vals = rayleigh.ppf([0.001, 0.5, 0.999]) np.allclose([0.001, 0.5, 0.999], rayleigh.cdf(vals)) # True # Generate random numbers: r = rayleigh.rvs(size=1000)
def gen_wind_histogram(oldFigure, sliderValue, autoState): windVal = [] if oldFigure is not None: windVal = oldFigure['data'][0]['y'] if 'Auto' in autoState: binVal = np.histogram(windVal, bins=range(int(round(min(windVal))), int(round(max(windVal))))) else: binVal = np.histogram(windVal, bins=sliderValue) avgVal = float(sum(windVal)) / len(windVal) medianVal = np.median(windVal) param = rayleigh.fit(binVal[0]) pdf_fitted = rayleigh.pdf(binVal[1], loc=(avgVal - abs(param[1])) * 0.55, scale=(binVal[1][-1] - binVal[1][0]) / 3) yVal = pdf_fitted * max(binVal[0]) * 20, yValMax = max(yVal[0]) binValMax = max(binVal[0]) trace = Bar(x=binVal[1], y=binVal[0], marker=dict(color='#7F7F7F'), showlegend=False, hoverinfo='x+y') trace1 = Scatter(x=[25], y=[0], mode='lines', line=dict(dash='dash', color='#2E5266'), marker=dict(opacity=0, ), visible=True, name='Average') trace2 = Scatter(x=[25], y=[0], line=dict(dash='dot', color='#BD9391'), mode='lines', marker=dict(opacity=0, ), visible=True, name='Median') trace3 = Scatter(mode='lines', line=dict(color='#42C4F7'), y=yVal[0], x=binVal[1][:len(binVal[1])], name='Rayleigh Fit') layout = Layout(xaxis=dict( title='Wind Speed (mph), Rounded to Closest Integer', showgrid=False, showline=False, ), yaxis=dict(showgrid=False, showline=False, zeroline=False, title='Number of Samples'), margin=dict(t=50, b=20, r=50), autosize=True, bargap=0.01, bargroupgap=0, hovermode='closest', legend=dict(x=0.175, y=-0.2, orientation='h'), shapes=[ dict(xref='x', yref='y', y1=int(max(binValMax, yValMax)) + 0.5, y0=0, x0=avgVal, x1=avgVal, type='line', line=dict(dash='dash', color='#2E5266', width=5)), dict(xref='x', yref='y', y1=int(max(maxV, yValMax)) + 0.5, y0=0, x0=medianVal, x1=medianVal, type='line', line=dict(dash='dot', color='#BD9391', width=5)) ]) return dict(data=[trace, trace1, trace2, trace3], layout=layout)
# Variando a média e plotando os gráficos #plt.figure(1,[15,5]) #sigma = np.sqrt(vtVar[0]); #for il in range(0,len(vtMu)): # mu = vtMu[il] # plt.subplot(2,2,1) # plt.plot(x, norm.pdf(x,mu), label='Média = {}'.format(mu)) # plt.subplot(2,2,2) # plt.plot(x, norm.cdf(x,mu), label='Média = {}'.format(mu)) # Variando a variância e plotando os gráficos mu = vtMu[0] for il in range(0, len(vtVar)): sigma = np.sqrt(vtVar[il]) plt.subplot(2, 1, 1) plt.plot(x, rayleigh.pdf(x, scale=sigma), label='$\sigma$ = {:01.2f}'.format(sigma)) plt.subplot(2, 1, 2) plt.plot(x, rayleigh.cdf(x, scale=sigma), label='$\sigma$ = {:01.2f}'.format(sigma)) #plt.subplot(2,2,1) #plt.legend() #plt.subplot(2,2,2) #plt.legend() plt.subplot(2, 1, 1) plt.legend() plt.subplot(2, 1, 2) plt.legend() plt.show()
nb = nw * nt * nq sharedsize = 0 #byte x = np.zeros(nb) x = x.astype(np.float32) dev_x = cuda.mem_alloc(x.nbytes) cuda.memcpy_htod(dev_x, x) source_module = gabcrm_module() pkernel = source_module.get_function("rayleighgen") pkernel(dev_x, np.float32(alpha), np.float32(beta), block=(int(nw), 1, 1), grid=(int(nt), int(nq)), shared=sharedsize) cuda.memcpy_dtoh(x, dev_x) plt.hist(x, bins=100, density=True) # plt.hist(np.log10(x[x>0]),bins=100,density=True) #plt.yscale("log") # plt.xscale("log") xl = np.linspace(rayleighfunc.ppf(0.001), rayleighfunc.ppf(0.999), 1000) plt.plot(xl, rayleighfunc.pdf(xl)) # plt.axvline(np.log10(np.mean(x)),color="red") plt.axvline(np.mean(x), color="red") # plt.yscale("log") print("mean=", np.mean(x)) plt.title("Rayleigh Distribution") plt.show()
unit="m/s") analysis.fit(method='mle') # Capturando los parametros de weibull forma = analysis.stats[3] escala = analysis.stats[6] count, bins, ignored = plt.hist( dfaux["Viento - Velocidad (m/s)"], bins=range(0, int(dfaux["Viento - Velocidad (m/s)"].max() + 2))) ab = np.arange(0, int(dfaux["Viento - Velocidad (m/s)"].max() + 2)) x = np.linspace(min(dfaux["Viento - Velocidad (m/s)"]), max(dfaux["Viento - Velocidad (m/s)"]), sum(count)) scale = count.max() / weib(x, escala, forma).max() # Capturando Parametros de Rayleigh param = rayleigh.fit( dfaux["Viento - Velocidad (m/s)"]) # distribution fitting pdf_fitted = rayleigh.pdf(x, loc=param[0], scale=param[1]) plt.plot(x, weib(x, escala, forma) * scale, '-b', label='Weibull') plt.plot(x, pdf_fitted * scale, '-r', label='Rayleigh') # incorporando RAyleigh plt.xlabel("Vel. Viento [m/s]") plt.ylabel("Distribucion de frecuencia") plt.title("Distribucion de Weibull") plt.legend(loc='upper right') # j = mes # i = anio #****************************************************************** # Generacion de Tablas de Frecuencia , PDF, y CDF #****************************************************************** histo, binEdges = np.histogram( dfaux['Viento - Velocidad (m/s)'], bins=range(0, int(dfaux["Viento - Velocidad (m/s)"].max() + 2)))
def curvaDeAjuste(): #leer datos del archivo csv data = np.loadtxt("xy.csv", delimiter=',', skiprows=1, usecols=range(1,22)) #inicializar probabilidades de "x" y "y" para formato histograma xProbabilities = [] #inicializar arreglo vacío de probabilidades de x xList = [] #inicializar arreglo vacío para lista horizontal de x xRayleighSamples = [] #inicializar sample list para Rayleigh yProbabilities = [] #inicializar arreglo vacío de probabilidades de y yList = [] #inicializar arreglo vacío para lista horizontal de y yRayleighSamples = [] #inicializar sample list para Rayleigh rayleighMultiplier = 100 #determinar multiplicador para longitud de lista de valores de rayleigh #recorrer rows x5-x15 for i in range(5,16): xRow = data[i-5, :] #xi xVal = np.sum(xRow) #suma de valores xProbabilities.append(xVal) xList.append(i) temp = int(round(xVal*rayleighMultiplier)) #obtener valor temporal para datos de Rayleigh de distribución dada for j in range(0,temp): xRayleighSamples.append(i) #añadir otro datapoint correspondiente a i #recorrer columnas y5-y25 for i in range(5,26): yCol = data[:,i-5] #yi yVal = np.sum(yCol) #suma de valores yProbabilities.append(yVal) yList.append(i) temp = int(round(xVal*rayleighMultiplier)) #obtener valor temporal para datos de Rayleigh de distribución dada for j in range(0,temp): yRayleighSamples.append(i) #añadir otro datapoint correspondiente a i ## PARA X # obtener fit data con curva gaussiana parsX, covX = curve_fit(f=gaussian, xdata=xList, ydata=xProbabilities, p0=[6,10,14], bounds=(-np.inf, np.inf)) stdevsX = np.sqrt(np.diag(covX)) #print(stdevsX) plt.figure() # Plot fit data Gaussiana como overlay en cima de los puntos ya determinados del histograma plt.scatter(xList, xProbabilities, s=10, color='#00b3b3', label='Data') plt.plot(xList, gaussian(xList, *parsX), linestyle='--', linewidth=2, color='black') plt.title('Curva de Ajuste de Gauss para X') plt.ylabel('Probabilidad') plt.xlabel('Valor de X') plt.legend(['Ajuste de Rayleigh','Probabilidad de X']) plt.savefig('curvaAjuste_x_Gaussian.png') #guardar imagen en folder # obtener fit data con curva de lorentz (tiene pico más pronunciado) parsX, covX = curve_fit(f=lorentzian, xdata=xList, ydata=xProbabilities, p0=[0.14,10,4], bounds=(-np.inf, np.inf)) stdevsX = np.sqrt(np.diag(covX)) #print(stdevsX) plt.figure() # Plot fit data Lorentz como overlay en cima de los puntos ya determinados del histograma plt.scatter(xList, xProbabilities, s=10, color='#00b3b3', label='Data') plt.plot(xList, lorentzian(xList, *parsX), linestyle='--', linewidth=2, color='black') plt.title('Curva de Ajuste de Lorentz para X') plt.ylabel('Probabilidad') plt.xlabel('Valor de X') plt.legend(['Ajuste de Rayleigh','Probabilidad de X']) plt.savefig('curvaAjuste_x_Lorentzian.png') #guardar imagen en folder # obtener fit data con curva de rayleigh (distribución normal con peso de un lado) param = rayleigh.fit(xRayleighSamples) pdf_fitted = rayleigh.pdf(xList,loc=param[0],scale=param[1]) plt.figure() plt.scatter(xList, xProbabilities, s=10, color='#00b3b3', label='Data') plt.plot(xList,pdf_fitted, linestyle='--', linewidth=2, color='black') plt.title('Curva de Ajuste de Rayleigh para X') plt.ylabel('Probabilidad') plt.xlabel('Valor de X') plt.legend(['Ajuste de Rayleigh','Probabilidad de X']) plt.savefig('curvaAjuste_x_Rayleigh.png') #guardar imagen en folder # obtener fit data con curva voigt (distribución de Gauss y Lorentz con peso) parsX, covX = curve_fit(f=voigt, xdata=xList, ydata=xProbabilities, p0=[0.5,10,4], bounds=(-np.inf, np.inf)) stdevsX = np.sqrt(np.diag(covX)) #print(stdevsX) plt.figure() # Plot fit data Voigt como overlay en cima de los puntos ya determinados de probabilidades plt.scatter(xList, xProbabilities, s=10, color='#00b3b3', label='Data') plt.plot(xList, voigt(xList, *parsX), linestyle='--', linewidth=2, color='black') plt.title('Curva de Ajuste de Voigt para X') plt.ylabel('Probabilidad') plt.xlabel('Valor de X') plt.legend(['Ajuste de Voigt','Probabilidad de X']) plt.savefig('curvaAjuste_x_Voigt.png') #guardar imagen en folder ## PARA Y # obtener fit data con curva gaussiana (distribución normal) parsY, covY = curve_fit(f=gaussian, xdata=yList, ydata=yProbabilities, p0=[6,15,24], bounds=(-np.inf, np.inf)) stdevsY = np.sqrt(np.diag(covY)) plt.figure() # Plot fit data Gaussiana como overlay en cima de los puntos ya determinados del histograma plt.scatter(yList, yProbabilities, s=10, color='#00b3b3', label='Data') plt.plot(yList, gaussian(yList, *parsY), linestyle='--', linewidth=2, color='black') plt.title('Curva de Ajuste de Gauss para Y') plt.ylabel('Probabilidad') plt.xlabel('Valor de Y') plt.legend(['Ajuste de Gauss','Probabilidad de Y']) plt.savefig('curvaAjuste_y_Gaussian.png') #guardar imagen en folder # obtener fit data con curva de lorentz (tiene pico más pronunciado) parsY, covY = curve_fit(f=lorentzian, xdata=yList, ydata=yProbabilities, p0=[0.14,15,2], bounds=(-np.inf, np.inf)) stdevsY = np.sqrt(np.diag(covY)) plt.figure() # Plot fit data Lorentz como overlay en cima de los puntos ya determinados del histograma plt.scatter(yList, yProbabilities, s=10, color='#00b3b3', label='Data') plt.plot(yList, lorentzian(yList, *parsY), linestyle='--', linewidth=2, color='black') plt.title('Curva de Ajuste de Lorentz para Y') plt.ylabel('Probabilidad') plt.xlabel('Valor de Y') plt.legend(['Ajuste de Lorentz','Probabilidad de Y']) plt.savefig('curvaAjuste_y_Lorentzian.png') #guardar imagen en folder # obtener fit data con curva de rayleigh (distribución normal con peso de un lado) param = rayleigh.fit(yRayleighSamples) pdf_fitted = rayleigh.pdf(yList,loc=param[0],scale=param[1]) plt.figure() plt.scatter(yList, yProbabilities, s=10, color='#00b3b3', label='Data') plt.plot(yList, pdf_fitted, linestyle='--', linewidth=2, color='black') plt.title('Curva de Ajuste de Rayleigh para Y') plt.ylabel('Probabilidad') plt.xlabel('Valor de Y') plt.legend(['Ajuste de Rayleigh','Probabilidad de Y']) plt.savefig('curvaAjuste_y_Rayleigh.png') #guardar imagen en folder # obtener fit data con curva voigt (distribución de Gauss y Lorentz con peso) parsY, covY = curve_fit(f=voigt, xdata=yList, ydata=yProbabilities, p0=[0.5,10,4], bounds=(-np.inf, np.inf)) stdevsY = np.sqrt(np.diag(covY)) plt.figure() # Plot fit data Voigt como overlay en cima de los puntos ya determinados de probabilidades plt.scatter(yList, yProbabilities, s=10, color='#00b3b3', label='Data') plt.plot(yList, voigt(yList, *parsY), linestyle='--', linewidth=2, color='black') plt.title('Curva de Ajuste de Voigt para Y') plt.ylabel('Probabilidad') plt.xlabel('Valor de Y') plt.legend(['Ajuste de Voigt','Probabilidad de Y']) plt.savefig('curvaAjuste_y_Voigt.png') #guardar imagen en folder print("Gracias a las gráficas anteriores es claro que la función indicada es la de Voigt: (ampG1*(1/(sigmaG1*(np.sqrt(2*np.pi))))*(np.exp(-((x-cenG1)**2)/((2*sigmaG1)**2)))) +\((ampL1*widL1**2/((x-cenL1)**2+widL1**2)) \n\nPara x, los parámetros son: ") print(parsX) print("Para y, los parámetros son: ") print(parsY) print("\nLas graficas de Voigt corresponden a las gráficas de las funciones de mejor ajuste. Las funciones se grafican de forma separada de los datos utilizando el código anterior.") plt.figure() # Plot fit data Voigt como overlay en cima de los puntos ya determinados de probabilidades plt.plot(xList, voigt(xList, *parsX), linestyle='--', linewidth=2, color='black') plt.title('Función de Densidad Marginal (Voigt) para X') plt.ylabel('Probabilidad') plt.xlabel('Valor de X') plt.legend(['Ajuste de Voigt']) plt.savefig('x_Voigt.png') #guardar imagen en folder plt.figure() # Plot fit data Voigt como overlay en cima de los puntos ya determinados de probabilidades plt.plot(yList, voigt(yList, *parsY), linestyle='--', linewidth=2, color='black') plt.title('Función de Densidad Marginal (Voigt) para Y') plt.ylabel('Probabilidad') plt.xlabel('Valor de Y') plt.legend(['Ajuste de Voigt']) plt.savefig('y_Voigt.png') #guardar imagen en folder return
def gen_wind_histogram(interval, wind_speed_figure, sliderValue, auto_state): wind_val = [] # Check to see whether wind-speed has been plotted yet if wind_speed_figure is not None: wind_val = wind_speed_figure['data'][0]['y'] if 'Auto' in auto_state: bin_val = np.histogram(wind_val, bins=range(int(round(min(wind_val))), int(round(max(wind_val))))) else: bin_val = np.histogram(wind_val, bins=sliderValue) avg_val = float(sum(wind_val)) / len(wind_val) median_val = np.median(wind_val) pdf_fitted = rayleigh.pdf(bin_val[1], loc=(avg_val) * 0.55, scale=(bin_val[1][-1] - bin_val[1][0]) / 3) y_val = pdf_fitted * max(bin_val[0]) * 20, y_val_max = max(y_val[0]) bin_val_max = max(bin_val[0]) trace = Bar(x=bin_val[1], y=bin_val[0], marker=Marker(color='#7F7F7F'), showlegend=False, hoverinfo='x+y') trace1 = Scatter(x=[bin_val[int(len(bin_val) / 2)]], y=[0], mode='lines', line=Line(dash='dash', color='#2E5266'), marker=Marker(opacity=0, ), visible=True, name='Average') trace2 = Scatter(x=[bin_val[int(len(bin_val) / 2)]], y=[0], line=Line(dash='dot', color='#BD9391'), mode='lines', marker=Marker(opacity=0, ), visible=True, name='Median') trace3 = Scatter(mode='lines', line=Line(color='#42C4F7'), y=y_val[0], x=bin_val[1][:len(bin_val[1])], name='Rayleigh Fit') layout = Layout(xaxis=dict(title='Wind Speed (mph)', showgrid=False, showline=False, fixedrange=True), yaxis=dict(showgrid=False, showline=False, zeroline=False, title='Number of Samples', fixedrange=True), margin=Margin(t=50, b=20, r=50), autosize=True, bargap=0.01, bargroupgap=0, hovermode='closest', legend=Legend(x=0.175, y=-0.2, orientation='h'), shapes=[ dict(xref='x', yref='y', y1=int(max(bin_val_max, y_val_max)) + 0.5, y0=0, x0=avg_val, x1=avg_val, type='line', line=Line(dash='dash', color='#2E5266', width=5)), dict(xref='x', yref='y', y1=int(max(bin_val_max, y_val_max)) + 0.5, y0=0, x0=median_val, x1=median_val, type='line', line=Line(dash='dot', color='#BD9391', width=5)) ]) return Figure(data=[trace, trace1, trace2, trace3], layout=layout)
from scipy.stats import rayleigh import numpy as np import matplotlib.pyplot as plt k = 0.5 x = np.arange(0.01,1,0.01) print(x) temp1 = rayleigh.cdf(x,k) temp2 = rayleigh.pdf(x,k) 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 gen_wind_histogram(interval, wind_speed_figure, slider_value, auto_state): """ Genererate wind histogram graph. :params interval: upadte the graph based on an interval :params wind_speed_figure: current wind speed graph :params slider_value: current slider value :params auto_state: current auto state """ wind_val = [] try: # Check to see whether wind-speed has been plotted yet if wind_speed_figure is not None: wind_val = wind_speed_figure["data"][0]["y"] if "Auto" in auto_state: bin_val = np.histogram( wind_val, bins=range(int(round(min(wind_val))), int(round(max(wind_val)))), ) else: bin_val = np.histogram(wind_val, bins=slider_value) except Exception as error: raise PreventUpdate avg_val = float(sum(wind_val)) / len(wind_val) median_val = np.median(wind_val) pdf_fitted = rayleigh.pdf( bin_val[1], loc=(avg_val) * 0.55, scale=(bin_val[1][-1] - bin_val[1][0]) / 3 ) y_val = (pdf_fitted * max(bin_val[0]) * 20,) y_val_max = max(y_val[0]) bin_val_max = max(bin_val[0]) trace = dict( type="bar", x=bin_val[1], y=bin_val[0], marker={"color": app_color["graph_line"]}, showlegend=False, hoverinfo="x+y", ) traces_scatter = [ {"line_dash": "dash", "line_color": "#2E5266", "name": "Average"}, {"line_dash": "dot", "line_color": "#BD9391", "name": "Median"}, ] scatter_data = [ dict( type="scatter", x=[bin_val[int(len(bin_val) / 2)]], y=[0], mode="lines", line={"dash": traces["line_dash"], "color": traces["line_color"]}, marker={"opacity": 0}, visible=True, name=traces["name"], ) for traces in traces_scatter ] trace3 = dict( type="scatter", mode="lines", line={"color": "#42C4F7"}, y=y_val[0], x=bin_val[1][: len(bin_val[1])], name="Rayleigh Fit", ) layout = dict( height=350, plot_bgcolor=app_color["graph_bg"], paper_bgcolor=app_color["graph_bg"], font={"color": "#fff"}, xaxis={ "title": "Wind Speed (mph)", "showgrid": False, "showline": False, "fixedrange": True, }, yaxis={ "showgrid": False, "showline": False, "zeroline": False, "title": "Number of Samples", "fixedrange": True, }, autosize=True, bargap=0.01, bargroupgap=0, hovermode="closest", legend={ "orientation": "h", "yanchor": "bottom", "xanchor": "center", "y": 1, "x": 0.5, }, shapes=[ { "xref": "x", "yref": "y", "y1": int(max(bin_val_max, y_val_max)) + 0.5, "y0": 0, "x0": avg_val, "x1": avg_val, "type": "line", "line": {"dash": "dash", "color": "#2E5266", "width": 5}, }, { "xref": "x", "yref": "y", "y1": int(max(bin_val_max, y_val_max)) + 0.5, "y0": 0, "x0": median_val, "x1": median_val, "type": "line", "line": {"dash": "dot", "color": "#BD9391", "width": 5}, }, ], ) return dict(data=[trace, scatter_data[0], scatter_data[1], trace3], layout=layout)
plt.ylabel("Frecuencia de aparición") plt.show() """ 5) Con los datos contenidos en datos.csv, encontrar la mejor curva de ajuste y graficar la curva de ajuste encontrada """ #Gráfica todas las curvas. plt.hist(DATOS, bins=BINS, alpha=0.7, color="lightblue", normed=True) xt = plt.xticks()[0] xmin, xmax = 0, max(xt) lnspc = np.linspace(xmin, xmax, len(DATOS)) c, d = rayleigh.fit(DATOS) modelo = rayleigh(c, d) pdf_g = rayleigh.pdf(lnspc, c, d) plt.plot(lnspc, pdf_g, 'k-', lw=5, alpha=1, color="blue", label='Rayleigh') e, f = norm.fit(DATOS) pdf_g = norm.pdf(lnspc, e, f) plt.plot(lnspc, pdf_g, 'r-', lw=2, alpha=0.5, color="red", label='Normal') g, h = uniform.fit(DATOS) pdf_g = uniform.pdf(lnspc, g, h) plt.plot(lnspc, pdf_g, 'r-', lw=2, alpha=0.5, color="black", label='Uniforme')