In [9]:
from astropy import units as u
In [21]:
def gaussian_model(xarr, amplitude, offset, width):
amplitude = u.Quantity(amplitude, u.K)
offset = u.Quantity(offset, u.km/u.s)
width = u.Quantity(width, u.km/u.s)
xarr = u.Quantity(xarr, u.km/u.s)
return amplitude * np.exp(-(xarr-offset)**2/(2.*width**2))
In [14]:
x = 5
u.Quantity(x, u.km/u.s)
Out[14]:
In [15]:
x = 5 * u.m/u.s
u.Quantity(x, u.km/u.s)
Out[15]:
In [16]:
xarr = np.linspace(-5,5,50) * u.km/u.s
In [18]:
gaussian(xarr, 1*u.K, 0.5*u.km/u.s, 2000*u.m/u.s)
Out[18]:
In [12]:
%matplotlib inline
import pylab as pl
pl.plot(xarr, gaussian(xarr, 1, 0.5, 2))
Out[12]:
In [19]:
from specutils.io import fits
spec = fits.read_fits_spectrum1d('gbt_1d.fits')
In [20]:
pl.plot(spec.velocity, spec.flux, 'k-')
Out[20]:
In [22]:
model = gaussian_model(spec.velocity, amplitude=5*u.K, offset=5*u.km/u.s, width=5*u.km/u.s)
In [23]:
pl.plot(spec.velocity, spec.flux, 'k-')
pl.plot(spec.velocity, model, 'b-')
Out[23]:
In [32]:
spec.flux * u.K
Out[32]:
In [28]:
def cost_function(params, data_range=None):
if data_range is not None:
data = spec.flux[data_range]
else:
data = spec.flux
return (((data * u.K) - gaussian_model(spec.velocity, *params))**2).sum().value
In [29]:
params = (1,2,3)
def f(a,b,c):
print("a={0}, b={1}, c={2}".format(a,b,c))
f(1,2,3)
f(*params)
In [30]:
cost_function((5*u.K, 5*u.km/u.s, 5*u.km/u.s))
Out[30]:
In [33]:
from scipy.optimize import minimize
In [36]:
result = minimize(cost_function, (5, 5, 5), args=(slice(100,200),))
result
Out[36]:
In [38]:
(amplitude, offset, width) = result.x
In [39]:
best_fit_model = gaussian_model(spec.velocity, *result.x)
In [41]:
pl.plot(spec.velocity, spec.flux, 'k-')
pl.plot(spec.velocity, best_fit_model, 'r-')
pl.xlim(-30, 30)
Out[41]:
In [42]:
arr = np.arange(100)
In [43]:
arr[10:50]
Out[43]:
In [44]:
arr[slice(10,50)]
Out[44]:
In [ ]: