ó
áp7]c           @` sü   d  Z  d d l m Z m Z m Z d d l Z d d l m Z d d l	 m
 Z
 m Z d d l m Z m Z m Z d d l m Z d Z d	 Z d
 Z d Z d Z e e Be Be Be BZ d Z d	 Z d
 Z d Z d e
 f d „  ƒ  YZ d e f d „  ƒ  YZ d S(   se   
State Space Representation and Kalman Filter, Smoother

Author: Chad Fulton
License: Simplified-BSD
i    (   t   divisiont   absolute_importt   print_functionN(   t   OptionWrapper(   t   KalmanFiltert   FilterResults(   t   reorder_missing_matrixt   reorder_missing_vectort   copy_index_matrix(   t   toolsi   i   i   i   i   t   KalmanSmootherc           B` sU  e  Z d  Z d d d d d d g Z e d e ƒ Z e d e ƒ Z e d e	 ƒ Z
 e d e ƒ Z e d e ƒ Z e d e ƒ Z d d	 d
 g Z e d e ƒ Z e d e ƒ Z e d e ƒ Z e d e ƒ Z e Z d Z d d d d „ Z e d „  ƒ Z d d d d „ Z  d d „ Z! d d „ Z" d d d e# d d „ Z$ d d d e% d e# d „ Z& RS(   s  
    State space representation of a time series process, with Kalman filter
    and smoother.

    Parameters
    ----------
    k_endog : array_like or integer
        The observed time-series process :math:`y` if array like or the
        number of variables in the process if an integer.
    k_states : int
        The dimension of the unobserved state process.
    k_posdef : int, optional
        The dimension of a guaranteed positive definite covariance matrix
        describing the shocks in the measurement equation. Must be less than
        or equal to `k_states`. Default is `k_states`.
    results_class : class, optional
        Default results class to use to save filtering output. Default is
        `SmootherResults`. If specified, class must extend from
        `SmootherResults`.
    **kwargs
        Keyword arguments may be used to provide default values for state space
        matrices, for Kalman filtering options, or for Kalman smoothing
        options. See `Representation` for more details.
    t   smoother_statet   smoother_state_covt   smoother_state_autocovt   smoother_disturbancet   smoother_disturbance_covt   smoother_allt   smoother_outputt   smooth_conventionalt   smooth_alternativet   smooth_classicalt   smooth_methodi    c         K` s…   | d  k r t } n  t t |  ƒ j | | | d | | | d  k	 rL | n t j j ƒ  |  _ i  |  _ |  j	 |   |  j
 |   d  S(   Nt   results_class(   t   Nonet   SmootherResultst   superR
   t   __init__R	   t   prefix_kalman_smoother_mapt   copyt   _kalman_smootherst   set_smoother_outputt   set_smooth_method(   t   selft   k_endogt   k_statest   k_posdefR   t   kalman_smoother_classest   kwargs(    (    sI   lib/python2.7/site-packages/statsmodels/tsa/statespace/kalman_smoother.pyR   g   s    		c         C` s'   |  j  } | |  j k r# |  j | Sd  S(   N(   t   prefixR   R   (   R    R&   (    (    sI   lib/python2.7/site-packages/statsmodels/tsa/statespace/kalman_smoother.pyt   _kalman_smoother~   s    	c         K` s  | d  k r |  j } n  | d  k r0 |  j } n  |  j | |  \ } } } } | p` | |  j k } | s |  j | }	 |	 j |  j | k	 } n  | rÏ |  j | }
 |
 |  j | |  j | | | ƒ |  j | <n+ |  j | j	 | t
 ƒ |  j | j | ƒ | | | | | f S(   N(   R   R   R   t   _initialize_filterR   t   kfiltert   _kalman_filtersR   t   _statespacesR   t   FalseR   (   R    R   R   R&   R%   t   dtypet   create_filtert   create_statespacet   create_smoothert   kalman_smoothert   cls(    (    sI   lib/python2.7/site-packages/statsmodels/tsa/statespace/kalman_smoother.pyt   _initialize_smoother…   s(    
c         K` sS   | d k	 r | |  _ n  x4 t j D]) } | | k r" t |  | | | ƒ q" q" Wd S(   sZ
  
        Set the smoother output

        The smoother can produce several types of results. The smoother output
        variable controls which are calculated and returned.

        Parameters
        ----------
        smoother_output : integer, optional
            Bitmask value to set the smoother output to. See notes for details.
        **kwargs
            Keyword arguments may be used to influence the smoother output by
            setting individual boolean flags. See notes for details.

        Notes
        -----
        The smoother output is defined by a collection of boolean flags, and
        is internally stored as a bitmask. The methods available are:

        SMOOTHER_STATE = 0x01
            Calculate and return the smoothed states.
        SMOOTHER_STATE_COV = 0x02
            Calculate and return the smoothed state covariance matrices.
        SMOOTHER_STATE_AUTOCOV = 0x10
            Calculate and return the smoothed state lag-one autocovariance
            matrices.
        SMOOTHER_DISTURBANCE = 0x04
            Calculate and return the smoothed state and observation
            disturbances.
        SMOOTHER_DISTURBANCE_COV = 0x08
            Calculate and return the covariance matrices for the smoothed state
            and observation disturbances.
        SMOOTHER_ALL
            Calculate and return all results.

        If the bitmask is set directly via the `smoother_output` argument, then
        the full method must be provided.

        If keyword arguments are used to set individual boolean flags, then
        the lowercase of the method must be used as an argument name, and the
        value is the desired value of the boolean flag (True or False).

        Note that the smoother output may also be specified by directly
        modifying the class attributes which are defined similarly to the
        keyword arguments.

        The default smoother output is SMOOTHER_ALL.

        If performance is a concern, only those results which are needed should
        be specified as any results that are not specified will not be
        calculated. For example, if the smoother output is set to only include
        SMOOTHER_STATE, the smoother operates much more quickly than if all
        output is required.

        Examples
        --------
        >>> import statsmodels.tsa.statespace.kalman_smoother as ks
        >>> mod = ks.KalmanSmoother(1,1)
        >>> mod.smoother_output
        15
        >>> mod.set_smoother_output(smoother_output=0)
        >>> mod.smoother_state = True
        >>> mod.smoother_output
        1
        >>> mod.smoother_state
        True
        N(   R   R   R
   t   smoother_outputst   setattr(   R    R   R%   t   name(    (    sI   lib/python2.7/site-packages/statsmodels/tsa/statespace/kalman_smoother.pyR   ¬   s
    Dc         K` sS   | d k	 r | |  _ n  x4 t j D]) } | | k r" t |  | | | ƒ q" q" Wd S(   sÞ  
        Set the smoothing method

        The smoothing method can be used to override the Kalman smoother
        approach used. By default, the Kalman smoother used depends on the
        Kalman filter method.

        Parameters
        ----------
        smooth_method : integer, optional
            Bitmask value to set the filter method to. See notes for details.
        **kwargs
            Keyword arguments may be used to influence the filter method by
            setting individual boolean flags. See notes for details.

        Notes
        -----
        The smoothing method is defined by a collection of boolean flags, and
        is internally stored as a bitmask. The methods available are:

        SMOOTH_CONVENTIONAL = 0x01
            Default Kalman smoother, as presented in Durbin and Koopman, 2012
            chapter 4.
        SMOOTH_CLASSICAL = 0x02
            Classical Kalman smoother, as presented in Anderson and Moore, 1979
            or Durbin and Koopman, 2012 chapter 4.6.1.
        SMOOTH_ALTERNATIVE = 0x04
            Modified Bryson-Frazier Kalman smoother method; this is identical
            to the conventional method of Durbin and Koopman, 2012, except that
            an additional intermediate step is included.
        SMOOTH_UNIVARIATE = 0x08
            Univariate Kalman smoother, as presented in Durbin and Koopman,
            2012 chapter 6, except with modified Bryson-Frazier timing.

        Practically speaking, these methods should all produce the same output
        but different computational implications, numerical stability
        implications, or internal timing assumptions.

        Note that only the first method is available if using a Scipy version
        older than 0.16.

        If the bitmask is set directly via the `smooth_method` argument, then
        the full method must be provided.

        If keyword arguments are used to set individual boolean flags, then
        the lowercase of the method must be used as an argument name, and the
        value is the desired value of the boolean flag (True or False).

        Note that the filter method may also be specified by directly modifying
        the class attributes which are defined similarly to the keyword
        arguments.

        The default filtering method is SMOOTH_CONVENTIONAL.

        Examples
        --------
        >>> mod = sm.tsa.statespace.SARIMAX(range(10))
        >>> mod.smooth_method
        1
        >>> mod.filter_conventional
        True
        >>> mod.filter_univariate = True
        >>> mod.smooth_method
        17
        >>> mod.set_smooth_method(filter_univariate=False,
                                  filter_collapsed=True)
        >>> mod.smooth_method
        33
        >>> mod.set_smooth_method(smooth_method=1)
        >>> mod.filter_conventional
        True
        >>> mod.filter_univariate
        False
        >>> mod.filter_collapsed
        False
        >>> mod.filter_univariate = True
        >>> mod.smooth_method
        17
        N(   R   R   R
   t   smooth_methodsR5   (   R    R   R%   R6   (    (    sI   lib/python2.7/site-packages/statsmodels/tsa/statespace/kalman_smoother.pyR   ö   s
    Pc         K` s]   |  j  | | d | | \ } } } }	 }
 |	 s6 |
 rE t d ƒ ‚ n  |  j | } | ƒ  | S(   NR&   sg   Passed settings forced re-creation of the Kalman filter. Please run `_filter` before running `_smooth`.(   R3   t
   ValueErrorR   (   R    R   R   R&   t   complex_stept   resultsR%   R-   R0   R.   R/   t   smoother(    (    sI   lib/python2.7/site-packages/statsmodels/tsa/statespace/kalman_smoother.pyt   _smoothL  s    $c   
      K` sy   |  j  |   } |  j |  ƒ } | j |  ƒ | j | ƒ | d k rP |  j } n  |  j | d | | }	 | j |	 ƒ | S(   s½  
        Apply the Kalman smoother to the statespace model.

        Parameters
        ----------
        smoother_output : int, optional
            Determines which Kalman smoother output calculate. Default is all
            (including state, disturbances, and all covariances).
        results : class or object, optional
            If a class, then that class is instantiated and returned with the
            result of both filtering and smoothing.
            If an object, then that object is updated with the smoothing data.
            If None, then a SmootherResults object is returned with both
            filtering and smoothing results.
        run_filter : bool, optional
            Whether or not to run the Kalman filter prior to smoothing. Default
            is True.
        prefix : string
            The prefix of the datatype. Usually only used internally.

        Returns
        -------
        SmootherResults object
        R:   N(   t   _filterR   t   update_representationt   update_filterR   R   R<   t   update_smoother(
   R    R   R   R:   t
   run_filterR&   R9   R%   R)   R;   (    (    sI   lib/python2.7/site-packages/statsmodels/tsa/statespace/kalman_smoother.pyt   smoothb  s    N('   t   __name__t
   __module__t   __doc__R4   R   t   SMOOTHER_STATER   t   SMOOTHER_STATE_COVR   t   SMOOTHER_DISTURBANCER   t   SMOOTHER_DISTURBANCE_COVR   t   SMOOTHER_STATE_AUTOCOVR   t   SMOOTHER_ALLR   R7   t   SMOOTH_CONVENTIONALR   t   SMOOTH_ALTERNATIVER   t   SMOOTH_CLASSICALR   t   SMOOTH_UNIVARIATEt   smooth_univariateR   R   R   R   t   propertyR'   R3   R   R   R,   R<   t   TrueRB   (    (    (    sI   lib/python2.7/site-packages/statsmodels/tsa/statespace/kalman_smoother.pyR
   "   s6   	&JV		R   c           B` s–   e  Z d  Z d d d d d d d d d	 d
 d g Z e j Z e j e Z	 e
 d „ Z d „  Z d „  Z e d „  ƒ Z e d „  ƒ Z e d „  ƒ Z RS(   s	  
    Results from applying the Kalman smoother and/or filter to a state space
    model.

    Parameters
    ----------
    model : Representation
        A Statespace representation

    Attributes
    ----------
    nobs : int
        Number of observations.
    k_endog : int
        The dimension of the observation series.
    k_states : int
        The dimension of the unobserved state process.
    k_posdef : int
        The dimension of a guaranteed positive definite covariance matrix
        describing the shocks in the measurement equation.
    dtype : dtype
        Datatype of representation matrices
    prefix : str
        BLAS prefix of representation matrices
    shapes : dictionary of name:tuple
        A dictionary recording the shapes of each of the representation
        matrices as tuples.
    endog : array
        The observation vector.
    design : array
        The design matrix, :math:`Z`.
    obs_intercept : array
        The intercept for the observation equation, :math:`d`.
    obs_cov : array
        The covariance matrix for the observation equation :math:`H`.
    transition : array
        The transition matrix, :math:`T`.
    state_intercept : array
        The intercept for the transition equation, :math:`c`.
    selection : array
        The selection matrix, :math:`R`.
    state_cov : array
        The covariance matrix for the state equation :math:`Q`.
    missing : array of bool
        An array of the same size as `endog`, filled with boolean values that
        are True if the corresponding entry in `endog` is NaN and False
        otherwise.
    nmissing : array of int
        An array of size `nobs`, where the ith entry is the number (between 0
        and k_endog) of NaNs in the ith row of the `endog` array.
    time_invariant : bool
        Whether or not the representation matrices are time-invariant
    initialization : str
        Kalman filter initialization method.
    initial_state : array_like
        The state vector used to initialize the Kalamn filter.
    initial_state_cov : array_like
        The state covariance matrix used to initialize the Kalamn filter.
    filter_method : int
        Bitmask representing the Kalman filtering method
    inversion_method : int
        Bitmask representing the method used to invert the forecast error
        covariance matrix.
    stability_method : int
        Bitmask representing the methods used to promote numerical stability in
        the Kalman filter recursions.
    conserve_memory : int
        Bitmask representing the selected memory conservation method.
    tolerance : float
        The tolerance at which the Kalman filter determines convergence to
        steady-state.
    loglikelihood_burn : int
        The number of initial periods during which the loglikelihood is not
        recorded.
    converged : bool
        Whether or not the Kalman filter converged.
    period_converged : int
        The time period in which the Kalman filter converged.
    filtered_state : array
        The filtered state vector at each time period.
    filtered_state_cov : array
        The filtered state covariance matrix at each time period.
    predicted_state : array
        The predicted state vector at each time period.
    predicted_state_cov : array
        The predicted state covariance matrix at each time period.
    kalman_gain : array
        The Kalman gain at each time period.
    forecasts : array
        The one-step-ahead forecasts of observations at each time period.
    forecasts_error : array
        The forecast errors at each time period.
    forecasts_error_cov : array
        The forecast error covariance matrices at each time period.
    loglikelihood : array
        The loglikelihood values at each time period.
    collapsed_forecasts : array
        If filtering using collapsed observations, stores the one-step-ahead
        forecasts of collapsed observations at each time period.
    collapsed_forecasts_error : array
        If filtering using collapsed observations, stores the one-step-ahead
        forecast errors of collapsed observations at each time period.
    collapsed_forecasts_error_cov : array
        If filtering using collapsed observations, stores the one-step-ahead
        forecast error covariance matrices of collapsed observations at each
        time period.
    standardized_forecast_error : array
        The standardized forecast errors
    smoother_output : int
        Bitmask representing the generated Kalman smoothing output
    scaled_smoothed_estimator : array
        The scaled smoothed estimator at each time period.
    scaled_smoothed_estimator_cov : array
        The scaled smoothed estimator covariance matrices at each time period.
    smoothing_error : array
        The smoothing error covariance matrices at each time period.
    smoothed_state : array
        The smoothed state at each time period.
    smoothed_state_cov : array
        The smoothed state covariance matrices at each time period.
    smoothed_state_autocov : array
        The smoothed state lago-one autocovariance matrices at each time
        period: :math:`Cov(\alpha_{t+1}, \alpha_t)`.
    smoothed_measurement_disturbance : array
        The smoothed measurement at each time period.
    smoothed_state_disturbance : array
        The smoothed state at each time period.
    smoothed_measurement_disturbance_cov : array
        The smoothed measurement disturbance covariance matrices at each time
        period.
    smoothed_state_disturbance_cov : array
        The smoothed state disturbance covariance matrices at each time period.
    R   t   scaled_smoothed_estimatort   scaled_smoothed_estimator_covt   smoothing_errort   smoothed_statet   smoothed_state_covt   smoothed_state_autocovt    smoothed_measurement_disturbancet   smoothed_state_disturbancet$   smoothed_measurement_disturbance_covt   smoothed_state_disturbance_covc         C` sh   t  t |  ƒ j | | ƒ x- |  j D]" } t |  | t | | d ƒ ƒ q# Wd |  _ d |  _ d |  _	 d S(   sø  
        Update the results to match a given model

        Parameters
        ----------
        model : Representation
            The model object from which to take the updated values.
        only_options : boolean, optional
            If set to true, only the smoother and filter options are updated,
            and the state space representation is not updated. Default is
            False.

        Notes
        -----
        This method is rarely required except for internal usage.
        N(
   R   R   R>   t   _smoother_optionsR5   t   getattrR   t   _smoothed_forecastst   _smoothed_forecasts_errort   _smoothed_forecasts_error_cov(   R    t   modelt   only_optionsR6   (    (    sI   lib/python2.7/site-packages/statsmodels/tsa/statespace/kalman_smoother.pyR>   %  s     		c   	      C` s7  g  } |  j  s |  j r( | j d ƒ n  |  j s: |  j rJ | j d ƒ n  |  j  rc | j d ƒ n  |  j r| | j d ƒ n  |  j r• | j d ƒ n  |  j r´ | d d d g 7} n  |  j rÐ | d	 d
 g 7} n  t j |  j ƒ d k } xœ|  j	 D]‘} | d k rqò | | k rs| d k r’t
 | | d ƒ } | d k	 rj| rjt j t | |  j d |  j ƒƒ } n t j | d t ƒ} t |  | | ƒ qƒ| d	 k rEt
 | | d ƒ } | d k	 r| rt | |  j d t d t d |  j ƒ} t |  j | |  j d t d t d t d |  j ƒn t j | d t ƒ} t |  | | ƒ qƒt |  | t j t
 | | d ƒ d t ƒƒ qò t |  | d ƒ qò Wd |  _ d |  _ d |  _ |  j d k rt j | j d t ƒ|  _ t j | j d t ƒ|  _ t j | j d t ƒ|  _ n  d } d } d | k rB|  j d d … | | … f |  _ n  d | k r||  j d d … d d … | | … f |  _ n  d |  _ d |  _ d |  _ |  j r3|  j j  d k r3|  j! |  j" 9_! |  j# |  j" 9_# |  j$ |  j" 9_$ |  j% |  j" 9_% |  j |  j" _ |  j |  j" _ |  j& |  j" _& n  d S(   s  
        Update the smoother results

        Parameters
        ----------
        smoother : KalmanSmoother
            The model object from which to take the updated values.

        Notes
        -----
        This method is rarely required except for internal usage.
        RS   RT   RV   RW   RX   RU   RY   RZ   R[   R\   i    R   R&   R   t   reorder_rowst   reorder_colst
   index_rowst
   index_colst   inplacei   N(   RU   RY   ('   R   R   t   appendR   R   R   t   npt   sumt   nmissingt   _smoother_attributesR^   R   t   arrayR   t   missingR&   RR   R5   R   R   t   obs_covt!   scaled_smoothed_diffuse_estimatort&   scaled_smoothed_diffuse1_estimator_covt&   scaled_smoothed_diffuse2_estimator_covt   nobs_diffuseRS   RT   R_   R`   Ra   t   filter_concentratedRb   t   _scaleRW   t   scaleRX   R\   R[   RU   (	   R    R;   t
   attributest   has_missingR6   t   vectort   matrixt   startt   end(    (    sI   lib/python2.7/site-packages/statsmodels/tsa/statespace/kalman_smoother.pyR@   A  s–    								%				%.			c         C` s­  |  j  d  k r—t j |  j j d |  j ƒ|  _  t j |  j j d |  j ƒ|  _ t j |  j	 j d |  j ƒ|  _
 x"t |  j ƒ D]} |  j j d d k r¤ d n | } |  j j d d k rÆ d n | } |  j j d d k rè d n | } |  j d  d  … | f j t ƒ } t j |  j d  d  … d  d  … | f |  j d  d  … | f ƒ |  j d  d  … | f |  j  d  d  … | f <|  j | d k r®t j |  j d  d  … | f <n  |  j | | f |  j  | | f |  j | | f <t j t j |  j d  d  … d  d  … | f |  j d  d  … d  d  … | f ƒ |  j d  d  … d  d  … | f j ƒ |  j d  d  … d  d  … | f |  j
 d  d  … d  d  … | f <q‚ Wn  |  j  |  j |  j
 f S(   NR-   i   i   i    (   R_   R   Rj   t   zerost	   forecastst   shapeR-   t   forecasts_errorR`   t   forecasts_error_covRa   t   ranget   nobst   designRp   t   obs_interceptRo   t   astypet   boolt   dotRV   Rl   t   nant   endogRW   t   T(   R    t   tt   design_tt	   obs_cov_tt   obs_intercept_tt   mask(    (    sI   lib/python2.7/site-packages/statsmodels/tsa/statespace/kalman_smoother.pyt   _get_smoothed_forecasts¼  s0    !!"""#8-1%"%Fc         C` s   |  j  ƒ  d S(   Ni    (   R’   (   R    (    (    sI   lib/python2.7/site-packages/statsmodels/tsa/statespace/kalman_smoother.pyt   smoothed_forecastsã  s    c         C` s   |  j  ƒ  d S(   Ni   (   R’   (   R    (    (    sI   lib/python2.7/site-packages/statsmodels/tsa/statespace/kalman_smoother.pyt   smoothed_forecasts_errorç  s    c         C` s   |  j  ƒ  d S(   Ni   (   R’   (   R    (    (    sI   lib/python2.7/site-packages/statsmodels/tsa/statespace/kalman_smoother.pyt   smoothed_forecasts_error_covë  s    (   RC   RD   RE   Rm   R
   R4   R]   R   t   _model_attributest   _attributesR,   R>   R@   R’   RQ   R“   R”   R•   (    (    (    sI   lib/python2.7/site-packages/statsmodels/tsa/statespace/kalman_smoother.pyR   ‘  s   …				{	'(   RE   t
   __future__R    R   R   t   numpyRj   t)   statsmodels.tsa.statespace.representationR   t(   statsmodels.tsa.statespace.kalman_filterR   R   t    statsmodels.tsa.statespace.toolsR   R   R   t   statsmodels.tsa.statespaceR	   RF   RG   RH   RI   RJ   RK   RL   RN   RM   RO   R
   R   (    (    (    sI   lib/python2.7/site-packages/statsmodels/tsa/statespace/kalman_smoother.pyt   <module>   s&   ÿ p