.. doctest-skip-all

.. _whatsnew-1.2:

**************************
What's New in Astropy 1.2?
**************************

Overview
========

Astropy 1.2 is a major release that adds significant new functionality since
the 1.1.x series of releases.

In particular, this release includes:

* A new class to compute :ref:`Lomb-Scargle periodograms
  <whatsnew-1.2-lombscargle>` efficiently using different methods.
* A number of :ref:`new statistics functions <whatsnew-1.2-stats>`, including
  for Jackknife resampling, circular statistics, and for the Akaike and
  Bayesian information criteria.
* Support for getting the :ref:`positions of solar system bodies
  <whatsnew-1.2-solarsystem>` in the :ref:`coordinates <astropy-coordinates>` sub-package.
* The ability to compute Barycentric and Heliocentric :ref:`light-travel time
  corrections <whatsnew-1.2-barycentric>`.
* Support for :ref:`offset coordinate frames <whatsnew-1.2-skyoffset>`, which
  can be used to define a coordinate system relative to a known position.
* An implementation of the :ref:`zscale algorithm <whatsnew-1.2-zscale>` to
  determine image limits automatically.
* Support for :ref:`bolometric magnitudes <whatsnew-1.2-magnitudes>` in the
  units package.
* Improvements to the :ref:`NDData class and subclasses <whatsnew-1.2-nddata>`.
* :ref:`Auto-downloading of IERS tables <whatsnew-1.2-iers>` as needed, which
  gives information about Earth orientation parameters necessary for high
  precision coordinate calculations and conversions to/from the UT1 scale.

In addition to these major changes, Astropy 1.2 includes a large number of
smaller improvements and bug fixes, which are described in the
:ref:`changelog`. By the numbers:

* 615 issues have been closed since v1.1
* 313 pull requests have been merged since v1.1
* 191 distinct people have contributed code

.. _whatsnew-1.2-lombscargle:

Lomb-scargle periodograms
=========================
The new :class:`~astropy.stats.LombScargle` class implements a fast Lomb-Scargle
periodogram, useful for detecting periodic signals in noisy, unevenly-spaced
data. For example, here is an irregular sinusoidal signal:

>>> import numpy as np
>>> rand = np.random.RandomState(42)
>>> t = 100 * rand.rand(100)
>>> dy = 0.1
>>> y = np.sin(2 * np.pi * t) + dy * rand.randn(100)

Given this data, we can compute the Lomb-Scargle periodogram and find the
frequency at which the power is maximized:

>>> from astropy.stats import LombScargle
>>> frequency, power = LombScargle(t, y, dy).autopower()
>>> frequency[np.argmax(power)]
0.99962825294969382

The maximum is very near the input frequency of 1.0 cycles per unit time.

As a more realistic example, here is a periodogram computed for six
months of nightly observations of a simulated RR-Lyrae-type variable
(this particular example is discussed more fully in
:ref:`lomb-scargle-example`):

.. plot::

    import numpy as np
    import matplotlib.pyplot as plt
    plt.style.use('ggplot')

    from astropy.stats import LombScargle


    def simulated_data(N, rseed=2, period=0.41, phase=0.0):
        """Simulate data based from a pre-computed empirical fit"""

        # coefficients from a 5-term Fourier fit to SDSS object 1019544
        coeffs = [-0.0191, 0.1375, -0.1968, 0.0959, 0.075,
                  -0.0686, 0.0307, -0.0045, -0.0421, 0.0216, 0.0041]

        rand = np.random.RandomState(rseed)
        t = phase + np.arange(N, dtype=float)
        t += 0.1 * rand.randn(N)
        dmag = 0.01 + 0.03 * rand.rand(N)

        omega = 2 * np.pi / period
        n = np.arange(1 + len(coeffs) // 2)[:, None]

        mag = (15 + dmag * rand.randn(N)
               + np.dot(coeffs[::2], np.cos(n * omega * t)) +
               + np.dot(coeffs[1::2], np.sin(n[1:] * omega * t)))

        return t, mag, dmag


    # generate data and compute the periodogram
    t, mag, dmag = simulated_data(50)
    freq, PLS = LombScargle(t, mag, dmag).autopower(minimum_frequency=1 / 1.2,
                                                    maximum_frequency=1 / 0.2)
    best_freq = freq[np.argmax(PLS)]
    phase = (t * best_freq) % 1

    # compute the best-fit model
    phase_fit = np.linspace(0, 1)
    mag_fit = LombScargle(t, mag, dmag).model(t=phase_fit / best_freq,
                                              frequency=best_freq)

    # set up the figure & axes for plotting
    fig, ax = plt.subplots(1, 2, figsize=(12, 5))
    fig.suptitle('Lomb-Scargle Periodogram (period=0.41 days)')
    fig.subplots_adjust(bottom=0.12, left=0.07, right=0.95)
    inset = fig.add_axes([0.78, 0.56, 0.15, 0.3])

    # plot the raw data
    ax[0].errorbar(t, mag, dmag, fmt='ok', elinewidth=1.5, capsize=0)
    ax[0].invert_yaxis()
    ax[0].set(xlim=(0, 50),
              xlabel='Observation time (days)',
              ylabel='Observed Magnitude')

    # plot the periodogram
    ax[1].plot(1. / freq, PLS)
    ax[1].set(xlabel='period (days)',
              ylabel='Lomb-Scargle Power',
              xlim=(0.2, 1.2),
              ylim=(0, 1));

    # plot the phased data & model in the inset
    inset.errorbar(phase, mag, dmag, fmt='.k', capsize=0)
    inset.plot(phase_fit, mag_fit)
    inset.invert_yaxis()
    inset.set_xlabel('phase')
    inset.set_ylabel('mag')

For more information on astropy's Lomb-Scargle functionality,
see :ref:`stats-lombscargle`.

.. _whatsnew-1.2-stats:

Other new statistics features
=============================

The **Jackknife resampling method** is available via the
:func:`~astropy.stats.jackknife_resampling` function. Jackknife resampling
generates n deterministic samples of size n-1 from a measured sample of size n.
Those samples can then be used for various statistics estimation such as
variance and bias using the :func:`~astropy.stats.jackknife_stats` function.
  
**Circular statistics** (circular mean, variance, etc) are now provided by the
:func:`~astropy.stats.circmean`, :func:`~astropy.stats.circvar`, ,
:func:`~astropy.stats.circmoment`, and :func:`~astropy.stats.circcorrcoef`
functions. in. The API basically follows the same conventions of R CircStats
package. In addition, the circular stats are compatible with the
:class:`~astropy.units.Quantity` class.

The **Akaike and Bayesian information criteria** are now implemented in
:func:`~astropy.stats.akaike_info_criterion`,
:func:`~astropy.stats.akaike_info_criterion_lsq`,
:func:`~astropy.stats.bayesian_info_criterion`, and
:func:`~astropy.stats.bayesian_info_criterion_lsq`. Basically, these
information criteria are used to decided whether increasing the number of
parameters in a model truly improves the fitting. Conversely, they are also
used to verify whether improvements in fitting are due to the increasing of the
number of parameters.

.. _whatsnew-1.2-solarsystem:

Solar system ephemerides
========================

It is now possible to calculate the positions of the major solar system bodies
(as well as the moon) in the :ref:`coordinates <astropy-coordinates>`
sub-package. These integrate fully all the coordinate frames, allowing easy
conversion to apparent (e.g. ``AltAz``) positions or barycentric values. The
positions can be calculated using either using built-in approximations or more
precise values that depend on downloading JPL-provided ephemeris models derived
from n-body simulations (the latter requires the additional dependency of the
`jplephem <https://pypi.python.org/pypi/jplephem>`_ package). For more details,
see :ref:`astropy-coordinates-solarsystem`.

.. _whatsnew-1.2-barycentric:

Barycentric light-travel time corrections
=========================================

The :class:`~astropy.time.Time` class has gained a new method
:meth:`~astropy.time.Time.light_travel_time` for calculating barycentric
(or heliocentric) corrections. For more details, see
:ref:`time-light-travel-time`.

.. _whatsnew-1.2-skyoffset:

Sky offset coordinate frames
============================

The :ref:`coordinates <astropy-coordinates>` sub-package now includes support
for coordinate frames that are rotated in the sky to be centered on a
particular object. This sort of frame is variously known as "FOV coordinates",
"offset coordinates", or "astrometric". It makes it easier to compute offsets
from a particular reference object, and define coordinate frames that for
heirarchical systems like groups or clusters of galaxies. It also enables the
new :meth:`~astropy.coordinates.SkyCoord.spherical_offsets_to` method. For more
details, see :ref:`astropy-skyoffset-frames`.

.. _whatsnew-1.2-zscale:

Zscale implementation
=====================

The `zscale <http://iraf.net/forum/viewtopic.php?showtopic=134139>`_ algorithm
from IRAF is now included in Astropy's :ref:`visualization
<astropy-visualization>` sub-package, and available as
a `~astropy.visualization.ZScaleInterval` interval class. The implementation is
based on `Numdisplay’s <http://stsdas.stsci.edu/numdisplay/>`_ one, slightly
modified to expose more arguments and work with data with any number of
dimensions.

.. _whatsnew-1.2-examples:

New example gallery
===================

The Astropy documentation now contains an
`example gallery <../generated/examples/index.html>`_ that highlights key
functionality of the package in short snippets of code with descriptive text.
The examples are meant to demonstrate the functionality and interoperability of
the subpackages in shorter-form worked examples. Longer form tutorials are still
maintained at `<http://tutorials.astropy.org/>`_.

.. _whatsnew-1.2-magnitudes:

Apparent/absolute bolometric magnitudes and other new units
===========================================================

The :ref:`units <astropy-units>` sub-package now supports bolometric magnitudes, based on the
bolometric flux and luminosity scales adopted in IAU 2015 resolution B2.

Furthermore, Earth and Jupiter radii have been made available as units.

.. _whatsnew-1.2-nddata:

NDData improvements
===================

Arithmetic and uncertainty handling have been enhanced for astropy 1.2, and a
new class, :class:`~astropy.nddata.NDDataRef`, has been added that should be
the starting point for new users of `astropy.nddata`. One can now do arithmetic
between an :class:`~astropy.nddata.NDDataRef` object and a scalar, an
:class:`~astropy.units.Quantity` or another :class:`~astropy.nddata.NDDataRef`
object (or any class that implements the nddata interface). Limited support for
propagating correlated errors was added to
:class:`~astropy.nddata.StdDevUncertainty`.

Several internal changes were made to the classes in the nddata package to
make writing custom classes that implement the nddata interface more
straightforward.

.. _whatsnew-1.2-iers:

Automatic updates to IERS Earth rotation data
=============================================

The `astropy.utils.iers` sub-package provides access to the tables provided by
the International Earth Rotation and Reference Systems (IERS) service.  These
are used in the :ref:`time <astropy-time>` sub-package to transform to/from UT1
values and for determining Earth orientation for celestial-to-terrestrial
coordinate transformations (in the :ref:`coordinates <astropy-coordinates>`
sub-package).

Starting with astropy 1.2, the latest IERS values (which include approximately
one year of predictive values) are automatically downloaded from the IERS
service when required.  This happens when a time or coordinate transformation
needs a value which is not already available via the download cache.

For details see the `astropy.utils.iers` sub-package documentation.

Other significant changes
=========================

Astropy now requires Numpy 1.7.0 or later.

Full change log
===============

To see a detailed list of all changes in version v1.2, including changes in
API, please see the :ref:`changelog`.
