In [1]:
def gaussian_model(xaxis, 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)
return amplitude*np.exp(-(xaxis-offset)**2/(2.*width**2))
In [2]:
from specutils.io import fits
spec = fits.read_fits_spectrum1d('gbt_1d.fits')
In [3]:
from astropy import units as u
In [4]:
%%bash
which conda
In [5]:
import specutils
import numpy
import astropy
specutils.__version__, astropy.__version__, numpy.__version__, astropy.__path__
Out[5]:
In [6]:
spec.velocity
Out[6]:
In [7]:
model = gaussian_model(spec.velocity, amplitude=5*u.K, offset=20*u.km/u.s, width=5*u.km/u.s)
In [8]:
%matplotlib inline
import pylab as pl
In [9]:
pl.plot(spec.velocity, spec.flux, 'k-')
pl.plot(spec.velocity, model)
Out[9]:
In [10]:
def cost_function(params):
return ((spec.flux*u.K-gaussian_model(spec.velocity, *params))**2).sum().value
In [11]:
from scipy.optimize import curve_fit, minimize
In [12]:
result = minimize(cost_function, (-5, 20, 20))
In [13]:
result
Out[13]:
In [14]:
best_fit_parameters = result.x
In [15]:
best_fit_model = gaussian_model(spec.velocity, *best_fit_parameters)
best_fit_model
Out[15]:
In [16]:
pl.plot(spec.velocity, spec.flux, 'k-')
pl.plot(spec.velocity, best_fit_model)
pl.xlim(-30,50)
Out[16]:
In [17]:
from scipy.optimize import curve_fit
In [18]:
# curve_fit does not play well with units
#result_curve_fit = curve_fit(gaussian_model, spec.velocity, spec.flux*u.K, p0=(-5, 20, 20))
In [19]:
import pyspeckit
sp = pyspeckit.Spectrum('gbt_1d.fits')
In [20]:
sp.plotter(xmin=-40, xmax=50)
sp.specfit(guesses=(-5, 20, 20))
In [ ]: