ó
šßÈ[c           @` só   d  Z  d d l m Z m Z m Z m Z d d l Z d d l Z d d l	 m
 Z
 d d l m Z d d l m Z d d	 d
 d d g Z d d d d „ Z d e f d „  ƒ  YZ d e f d „  ƒ  YZ d e f d „  ƒ  YZ d e f d „  ƒ  YZ d S(   uÑ  
Bayesian Blocks for Time Series Analysis
========================================

Dynamic programming algorithm for solving a piecewise-constant model for
various datasets. This is based on the algorithm presented in Scargle
et al 2012 [1]_. This code was ported from the astroML project [2]_.

Applications include:

- finding an optimal histogram with adaptive bin widths
- finding optimal segmentation of time series data
- detecting inflection points in the rate of event data

The primary interface to these routines is the :func:`bayesian_blocks`
function. This module provides fitness functions suitable for three types
of data:

- Irregularly-spaced event data via the :class:`Events` class
- Regularly-spaced event data via the :class:`RegularEvents` class
- Irregularly-spaced point measurements via the :class:`PointMeasures` class

For more fine-tuned control over the fitness functions used, it is possible
to define custom :class:`FitnessFunc` classes directly and use them with
the :func:`bayesian_blocks` routine.

One common application of the Bayesian Blocks algorithm is the determination
of optimal adaptive-width histogram bins. This uses the same fitness function
as for irregularly-spaced time series events. The easiest interface for
creating Bayesian Blocks histograms is the :func:`astropy.stats.histogram`
function.

References
----------
.. [1] http://adsabs.harvard.edu/abs/2012arXiv1207.5578S
.. [2] http://astroML.org/ https://github.com//astroML/astroML/
i    (   t   absolute_importt   divisiont   print_functiont   unicode_literalsNi   (   t	   signature(   t   AstropyUserWarning(   t   rangeu   FitnessFuncu   Eventsu   RegularEventsu   PointMeasuresu   bayesian_blocksu   eventsc         K` s”   i t  d 6t d 6t d 6} | j | | ƒ } t | ƒ t k r] t | t ƒ r] | |   } n$ t | t ƒ ru | } n t d ƒ ‚ | j	 |  | | ƒ S(   uø  Compute optimal segmentation of data with Scargle's Bayesian Blocks

    This is a flexible implementation of the Bayesian Blocks algorithm
    described in Scargle 2012 [1]_.

    Parameters
    ----------
    t : array_like
        data times (one dimensional, length N)
    x : array_like (optional)
        data values
    sigma : array_like or float (optional)
        data errors
    fitness : str or object
        the fitness function to use for the model.
        If a string, the following options are supported:

        - 'events' : binned or unbinned event data.  Arguments are ``gamma``,
          which gives the slope of the prior on the number of bins, or
          ``ncp_prior``, which is :math:`-\ln({\tt gamma})`.
        - 'regular_events' : non-overlapping events measured at multiples of a
          fundamental tick rate, ``dt``, which must be specified as an
          additional argument.  Extra arguments are ``p0``, which gives the
          false alarm probability to compute the prior, or ``gamma``, which
          gives the slope of the prior on the number of bins, or ``ncp_prior``,
          which is :math:`-\ln({\tt gamma})`.
        - 'measures' : fitness for a measured sequence with Gaussian errors.
          Extra arguments are ``p0``, which gives the false alarm probability
          to compute the prior, or ``gamma``, which gives the slope of the
          prior on the number of bins, or ``ncp_prior``, which is
          :math:`-\ln({\tt gamma})`.

        In all three cases, if more than one of ``p0``, ``gamma``, and
        ``ncp_prior`` is chosen, ``ncp_prior`` takes precedence over ``gamma``
        which takes precedence over ``p0``.

        Alternatively, the fitness parameter can be an instance of
        :class:`FitnessFunc` or a subclass thereof.

    **kwargs :
        any additional keyword arguments will be passed to the specified
        :class:`FitnessFunc` derived class.

    Returns
    -------
    edges : ndarray
        array containing the (N+1) edges defining the N bins

    Examples
    --------
    Event data:

    >>> t = np.random.normal(size=100)
    >>> edges = bayesian_blocks(t, fitness='events', p0=0.01)

    Event data with repeats:

    >>> t = np.random.normal(size=100)
    >>> t[80:] = t[:20]
    >>> edges = bayesian_blocks(t, fitness='events', p0=0.01)

    Regular event data:

    >>> dt = 0.05
    >>> t = dt * np.arange(1000)
    >>> x = np.zeros(len(t))
    >>> x[np.random.randint(0, len(t), len(t) // 10)] = 1
    >>> edges = bayesian_blocks(t, x, fitness='regular_events', dt=dt)

    Measured point data with errors:

    >>> t = 100 * np.random.random(100)
    >>> x = np.exp(-0.5 * (t - 50) ** 2)
    >>> sigma = 0.1
    >>> x_obs = np.random.normal(x, sigma)
    >>> edges = bayesian_blocks(t, x_obs, sigma, fitness='measures')

    References
    ----------
    .. [1] Scargle, J et al. (2012)
       http://adsabs.harvard.edu/abs/2012arXiv1207.5578S

    See Also
    --------
    astropy.stats.histogram : compute a histogram using bayesian blocks
    u   eventsu   regular_eventsu   measuresu    fitness parameter not understood(
   t   Eventst   RegularEventst   PointMeasurest   gett   typet
   issubclasst   FitnessFunct
   isinstancet
   ValueErrort   fit(   t   tt   xt   sigmat   fitnesst   kwargst   FITNESS_DICTt   fitfunc(    (    s<   lib/python2.7/site-packages/astropy/stats/bayesian_blocks.pyt   bayesian_blocks9   s    X

!	R   c           B` sh   e  Z d  Z d d	 d	 d „ Z d	 d	 d „ Z d „  Z d „  Z e d „  ƒ Z	 d „  Z
 d	 d	 d „ Z RS(
   u.  Base class for bayesian blocks fitness functions

    Derived classes should overload the following method:

    ``fitness(self, **kwargs)``:
      Compute the fitness given a set of named arguments.
      Arguments accepted by fitness must be among ``[T_k, N_k, a_k, b_k, c_k]``
      (See [1]_ for details on the meaning of these parameters).

    Additionally, other methods may be overloaded as well:

    ``__init__(self, **kwargs)``:
      Initialize the fitness function with any parameters beyond the normal
      ``p0`` and ``gamma``.

    ``validate_input(self, t, x, sigma)``:
      Enable specific checks of the input data (``t``, ``x``, ``sigma``)
      to be performed prior to the fit.

    ``compute_ncp_prior(self, N)``: If ``ncp_prior`` is not defined explicitly,
      this function is called in order to define it before fitting. This may be
      calculated from ``gamma``, ``p0``, or whatever method you choose.

    ``p0_prior(self, N)``:
      Specify the form of the prior given the false-alarm probability ``p0``
      (See [1]_ for details).

    For examples of implemented fitness functions, see :class:`Events`,
    :class:`RegularEvents`, and :class:`PointMeasures`.

    References
    ----------
    .. [1] Scargle, J et al. (2012)
       http://adsabs.harvard.edu/abs/2012arXiv1207.5578S
    gš™™™™™©?c         C` s   | |  _  | |  _ | |  _ d  S(   N(   t   p0t   gammat	   ncp_prior(   t   selfR   R   R   (    (    s<   lib/python2.7/site-packages/astropy/stats/bayesian_blocks.pyt   __init__Ä   s    		c         C` sõ  t  j | d t ƒ} | d
 k	 r3 t  j | ƒ } n  | d
 k	 rQ t  j | ƒ } n  t  j | ƒ } | j d k r~ t d ƒ ‚ n  t  j | d t d t ƒ\ } } } | d
 k r| d
 k	 rÉ t d ƒ ‚ n d } t	 | ƒ t	 | ƒ k rù t  j
 | ƒ } n t  j | ƒ } | } n† t  j | ƒ } | j d d | j f g k rMt d ƒ ‚ n  | t  j | ƒ 7} t	 | ƒ t	 | ƒ k r‡t d ƒ ‚ n  | } | | } | d
 k r¬d } n< t  j | ƒ } | j d d | j f g k rèt d	 ƒ ‚ n  | | | f S(   u®  Validate inputs to the model.

        Parameters
        ----------
        t : array_like
            times of observations
        x : array_like (optional)
            values observed at each time
        sigma : float or array_like (optional)
            errors in values x

        Returns
        -------
        t, x, sigma : array_like, float or None
            validated and perhaps modified versions of inputs
        t   dtypei   u!   t must be a one-dimensional arrayt   return_indext   return_inverseu*   If sigma is specified, x must be specifiedu   x does not match shape of tu6   Repeated values in t not supported when x is specifiedu#   sigma does not match the shape of xN(    (   i   (    (   i   (   t   npt   asarrayt   floatt   Nonet   arrayt   ndimR   t   uniquet   Truet   lent	   ones_liket   bincountt   shapet   sizet
   zeros_like(   R   R   R   R   t   unq_tt   unq_indt   unq_inv(    (    s<   lib/python2.7/site-packages/astropy/stats/bayesian_blocks.pyt   validate_inputÉ   s@    	
	c         K` s   t  ƒ  ‚ d  S(   N(   t   NotImplementedError(   R   R   (    (    s<   lib/python2.7/site-packages/astropy/stats/bayesian_blocks.pyR     s    c         C` s    d t  j d |  j | d ƒ S(   uD  
        Empirical prior, parametrized by the false alarm probability ``p0``
        See  eq. 21 in Scargle (2012)

        Note that there was an error in this equation in the original Scargle
        paper (the "log" was missing). The following corrected form is taken
        from https://arxiv.org/abs/1304.2818
        i   gR¸…ëaR@gd;ßO—Þ¿(   R!   t   logR   (   R   t   N(    (    s<   lib/python2.7/site-packages/astropy/stats/bayesian_blocks.pyt   p0_prior  s    	c         C` s   t  |  j ƒ j j ƒ  S(   N(   R   R   t
   parameterst   keys(   R   (    (    s<   lib/python2.7/site-packages/astropy/stats/bayesian_blocks.pyt   _fitness_args  s    c         C` sb   |  j  d k	 r |  j  S|  j d k	 r6 t j |  j ƒ S|  j d k	 rR |  j | ƒ St d ƒ ‚ d S(   uj   
        If ``ncp_prior`` is not explicitly defined, compute it from ``gamma``
        or ``p0``.
        u_   ``ncp_prior`` is not defined, and cannot compute it as neither ``gamma`` nor ``p0`` is defined.N(   R   R$   R   R!   R4   R   R6   R   (   R   R5   (    (    s<   lib/python2.7/site-packages/astropy/stats/bayesian_blocks.pyt   compute_ncp_prior"  s    c         C` sX  |  j  | | | ƒ \ } } } d |  j k rG t j | ƒ | d } n  d |  j k rg | | d } n  d |  j k r‹ | | | d } n  t j | d  d | d | d  | d g ƒ } | d | } t | ƒ }	 t j |	 d t ƒ}
 t j |	 d t ƒ} |  j	 d k r |  j |	 ƒ } n  xÃt |	 ƒ D]µ} i  } d	 |  j k ri| | d  | | d | d	 <n  d
 |  j k r°t j | | d  d d d … ƒ d d d … | d
 <n  d |  j k rûd t j | | d  d d d … ƒ d d d … | d <n  d |  j k rCt j | | d  d d d … ƒ d d d … | d <n  d |  j k rŽd t j | | d  d d d … ƒ d d d … | d <n  |  j |   } | | } | d c |
 |  7)t j | ƒ } | | | <| | |
 | <q-Wt j |	 d t ƒ} |	 } |	 } x< t rE| d 8} | | | <| d k r4Pn  | | d } q
W| | } | | S(   uÀ  Fit the Bayesian Blocks model given the specified fitness function.

        Parameters
        ----------
        t : array_like
            data times (one dimensional, length N)
        x : array_like (optional)
            data values
        sigma : array_like or float (optional)
            data errors

        Returns
        -------
        edges : ndarray
            array containing the (M+1) edges defining the M optimal bins
        u   a_ki   u   b_ku   c_ki   g      à?iÿÿÿÿR   u   T_ku   N_kNi    (   R2   R9   R!   R*   t   concatenateR)   t   zerosR#   t   intR   R$   R:   R   t   cumsumR   t   argmaxR(   (   R   R   R   R   t   ak_rawt   bk_rawt   ck_rawt   edgest   block_lengthR5   t   bestt   lastR   t   Rt   kwdst   fit_vect   A_Rt   i_maxt   change_pointst   i_cpt   ind(    (    s<   lib/python2.7/site-packages/astropy/stats/bayesian_blocks.pyR   1  sZ    !8<9<

	


N(   t   __name__t
   __module__t   __doc__R$   R   R2   R   R6   t   propertyR9   R:   R   (    (    (    s<   lib/python2.7/site-packages/astropy/stats/bayesian_blocks.pyR       s   #E			R   c           B` s2   e  Z d  Z d d d d „ Z d „  Z d „  Z RS(   ui  Bayesian blocks fitness for binned or unbinned events

    Parameters
    ----------
    p0 : float (optional)
        False alarm probability, used to compute the prior on
        :math:`N_{\rm blocks}` (see eq. 21 of Scargle 2012). For the Events
        type data, ``p0`` does not seem to be an accurate representation of the
        actual false alarm probability. If you are using this fitness function
        for a triggering type condition, it is recommended that you run
        statistical trials on signal-free noise to determine an appropriate
        value of ``gamma`` or ``ncp_prior`` to use for a desired false alarm
        rate.
    gamma : float (optional)
        If specified, then use this gamma to compute the general prior form,
        :math:`p \sim {\tt gamma}^{N_{\rm blocks}}`.  If gamma is specified, p0
        is ignored.
    ncp_prior : float (optional)
        If specified, use the value of ``ncp_prior`` to compute the prior as
        above, using the definition :math:`{\tt ncp\_prior} = -\ln({\tt
        gamma})`.
        If ``ncp_prior`` is specified, ``gamma`` and ``p0`` is ignored.
    gš™™™™™©?c         C` sW   | d  k	 r7 | d  k r7 | d  k r7 t j d t ƒ n  t t |  ƒ j | | | ƒ d  S(   NuÚ   p0 does not seem to accurately represent the false positive rate for event data. It is highly recommended that you run random trials on signal-free noise to calibrate ncp_prior to achieve a desired false positive rate.(   R$   t   warningst   warnR   t   superR   R   (   R   R   R   R   (    (    s<   lib/python2.7/site-packages/astropy/stats/bayesian_blocks.pyR   ¨  s    $	
c         C` s   | t  j | ƒ t  j | ƒ S(   N(   R!   R4   (   R   t   N_kt   T_k(    (    s<   lib/python2.7/site-packages/astropy/stats/bayesian_blocks.pyR   ±  s    c         C` sh   t  t |  ƒ j | | | ƒ \ } } } | d  k	 r[ t j | d d k ƒ r[ t d ƒ ‚ n  | | | f S(   Ni   i    u-   x must be integer counts for fitness='events'(   RU   R   R2   R$   R!   t   anyR   (   R   R   R   R   (    (    s<   lib/python2.7/site-packages/astropy/stats/bayesian_blocks.pyR2   µ  s    '%N(   RO   RP   RQ   R$   R   R   R2   (    (    (    s<   lib/python2.7/site-packages/astropy/stats/bayesian_blocks.pyR     s   		R   c           B` s2   e  Z d  Z d d d d „ Z d „  Z d „  Z RS(   u  Bayesian blocks fitness for regular events

    This is for data which has a fundamental "tick" length, so that all
    measured values are multiples of this tick length.  In each tick, there
    are either zero or one counts.

    Parameters
    ----------
    dt : float
        tick rate for data
    p0 : float (optional)
        False alarm probability, used to compute the prior on :math:`N_{\rm
        blocks}` (see eq. 21 of Scargle 2012). If gamma is specified, p0 is
        ignored.
    ncp_prior : float (optional)
        If specified, use the value of ``ncp_prior`` to compute the prior as
        above, using the definition :math:`{\tt ncp\_prior} = -\ln({\tt
        gamma})`.  If ``ncp_prior`` is specified, ``gamma`` and ``p0`` are
        ignored.
    gš™™™™™©?c         C` s)   | |  _  t t |  ƒ j | | | ƒ d  S(   N(   t   dtRU   R   R   (   R   RY   R   R   R   (    (    s<   lib/python2.7/site-packages/astropy/stats/bayesian_blocks.pyR   Ñ  s    	c         C` sb   t  t |  ƒ j | | | ƒ \ } } } t j | d k | d k Bƒ sU t d ƒ ‚ n  | | | f S(   Ni    i   u*   Regular events must have only 0 and 1 in x(   RU   R   R2   R!   t   allR   (   R   R   R   R   (    (    s<   lib/python2.7/site-packages/astropy/stats/bayesian_blocks.pyR2   Õ  s    'c         C` s™   | |  j  } | | } d } t j | d | k ƒ rI t j d t ƒ n  d | } d | | d k <d | | d k <| t j | ƒ | | t j | ƒ S(   Ng:Œ0âŽyE>i   u3   regular events: N/M > 1.  Is the time step correct?i    (   RY   R!   RX   RS   RT   R   R4   (   R   RW   RV   t   M_kt   N_over_Mt   epst   one_m_NM(    (    s<   lib/python2.7/site-packages/astropy/stats/bayesian_blocks.pyR   Û  s    
	

N(   RO   RP   RQ   R$   R   R2   R   (    (    (    s<   lib/python2.7/site-packages/astropy/stats/bayesian_blocks.pyR   ¼  s   	R	   c           B` s2   e  Z d  Z d d d d „ Z d „  Z d „  Z RS(   u#  Bayesian blocks fitness for point measures

    Parameters
    ----------
    p0 : float (optional)
        False alarm probability, used to compute the prior on :math:`N_{\rm
        blocks}` (see eq. 21 of Scargle 2012). If gamma is specified, p0 is
        ignored.
    ncp_prior : float (optional)
        If specified, use the value of ``ncp_prior`` to compute the prior as
        above, using the definition :math:`{\tt ncp\_prior} = -\ln({\tt
        gamma})`.  If ``ncp_prior`` is specified, ``gamma`` and ``p0`` are
        ignored.
    gš™™™™™©?c         C` s    t  t |  ƒ j | | | ƒ d  S(   N(   RU   R	   R   (   R   R   R   R   (    (    s<   lib/python2.7/site-packages/astropy/stats/bayesian_blocks.pyR   û  s    c         C` s   | | d | S(   Ni   (    (   R   t   a_kt   b_k(    (    s<   lib/python2.7/site-packages/astropy/stats/bayesian_blocks.pyR   þ  s    c         C` s7   | d  k r t d ƒ ‚ n  t t |  ƒ j | | | ƒ S(   Nu&   x must be specified for point measures(   R$   R   RU   R	   R2   (   R   R   R   R   (    (    s<   lib/python2.7/site-packages/astropy/stats/bayesian_blocks.pyR2     s    N(   RO   RP   RQ   R$   R   R   R2   (    (    (    s<   lib/python2.7/site-packages/astropy/stats/bayesian_blocks.pyR	   ì  s   	(   RQ   t
   __future__R    R   R   R   RS   t   numpyR!   t   utils.compat.funcsigsR   t   utils.exceptionsR   t   extern.six.movesR   t   __all__R$   R   t   objectR   R   R   R	   (    (    (    s<   lib/python2.7/site-packages/astropy/stats/bayesian_blocks.pyt   <module>'   s   "	fð,0