Astropy: Modeling - Solutions

Level 1

In [1]:
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
In [2]:
from astropy.modeling import models, fitting
In [3]:
x, y = np.loadtxt('data/fitting_data.txt', unpack=True)
In [4]:
plt.plot(x, y, 'o')
Out[4]:
[<matplotlib.lines.Line2D at 0x109f1ef98>]
In [5]:
m1 = models.Linear1D()
m2 = models.Polynomial1D(2)
In [6]:
fitter = fitting.LevMarLSQFitter()
In [7]:
m1_new = fitter(m1, x, y)
m2_new = fitter(m2, x, y)
WARNING: Model is linear in parameters; consider using linear fitting methods. [astropy.modeling.fitting]
WARNING:astropy:Model is linear in parameters; consider using linear fitting methods.

In [8]:
xfine = np.linspace(0, 100, 1000)
In [9]:
plt.plot(x, y, 'o')
plt.plot(xfine, m1_new(xfine), 'r-')
plt.plot(xfine, m2_new(xfine), 'b-')
Out[9]:
[<matplotlib.lines.Line2D at 0x10ad1a550>]

Level 2

In [10]:
from astropy.io import fits
hdu = fits.open('data/n57510ul.fits')[0]
flux = hdu.data
x = np.arange(len(flux))
In [11]:
plt.plot(flux)
Out[11]:
[<matplotlib.lines.Line2D at 0x10af26198>]
In [12]:
m = models.Const1D() + models.Gaussian1D(mean=420)
m_new = fitter(m, x, flux)
In [13]:
m_new
Out[13]:
<CompoundModel0(amplitude_0=2.3397361336921737e-14, amplitude_1=2.6450682744576255e-14, mean_1=417.6034577839637, stddev_1=9.449863989735471)>
In [14]:
plt.plot(x, flux)
plt.plot(x, m_new(x))
Out[14]:
[<matplotlib.lines.Line2D at 0x10af31320>]