forked from uchileFI3104B-2015B/10Tarea
/
Tarea10.py
135 lines (105 loc) · 3.45 KB
/
Tarea10.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import scipy.stats
from scipy.optimize import leastsq, curve_fit
from scipy.stats import kstest
def datos():
'''
Lee el archivo y retorna sus columnas como 2 listas
'''
arch = np.loadtxt("espectro.dat")
wave = arch[:, 0]
flux = arch[:, 1]
return wave, flux
def rectagauss(x, a, b, A, mu, sigma):
'''
Retorna el ajuste para un modelo gaussiano
'''
recta = a + b * x
gauss = A * scipy.stats.norm(loc=mu, scale=sigma).pdf(x)
return recta - gauss
def rectalorentz(x, a, b, A, mu, sigma):
'''
Retorna el ajuste para un modelo lorentziano
'''
recta = a + b * x
lorentz = A * scipy.stats.cauchy(loc=mu, scale=sigma).pdf(x)
return recta - lorentz
def fit(funcion, x, y, seeds):
'''
Calcula coeficientes a y b de la ecuacion que
mejor fitea los vectores x,y.
'''
popt, pcov = curve_fit(funcion, x, y, seeds)
return popt
def chi(funcion, x, y, seeds_op):
'''
Retorna el chi^2 asociado a la ecuacion entrante
'''
X = 0
n = len(x)
for i in range(n):
X += (y[i] - funcion(x[i], *seeds_op))**2
return X
def errorgauss(seeds, wave, flux):
'''
Residuo del modelo gaussiano
'''
error = flux - rectagauss(wave, *seeds)
return error
def errorlorentz(seeds, wave, flux):
'''
Residuo del modelo lorentziano
'''
error = flux - rectalorentz(wave, *seeds)
return error
def cdf(data, funcion):
return np.array([np.sum(funcion <= yy) for yy in data]) / len(funcion)
def test_ks(wave, flux, p_optg, p_optl):
xmin = np.min(wave)
xmax = np.max(wave)
x = np.linspace(xmin, xmax, 1000)
# Gauss
y_gauss_ord = np.sort(rectagauss(x, *p_optg))
y_expg_ord = np.sort(flux)
dng, probg = kstest(y_expg_ord, cdf, args=(y_gauss_ord,))
# Lorentz
y_lorentz_ord = np.sort(rectalorentz(x, *p_optl))
y_expl_ord = np.sort(flux)
dnl, probl = kstest(y_expl_ord, cdf, args=(y_lorentz_ord,))
return probg, probl
# Setup
wave, flux = datos()
n = len(wave)
# Semillas para el ajuste, sacadas del grafico espectro (a, b, A, mu, sigma)
seeds = 9.e-17, 8.e-21, 1.e-17, 6550., 10.
# Main
# - - - P1 - - - #
poptg = fit(rectagauss, wave, flux, seeds) # Gaussiana
poptl = fit(rectalorentz, wave, flux, seeds) # Lorentziana
print 'Modelo Gauss:'
print 'a =', poptg[0], 'b =', poptg[1], 'A =', poptg[2], 'mu =', poptg[3],\
'sigma =', poptg[4], 'chi**2 = ', chi(rectagauss, wave, flux, poptg)
print 'Modelo Lorentz:'
print 'a =', poptl[0], 'b =', poptl[1], 'A =', poptl[2], 'mu =', poptl[3],\
'sigma =', poptl[4], 'chi**2 = ', chi(rectalorentz, wave, flux, poptl)
# - - - P2 - - - #
optimog = leastsq(errorgauss, seeds, args=(wave, flux))[0]
optimol = leastsq(errorlorentz, seeds, args=(wave, flux))[0]
ks = test_ks(wave, flux, optimog, optimol)
print 'Test KS Gauss:', ks[0]
print 'Test KS Lorentz:', ks[1]
# Grafico P1
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(wave, flux, 'y*-', alpha=0.5, label="Datos Experimentales")
ax1.plot(wave, rectalorentz(wave, *poptl), 'r-', linewidth='1.5',
label="Ajuste Lorentz")
ax1.plot(wave, rectagauss(wave, *poptg), 'g-', linewidth='1.5',
label="Ajuste Gauss")
ax1.set_xlabel("Longitud de onda $[Angstrom]$")
ax1.set_ylabel("Flujo por unidad de frecuencia $[erg s^{-1} Hz^{-1} cm^{-2}]$")
ax1.set_title("Espectro y sus ajustes")
plt.legend(loc='lower right')
plt.show()