def c_impl(x, y, modelo, seeds, porcentaje, N):
    '''
    Realiza lo mismo que la funcion c_manual, pero determina la distancia
    maxima entre CDFs y el intervalo de confianza con algoritmos
    predeterminados.
    '''
    # Datos a modelar
    datos_sinteticos = np.linspace(np.min(x), np.max(x), N)
    # Parametros optimos del modelo
    popt = fitear_implementado(modelo, x, y, seed=seeds)
    # Crear datos segun modelo y ordenarlos
    y_sint = np.sort(modelo(datos_sinteticos, *popt))
    # Ordenar datos experimentales
    y_datos = np.sort(y)
    # Crear CDF del modelo
    cdf = funcion_cdf(y_datos, y_sint)
    # Encontrar maxima diferencia entre CDF experimental y CDF del modelo
    n = len(y)
    # Crear objeto de Kolmogorov-Smirnov
    ks_dist_g = kstwobign()
    # Porcentaje de confianza
    alpha = porcentaje / 100.
    # Distancia critica de diferencia entre CDF para el porcentaje dado
    Dn_crit = ks_dist_g.ppf(1 - alpha) / np.sqrt(n)
    # Distancia maxima entre CDFs y nivel de confianza
    Dn, confianza = kstest(y_datos, funcion_cdf, args=(y_sint,))
    return y_sint, y_datos, cdf, Dn, Dn_crit, confianza
def c_manual(x, y, modelo, seeds, porcentaje, N):
    '''
    Determina la confiabilidad del modelo propuesto para fitear los datos
    'x' y 'y' ingresados a partir de un porcentaje de confiabilidad aceptado.
    N es el numero de datos sinteticos a crear para realizar la comparacion.
    Retorna los parametros utilizados para determinar la confiabilidad.
    '''
    # Datos a modelar
    datos_sinteticos = np.linspace(np.min(x), np.max(x), N)
    # Parametros optimos del modelo
    popt = fitear_implementado(modelo, x, y, seed=seeds)
    # Crear datos segun modelo y ordenarlos
    y_sint = np.sort(modelo(datos_sinteticos, *popt))
    # Ordenar datos experimentales
    y_datos = np.sort(y)
    # Crear CDF del modelo
    cdf = funcion_cdf(y_datos, y_sint)
    # Encontrar maxima diferencia entre CDF experimental y CDF del modelo
    n = len(y)
    max1 = np.max(cdf - np.arange(n) / n)
    max2 = np.max(np.arange(1, n + 1) / n - cdf)
    Dn = max(max1, max2)
    # Crear objeto de Kolmogorov-Smirnov
    ks_dist_g = kstwobign()
    # Porcentaje de confianza
    alpha = porcentaje / 100.
    # Distancia critica de diferencia entre CDF para el porcentaje dado
    Dn_crit = ks_dist_g.ppf(1 - alpha) / np.sqrt(n)
    # Calcular nivel de confianza para el Dn obtenido
    confianza = 1 - ks_dist_g.cdf(Dn * np.sqrt(n))
    return y_sint, y_datos, cdf, Dn, Dn_crit, confianza
Beispiel #3
0
def prueba_ks(x_exp, y_exp, modelo, p_opt, titulo):
    '''
    realiza la prueba completa de kolmogorov-smirnov y grafica las funciones
    de probabilidad acumulada y muestra el d_n critico
    '''
    # D_n y confianza
    xmin = np.min(x_exp)
    xmax = np.max(x_exp)
    y_modelo_ord = np.sort(modelo(p_opt, np.linspace(xmin, xmax, 1000)))
    y_exp_ord = np.sort(y_exp)
    Dn, prob = kstest(y_exp_ord, cdf, args=(y_modelo_ord, ))
    # D_n critico
    N = len(y_exp_ord)
    ks_dist = kstwobign()
    alpha = 0.05
    Dn_critico = ks_dist.ppf(1 - alpha) / np.sqrt(N)
    # graficos
    CDF = cdf(y_exp_ord, y_modelo_ord)
    ax, fig = plt.subplots()
    plt.plot(y_exp_ord,
             np.arange(N) / N,
             '-^',
             drawstyle='steps-post',
             label="Datos")
    plt.plot(y_exp_ord, np.arange(1, N + 1) / N, '-.', drawstyle='steps-post')
    plt.plot(y_exp_ord, CDF, '-+', drawstyle='steps-post', label="Modelo")
    fig.set_xlabel("Longitud de Onda [$\AA$]")
    fig.set_ylabel("Probabilidad")
    plt.legend(loc=2)
    plt.savefig("{}".format(titulo))
    plt.show()
    return Dn, prob, Dn_critico
Beispiel #4
0
def prueba_ks(x_exp, y_exp, modelo, p_opt, titulo):
    """
    realiza la prueba completa de kolmogorov-smirnov y grafica las funciones
    de probabilidad acumulada y muestra el d_n critico
    """
    # D_n y confianza
    xmin = np.min(x_exp)
    xmax = np.max(x_exp)
    y_modelo_ord = np.sort(modelo(p_opt, np.linspace(xmin, xmax, 1000)))
    y_exp_ord = np.sort(y_exp)
    Dn, prob = kstest(y_exp_ord, cdf, args=(y_modelo_ord,))
    # D_n critico
    N = len(y_exp_ord)
    ks_dist = kstwobign()
    alpha = 0.05
    Dn_critico = ks_dist.ppf(1 - alpha) / np.sqrt(N)
    # graficos
    CDF = cdf(y_exp_ord, y_modelo_ord)
    ax, fig = plt.subplots()
    plt.plot(y_exp_ord, np.arange(N) / N, "-^", drawstyle="steps-post", label="Datos")
    plt.plot(y_exp_ord, np.arange(1, N + 1) / N, "-.", drawstyle="steps-post")
    plt.plot(y_exp_ord, CDF, "-+", drawstyle="steps-post", label="Modelo")
    fig.set_xlabel("Longitud de Onda [$\AA$]")
    fig.set_ylabel("Probabilidad")
    plt.legend(loc=2)
    plt.savefig("{}".format(titulo))
    plt.show()
    return Dn, prob, Dn_critico
Beispiel #5
0
def dn(x_data, y_data, a_opt, a_opt1):
    ''' esta función entregará el valor de Dn de cada modelo,
    si el dn es menor que el dn crítico hemos
    hecho un buen fit'''

    xmin = np.min(x_data)
    xmax = np.max(x_data)
    y_model_sorted = np.sort(modelo_1(np.linspace(xmin, xmax, 1000), *a_opt))
    y_model_sorted1 = np.sort(modelo_2(np.linspace(xmin, xmax, 1000), *a_opt1))
    y_data_sorted = np.sort(y_data)
    N = len(y_data_sorted)
    Dn_scipy, prob_scipy = kstest(y_data_sorted,
                                  cdf, args=(y_model_sorted,))
    Dn_scipy2, prob_scipy2 = kstest(y_data_sorted,
                                    cdf, args=(y_model_sorted1,))

    ks_dist = kstwobign()
    alpha = 0.05
    Dn_critico = ks_dist.ppf(1 - alpha) / np.sqrt(N)
    print "Dn_critico = ", Dn_critico
    print "Dn Gaussiana = ", Dn_scipy
    print "nivel de confianza", prob_scipy
    print "Dn Lorenz = ", Dn_scipy2
    print "nivel de confianza =", prob_scipy2
Dip = DD.argmax()
Dplus = DD[Dip]
DD = cdf_hypo - cdf_data_lo
Dim = DD.argmax()
Dmin = DD[Dim]
if Dplus >= Dmin:
    Di = Dip
else:
    Di = Dim
Dmax = max(Dplus, Dmin)

header = "\n============= Kolmogorov-Smirnov statistics ============="
print(header)
from scipy.stats import kstwobign
# Routine based on NR. It's a good approximation for N>4
dist = kstwobign()
alphas = [0.2, 0.1, 0.05, 0.025, 0.01]
# Select significance level for rejecting null hypothesis
alpha = 0.05  # 10%
for a in alphas:
    Dn_crit = dist.ppf(1 - a) / numpy.sqrt(N)
    print("Critical value of D at alpha=%.3f(two sided):  %g" % (a, Dn_crit))
print("Selected alpha:               :", alpha)
print("This implies that in %d%% of the time we reject H0 while it is true." %
      (alpha * 100))
Dn_crit = dist.ppf(1 - alpha) / numpy.sqrt(N)
print("\nCritical value of D from kstwobign() at alpha=%g(two sided):  %g" %
      (alpha, Dn_crit))
print("Dplus, Dmin                   :", Dplus, Dmin)
print("Dmax                          :", Dmax)
print("Confidence level kstwobign()  :", dist.sf(Dmax * numpy.sqrt(N)))
Beispiel #7
0
def general_fit(x, y, model_to_fit, initial_guess, x_err = None, y_err = None):
	""" x, y are the data which we want to fit.
		The model_to_fit has the following form: 
		model_to_fit = lambda parameter, data: parameter[0]*data + parameter[1],
		and the parameter is a list.
		The initial guess for the parameters is initial_guess = [a, b]"""
	
	# Save the model in the needed form	
	odr_model = Model(model_to_fit)
	
	# Save the data with errors if given in the needed form
	if (y_err is None) and (x_err is None):
		odr_data = RealData(x, y)
	elif x_err is None:
		odr_data = RealData(x, y, sy = y_err)
	elif y_err is None:
		odr_data = RealData(x, y, sx = x_err)
	else:
		odr_data = RealData(x, y, sx = x_err, sy = y_err)
	
	# This value tells the number of data points - degrees of freedom
	degrees_of_freedom = x.shape[0] - len(initial_guess)
	
	myodr = ODR(odr_data, odr_model, beta0 = initial_guess)
	
	# Runs the fitting and saves the found parameters and there errors
	odr_output = myodr.run()
	odr_parameter_ideal = odr_output.beta
	odr_parameter_error = odr_output.sd_beta
	
	### This part is to calculate the p-value of the fit and for this we 
	### need first to calculate chi2
	
	if y_err is None:
		# We make a distinguish between the general case and if yerr=None, 
		# there we need to use a different test which is called the 
		# Kolmogorov-Smirnov test.
		
		# We compute the cdf
		N = y.shape[0]
		z = sort(y)
		cdf_data_high = arange(1.0, N+1.0)/N
		cdf_data_low = arange(0.0, 1.0*N)/N
		X = linspace(min(x), max(x), 300)
		fitted_values = model_to_fit(odr_parameter_ideal, X)
		fitted_values.sort()
		cdf_fitted = cdf(z, fitted_values)
    	
    		# Find biggest distance between cumulative functions
		DD = cdf_data_high - cdf_fitted
        	Dip = DD.argmax()
        	Dplus = DD[Dip]
        	DD = cdf_fitted - cdf_data_lo
        	Dim = DD.argmax()
        	Dmin = DD[Dim]
        	if Dplus >= Dmin:
			Di = Dip
		else:
			Di = Dim
        	Dmax = max(Dplus, Dmin)

        	rv = kstwobign()

        	odr_p_value = 1.0 - rv.cdf(Dmax)

	else:
		# This is for the general case.
		chi_squarred = sum((y - model_to_fit(odr_parameter_ideal, x))**2/y_err**2)
		odr_p_value = 1.0 - chi2.cdf(chi_squarred, degrees_of_freedom)

	return odr_parameter_ideal, odr_parameter_error, odr_p_value
Beispiel #8
0
def all_dists():
    # dists param were taken from scipy.stats official
    # documentaion examples
    # Total - 89
    return {
        "alpha":
        stats.alpha(a=3.57, loc=0.0, scale=1.0),
        "anglit":
        stats.anglit(loc=0.0, scale=1.0),
        "arcsine":
        stats.arcsine(loc=0.0, scale=1.0),
        "beta":
        stats.beta(a=2.31, b=0.627, loc=0.0, scale=1.0),
        "betaprime":
        stats.betaprime(a=5, b=6, loc=0.0, scale=1.0),
        "bradford":
        stats.bradford(c=0.299, loc=0.0, scale=1.0),
        "burr":
        stats.burr(c=10.5, d=4.3, loc=0.0, scale=1.0),
        "cauchy":
        stats.cauchy(loc=0.0, scale=1.0),
        "chi":
        stats.chi(df=78, loc=0.0, scale=1.0),
        "chi2":
        stats.chi2(df=55, loc=0.0, scale=1.0),
        "cosine":
        stats.cosine(loc=0.0, scale=1.0),
        "dgamma":
        stats.dgamma(a=1.1, loc=0.0, scale=1.0),
        "dweibull":
        stats.dweibull(c=2.07, loc=0.0, scale=1.0),
        "erlang":
        stats.erlang(a=2, loc=0.0, scale=1.0),
        "expon":
        stats.expon(loc=0.0, scale=1.0),
        "exponnorm":
        stats.exponnorm(K=1.5, loc=0.0, scale=1.0),
        "exponweib":
        stats.exponweib(a=2.89, c=1.95, loc=0.0, scale=1.0),
        "exponpow":
        stats.exponpow(b=2.7, loc=0.0, scale=1.0),
        "f":
        stats.f(dfn=29, dfd=18, loc=0.0, scale=1.0),
        "fatiguelife":
        stats.fatiguelife(c=29, loc=0.0, scale=1.0),
        "fisk":
        stats.fisk(c=3.09, loc=0.0, scale=1.0),
        "foldcauchy":
        stats.foldcauchy(c=4.72, loc=0.0, scale=1.0),
        "foldnorm":
        stats.foldnorm(c=1.95, loc=0.0, scale=1.0),
        # "frechet_r": stats.frechet_r(c=1.89, loc=0.0, scale=1.0),
        # "frechet_l": stats.frechet_l(c=3.63, loc=0.0, scale=1.0),
        "genlogistic":
        stats.genlogistic(c=0.412, loc=0.0, scale=1.0),
        "genpareto":
        stats.genpareto(c=0.1, loc=0.0, scale=1.0),
        "gennorm":
        stats.gennorm(beta=1.3, loc=0.0, scale=1.0),
        "genexpon":
        stats.genexpon(a=9.13, b=16.2, c=3.28, loc=0.0, scale=1.0),
        "genextreme":
        stats.genextreme(c=-0.1, loc=0.0, scale=1.0),
        "gausshyper":
        stats.gausshyper(a=13.8, b=3.12, c=2.51, z=5.18, loc=0.0, scale=1.0),
        "gamma":
        stats.gamma(a=1.99, loc=0.0, scale=1.0),
        "gengamma":
        stats.gengamma(a=4.42, c=-3.12, loc=0.0, scale=1.0),
        "genhalflogistic":
        stats.genhalflogistic(c=0.773, loc=0.0, scale=1.0),
        "gilbrat":
        stats.gilbrat(loc=0.0, scale=1.0),
        "gompertz":
        stats.gompertz(c=0.947, loc=0.0, scale=1.0),
        "gumbel_r":
        stats.gumbel_r(loc=0.0, scale=1.0),
        "gumbel_l":
        stats.gumbel_l(loc=0.0, scale=1.0),
        "halfcauchy":
        stats.halfcauchy(loc=0.0, scale=1.0),
        "halflogistic":
        stats.halflogistic(loc=0.0, scale=1.0),
        "halfnorm":
        stats.halfnorm(loc=0.0, scale=1.0),
        "halfgennorm":
        stats.halfgennorm(beta=0.675, loc=0.0, scale=1.0),
        "hypsecant":
        stats.hypsecant(loc=0.0, scale=1.0),
        "invgamma":
        stats.invgamma(a=4.07, loc=0.0, scale=1.0),
        "invgauss":
        stats.invgauss(mu=0.145, loc=0.0, scale=1.0),
        "invweibull":
        stats.invweibull(c=10.6, loc=0.0, scale=1.0),
        "johnsonsb":
        stats.johnsonsb(a=4.32, b=3.18, loc=0.0, scale=1.0),
        "johnsonsu":
        stats.johnsonsu(a=2.55, b=2.25, loc=0.0, scale=1.0),
        "ksone":
        stats.ksone(n=1e03, loc=0.0, scale=1.0),
        "kstwobign":
        stats.kstwobign(loc=0.0, scale=1.0),
        "laplace":
        stats.laplace(loc=0.0, scale=1.0),
        "levy":
        stats.levy(loc=0.0, scale=1.0),
        "levy_l":
        stats.levy_l(loc=0.0, scale=1.0),
        "levy_stable":
        stats.levy_stable(alpha=0.357, beta=-0.675, loc=0.0, scale=1.0),
        "logistic":
        stats.logistic(loc=0.0, scale=1.0),
        "loggamma":
        stats.loggamma(c=0.414, loc=0.0, scale=1.0),
        "loglaplace":
        stats.loglaplace(c=3.25, loc=0.0, scale=1.0),
        "lognorm":
        stats.lognorm(s=0.954, loc=0.0, scale=1.0),
        "lomax":
        stats.lomax(c=1.88, loc=0.0, scale=1.0),
        "maxwell":
        stats.maxwell(loc=0.0, scale=1.0),
        "mielke":
        stats.mielke(k=10.4, s=3.6, loc=0.0, scale=1.0),
        "nakagami":
        stats.nakagami(nu=4.97, loc=0.0, scale=1.0),
        "ncx2":
        stats.ncx2(df=21, nc=1.06, loc=0.0, scale=1.0),
        "ncf":
        stats.ncf(dfn=27, dfd=27, nc=0.416, loc=0.0, scale=1.0),
        "nct":
        stats.nct(df=14, nc=0.24, loc=0.0, scale=1.0),
        "norm":
        stats.norm(loc=0.0, scale=1.0),
        "pareto":
        stats.pareto(b=2.62, loc=0.0, scale=1.0),
        "pearson3":
        stats.pearson3(skew=0.1, loc=0.0, scale=1.0),
        "powerlaw":
        stats.powerlaw(a=1.66, loc=0.0, scale=1.0),
        "powerlognorm":
        stats.powerlognorm(c=2.14, s=0.446, loc=0.0, scale=1.0),
        "powernorm":
        stats.powernorm(c=4.45, loc=0.0, scale=1.0),
        "rdist":
        stats.rdist(c=0.9, loc=0.0, scale=1.0),
        "reciprocal":
        stats.reciprocal(a=0.00623, b=1.01, loc=0.0, scale=1.0),
        "rayleigh":
        stats.rayleigh(loc=0.0, scale=1.0),
        "rice":
        stats.rice(b=0.775, loc=0.0, scale=1.0),
        "recipinvgauss":
        stats.recipinvgauss(mu=0.63, loc=0.0, scale=1.0),
        "semicircular":
        stats.semicircular(loc=0.0, scale=1.0),
        "t":
        stats.t(df=2.74, loc=0.0, scale=1.0),
        "triang":
        stats.triang(c=0.158, loc=0.0, scale=1.0),
        "truncexpon":
        stats.truncexpon(b=4.69, loc=0.0, scale=1.0),
        "truncnorm":
        stats.truncnorm(a=0.1, b=2, loc=0.0, scale=1.0),
        "tukeylambda":
        stats.tukeylambda(lam=3.13, loc=0.0, scale=1.0),
        "uniform":
        stats.uniform(loc=0.0, scale=1.0),
        "vonmises":
        stats.vonmises(kappa=3.99, loc=0.0, scale=1.0),
        "vonmises_line":
        stats.vonmises_line(kappa=3.99, loc=0.0, scale=1.0),
        "wald":
        stats.wald(loc=0.0, scale=1.0),
        "weibull_min":
        stats.weibull_min(c=1.79, loc=0.0, scale=1.0),
        "weibull_max":
        stats.weibull_max(c=2.87, loc=0.0, scale=1.0),
        "wrapcauchy":
        stats.wrapcauchy(c=0.0311, loc=0.0, scale=1.0),
    }
Beispiel #9
0
plt.plot(fnu_datos_gauss, cdf_gauss, 'r-^', drawstyle='steps-post')
plt.title('CDF Gauss')
plt.xlabel('$F_{nu} $[$erg\ \  s^{-1}\ Hz^{-1}\ cm^{-2}$]')
plt.ylabel('Probabilidad')
plt.show()

# obtiene valores maximos de la distancia entre cdf de los datos y el modelo
max1g = np.max(cdf_gauss - np.arange(n) / n)
max2g = np.max(np.arange(1, n + 1) / n - cdf_gauss)
# guarda el maximo de los maximos
Dng = max(max1g, max2g)
print '----------------------------------------------'
print 'Gauss'
print 'Distacia Maxima entre CDF\'s =', Dng

ks_dist_g = kstwobign()  # crea el objeto de Kolmogorov-Smirnov two-sided test
alpha = 0.05  # tolerancia 5%
# obtiene la distancia critica como el punto en 95% de la distribucion
Dng_crit = ks_dist_g.ppf(1 - alpha) / np.sqrt(n)

print 'Distacia critica al 5% =', Dng_crit

print 'Nivel de confianza =', 1 - ks_dist_g.cdf(Dng * np.sqrt(n))

# test ya implementado
Dn_testg, prob_scipyg = kstest(fnu_datos_gauss, cdf, args=(fnu_modelo_gauss, ))

print 'Distacia Maxima entre CDF\'s implementado =', Dn_testg
print 'Nivel de confianza implementado =', prob_scipyg
print '----------------------------------------------'
Beispiel #10
0
chi2_2 = chi2([wavelength, Fnu], param_optimo2, modelo_2)
Dn_2, prob_2 = kstest(np.sort(Fnu), cdf,
                      args=(np.sort(modelo_2(x, m2, n2, A2, mu2, sigma2)),))
print 'Segundo modelo: recta menos perfil de Lorentz'
print 'Pendiente               :', m2
print 'Coeficiente de posicion :', n2
print 'Amplitud                :', A2
print 'mu                      :', mu2
print 'sigma                   :', sigma2
print 'Chi2                    :', chi2_2
print "Dn                      : ", Dn_2
print "Nivel de confianza      : ", prob_2
print ''

# Calculo Dn critico
ks_dist = kstwobign()
alpha = 0.05
Dn_critico = ks_dist.ppf(1 - alpha) / np.sqrt(len(Fnu))
print "Dn_critico = ", Dn_critico


# Plot
plt.figure(1)
plt.plot(wavelength, Fnu, color='darkcyan', drawstyle='steps-post',
         label='Datos')
plt.plot(x, modelo_1(x, m1, n1, A1, mu1, sigma1), color='blue',
         label='Modelo 1 (Gaussiana)')
plt.plot(x, modelo_2(x, m2, n2, A2, mu2, sigma2), color='fuchsia',
         label='Modelo 2 (Lorentz)')
plt.xlabel('Wavelength [$\AA$]', fontsize=16)
plt.ylabel('$F_v$[erg s$^{-1}$Hz$^{-1}$cm$^{-2}$]', fontsize=16)
mean, var, skew, kurt = kstwobign.stats(moments='mvsk')

# Display the probability density function (``pdf``):

x = np.linspace(kstwobign.ppf(0.01),
                kstwobign.ppf(0.99), 100)
ax.plot(x, kstwobign.pdf(x),
       'r-', lw=5, alpha=0.6, label='kstwobign 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 = kstwobign()
ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf')

# Check accuracy of ``cdf`` and ``ppf``:

vals = kstwobign.ppf([0.001, 0.5, 0.999])
np.allclose([0.001, 0.5, 0.999], kstwobign.cdf(vals))
# True

# Generate random numbers:

r = kstwobign.rvs(size=1000)

# And compare the histogram:

ax.hist(r, density=True, histtype='stepfilled', alpha=0.2)
Beispiel #12
0
ax2.plot(y_data_sorted, np.arange(1, N+1) / N, '-.', drawstyle='steps-post')
ax2.plot(y_data_sorted, CDF_model_Lorentz, 'g-x',
         drawstyle='steps-post', label="Modelo Lorentz")
ax2.set_title('Probabilidad acumulada')
ax2.set_xlabel('Longitud de onda $[Angstrom]$')
ax2.set_ylabel('Probabilidad')
ax2.legend(loc='upper left')
plt.tight_layout()
plt.draw()
plt.show()




#Ahora vemos cual es más acertado en base a la distancia con los puntos de la muestra, diremos que la distancia critica será Dn_critico

Dn_scipy_Gauss, prob_scipy_Gauss = kstest(y_data_sorted,
                                  cdf, args=(y_model_sorted_Gauss,))
print "Dn_scipy Gauss  : ", Dn_scipy_Gauss
print "Nivel de confianza (Gauss) : ", prob_scipy_Gauss

Dn_scipy_Lorentz, prob_scipy_Lorentz = kstest(y_data_sorted,
                                  cdf, args=(y_model_sorted_Lorentz,))
print "Dn_scipy Lorentz : ", Dn_scipy_Lorentz
print "Nivel de confianza (Lorentz) : ", prob_scipy_Lorentz

ks_dist = kstwobign() # two-sided, aproximacion para big N
alpha = 0.05
Dn_critico = ks_dist.ppf(1 - alpha) / np.sqrt(N)
print "Dn_critico = ", Dn_critico
Beispiel #13
0
ax.set_xlabel('Frecuencia [$erg$ $s^{-1} Hz^{-1} cm^{-2}$]')

# zoom en el plot
axins = zoomed_inset_axes(ax, 6, loc=6)
axins.plot(y_data_sorted, np.arange(N) / N, '-^', drawstyle='steps-post',
           color='b')
axins.plot(y_data_sorted, np.arange(1, N+1) / N, '-.', drawstyle='steps-post',
           color='b')
axins.plot(y_data_sorted, CDF_gauss, '-x', drawstyle='steps-post',
           label='Ajuste recta-gaussiana', color='g')
axins.plot(y_data_sorted, CDF_lorentz, '-x', drawstyle='steps-post',
           label='Ajuste recta-lorentz', color='r')

plt.yticks(visible=False)
plt.xticks(visible=False)
x1, x2, y1, y2 = 1.375 * 10**-16, 1.39 * 10**-16, 0.05, 0.09  # limites
axins.set_xlim(x1, x2)
axins.set_ylim(y1, y2)
mark_inset(ax, axins, loc1=1, loc2=4, fc="none", ec="0.5")

plt.draw()
plt.show()
plt.savefig('figura2.png')


# Dn critico
ks_dist = kstwobign()  # aproximacion para N grande
alpha = 0.05
Dn_critico = ks_dist.ppf(1 - alpha) / np.sqrt(N)
print "Dn_critico = ", Dn_critico
Beispiel #14
0
         CDF_model_Lorentz,
         'g-x',
         drawstyle='steps-post',
         label="Modelo Lorentz")
ax2.set_title('Probabilidad acumulada')
ax2.set_xlabel('Longitud de onda $[Angstrom]$')
ax2.set_ylabel('Probabilidad')
ax2.legend(loc='upper left')
plt.tight_layout()
plt.draw()
plt.show()

#Ahora vemos cual es más acertado en base a la distancia con los puntos de la muestra, diremos que la distancia critica será Dn_critico

Dn_scipy_Gauss, prob_scipy_Gauss = kstest(y_data_sorted,
                                          cdf,
                                          args=(y_model_sorted_Gauss, ))
print "Dn_scipy Gauss  : ", Dn_scipy_Gauss
print "Nivel de confianza (Gauss) : ", prob_scipy_Gauss

Dn_scipy_Lorentz, prob_scipy_Lorentz = kstest(y_data_sorted,
                                              cdf,
                                              args=(y_model_sorted_Lorentz, ))
print "Dn_scipy Lorentz : ", Dn_scipy_Lorentz
print "Nivel de confianza (Lorentz) : ", prob_scipy_Lorentz

ks_dist = kstwobign()  # two-sided, aproximacion para big N
alpha = 0.05
Dn_critico = ks_dist.ppf(1 - alpha) / np.sqrt(N)
print "Dn_critico = ", Dn_critico
Beispiel #15
0
plt.plot(fnu_datos_gauss, cdf_gauss, 'r-^', drawstyle='steps-post')
plt.title('CDF Gauss')
plt.xlabel('$F_{nu} $[$erg\ \  s^{-1}\ Hz^{-1}\ cm^{-2}$]')
plt.ylabel('Probabilidad')
plt.show()

# obtiene valores maximos de la distancia entre cdf de los datos y el modelo
max1g = np.max(cdf_gauss - np.arange(n) / n)
max2g = np.max(np.arange(1, n + 1) / n - cdf_gauss)
# guarda el maximo de los maximos
Dng = max(max1g, max2g)
print '----------------------------------------------'
print 'Gauss'
print 'Distacia Maxima entre CDF\'s =', Dng

ks_dist_g = kstwobign()  # crea el objeto de Kolmogorov-Smirnov two-sided test
alpha = 0.05  # tolerancia 5%
# obtiene la distancia critica como el punto en 95% de la distribucion
Dng_crit = ks_dist_g.ppf(1-alpha) / np.sqrt(n)

print 'Distacia critica al 5% =', Dng_crit

print 'Nivel de confianza =', 1 - ks_dist_g.cdf(Dng*np.sqrt(n))

# test ya implementado
Dn_testg, prob_scipyg = kstest(fnu_datos_gauss, cdf, args=(fnu_modelo_gauss,))

print 'Distacia Maxima entre CDF\'s implementado =', Dn_testg
print 'Nivel de confianza implementado =', prob_scipyg
print '----------------------------------------------'