# Template-based Period Fitting¶

Though it can be very slow in practice, a template-based fitting method is perhaps the best way to narrow-in on the period of astronomical objects, particularly if the templates fit the data well. The reason for the slow performance is that template models require a nonlinear optimization for each candidate period.

Note that while it is possible to use the period optimizer with the template method, we skip it here because it is very computationally intensive.

## Single Band Template Model¶

`gatspy`

implements a template-based model using the Sesar 2010 RR Lyrae
templates in the `RRLyraeTemplateModeler`

class.
We’ll demonstrate its use here, starting with fetching some RR Lyrae data:

```
In [1]: from gatspy import datasets, periodic
In [2]: rrlyrae = datasets.fetch_rrlyrae()
In [3]: lcid = rrlyrae.ids[0]
In [4]: t, mag, dmag, filts = rrlyrae.get_lightcurve(lcid)
In [5]: mask = (filts == 'r')
In [6]: t_r, mag_r, dmag_r = t[mask], mag[mask], dmag[mask]
```

Next we will define the template model and fit it to the data:

```
In [7]: model = periodic.RRLyraeTemplateModeler('r')
In [8]: model.fit(t_r, mag_r, dmag_r);
```

With this model fit, we can now compute the light curve for any given period. This fit will compute the RMS residual around all available templates and use the one which provides the closest fit:

```
In [9]: period = rrlyrae.get_metadata(lcid)['P']
In [10]: t_fit = np.linspace(0, period, 1000)
In [11]: mag_fit = model.predict(t_fit, period=period)
```

Plotting the results, we see the best fit template at this phase:

(Source code, png, hires.png, pdf)

## Multiband Template Fitting¶

The multiband template model makes use of templates within each band, and fits
each individually. This is implemented in
`RRLyraeTemplateModelerMultiband`

. The API for this
modeler is similar to that discussed in the
Multiband Lomb-Scargle Periodogram.

The following figure shows the template fits to a multiband lightcurve:

(Source code, png, hires.png, pdf)