
p7]c           @` s  d  Z  d d l m Z m Z m Z d d l Z d d l Z d d l Z	 d d l
 m Z d d l m Z d d l m Z m Z d d l m Z d d l m Z m Z m Z m Z d d	 l m Z d d
 l m Z m Z m Z d d l j j  Z! d d l" j# j$ Z% d d l& m' Z' d d l( j) j j* Z+ d d l, m- Z- d d l. m/ Z/ d d l0 m1 Z1 m2 Z2 e3 e4 k rne4 Z5 n  d   Z6 d e+ j7 f d     YZ8 d e+ j9 f d     YZ: d e! j; f d     YZ< e! j= e< e:  d e% j> f d     YZ> d e! j; f d     YZ? e! j= e? e>  d S(   s@   
State Space Model

Author: Chad Fulton
License: Simplified-BSD
i    (   t   divisiont   absolute_importt   print_functionN(   t   norm(   t   long(   t   pinv_extendedt   Bunch(   t   PrecisionWarning(   t   _get_epsilont   approx_hess_cst   approx_fprime_cst   approx_fprime(   t   cache_readonly(   t   aict   bict   hqic(   t   identityi   (   t   SimulationSmoother(   t   SmootherResults(   t   INVERT_UNIVARIATEt   SOLVE_LUc   	      O` s  g  } t  |  d k r t | d t  r8 | d } n t t |  |   } x; t t  |    D]' } | j | j |  | | |   q` Wxz | j   D]+ \ } } | | k r t d |   q q Wn> x; t t  |    D]' } | j | j	 |  | | |   q Wt
 |  | f S(   Ni    s7   loglike() got multiple values for keyword argument '%s'(   t   lent
   isinstancet   dictt   zipt   ranget   appendt   gett   itemst	   TypeErrort   popt   tuple(	   t   namest   defaultst   argst   kwargst   output_argst   flagst   it   namet   value(    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   _handle_args(   s    %%t   MLEModelc           B` sq  e  Z d  Z dB dB dB d  Z d   Z d   Z d   Z d   Z dB d  Z	 dB d  Z
 dB d  Z dB d	  Z dB d
  Z d   Z dB d  Z d   Z e d    Z e j d    Z e d    Z e j d    Z e d    Z e j d    Z e d    Z e j d    Z dB e d dB d d d d dB e dB dB dB dB d  Z e d    Z dB dB dB dB d  Z e e dB dB e dB dB d  Z e e dB dB e dB dB d  Z d  d! g Z e e g Z d"   Z  e e d#  Z! dB d$  Z" e dB e dB d%  Z# e dB e d&  Z$ e dB d'  Z% d(   Z& e d)  Z' e d*  Z( e e d+  Z) d  d, d- d. g Z* e d/ dB e g Z+ d0   Z, d/ e dB e d1  Z- d  d2 d- d. g Z. e d/ dB e g Z/ d3   Z0 d4   Z1 d5   Z2 e d6  Z3 d7   Z4 e d8    Z5 e d9    Z6 e d:  Z7 d;   Z8 d<   Z9 e e d=  Z: dB dB dB d>  Z; d d? e e d@  Z< e= dB dA   Z> RS(C   s[  
    State space model for maximum likelihood estimation

    Parameters
    ----------
    endog : array_like
        The observed time-series process :math:`y`
    k_states : int
        The dimension of the unobserved state process.
    exog : array_like, optional
        Array of exogenous regressors, shaped nobs x k. Default is no
        exogenous regressors.
    dates : array-like of datetime, optional
        An array-like object of datetime objects. If a Pandas object is given
        for endog, it is assumed to have a DateIndex.
    freq : str, optional
        The frequency of the time-series. A Pandas offset or 'B', 'D', 'W',
        'M', 'A', or 'Q'. This is optional if dates are given.
    **kwargs
        Keyword arguments may be used to provide default values for state space
        matrices or for Kalman filtering options. See `Representation`, and
        `KalmanFilter` for more details.

    Attributes
    ----------
    ssm : statsmodels.tsa.statespace.kalman_filter.KalmanFilter
        Underlying state space representation.

    Notes
    -----
    This class wraps the state space model with Kalman filtering to add in
    functionality for maximum likelihood estimation. In particular, it adds
    the concept of updating the state space representation based on a defined
    set of parameters, through the `update` method or `updater` attribute (see
    below for more details on which to use when), and it adds a `fit` method
    which uses a numerical optimizer to select the parameters that maximize
    the likelihood of the model.

    The `start_params` `update` method must be overridden in the
    child class (and the `transform` and `untransform` methods, if needed).

    See Also
    --------
    MLEResults
    statsmodels.tsa.statespace.kalman_filter.KalmanFilter
    statsmodels.tsa.statespace.representation.Representation
    c         K` s   t  t |   j d | d | d | d | d d  | |  _ |  j   \ |  _ |  _ |  j j d |  _ | |  _	 |  j
 |   d  S(   Nt   endogt   exogt   datest   freqt   missingt   nonei    (   t   superR*   t   __init__t   _init_kwargst   prepare_dataR+   R,   t   shapet   nobst   k_statest   initialize_statespace(   t   selfR+   R7   R,   R-   R.   R#   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR2   r   s    		c         C` sw   t  j |  j j d d } |  j j } | d k	 rE t  j |  } n  | j d k rm | j d d f | _ n  | | f S(   sH   
        Prepare data for use in the state space representation
        t   ordert   Ci   i    N(   t   npt   arrayt   datat
   orig_endogt	   orig_exogt   Nonet   ndimR5   (   R9   R+   R,   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR4      s    c         K` sN   |  j  j } t | j d |  j |  |  _ |  j j |  |  j j |  _ d S(   s   
        Initialize the state space representation

        Parameters
        ----------
        **kwargs
            Additional keyword arguments to pass to the state space class
            constructor.

        i    N(   R+   t   TR   R5   R7   t   ssmt   bindt   k_endog(   R9   R#   R+   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR8      s    c         C` s   |  j  j | |  S(   N(   RD   t   __setitem__(   R9   t   keyR(   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRG      s    c         C` s   |  j  j |  S(   N(   RD   t   __getitem__(   R9   RH   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRI      s    c         K` s   |  j  j | |  d S(   sd  
        Set the filtering method

        The filtering method controls aspects of which Kalman filtering
        approach will be used.

        Parameters
        ----------
        filter_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
        -----
        This method is rarely used. See the corresponding function in the
        `KalmanFilter` class for details.
        N(   RD   t   set_filter_method(   R9   t   filter_methodR#   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRJ      s    c         K` s   |  j  j | |  d S(   s  
        Set the inversion method

        The Kalman filter may contain one matrix inversion: that of the
        forecast error covariance matrix. The inversion method controls how and
        if that inverse is performed.

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

        Notes
        -----
        This method is rarely used. See the corresponding function in the
        `KalmanFilter` class for details.
        N(   RD   t   set_inversion_method(   R9   t   inversion_methodR#   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRL      s    c         K` s   |  j  j | |  d S(   s  
        Set the numerical stability method

        The Kalman filter is a recursive algorithm that may in some cases
        suffer issues with numerical stability. The stability method controls
        what, if any, measures are taken to promote stability.

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

        Notes
        -----
        This method is rarely used. See the corresponding function in the
        `KalmanFilter` class for details.
        N(   RD   t   set_stability_method(   R9   t   stability_methodR#   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRN      s    c         K` s   |  j  j | |  d S(   s  
        Set the memory conservation method

        By default, the Kalman filter computes a number of intermediate
        matrices at each iteration. The memory conservation options control
        which of those matrices are stored.

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

        Notes
        -----
        This method is rarely used. See the corresponding function in the
        `KalmanFilter` class for details.
        N(   RD   t   set_conserve_memory(   R9   t   conserve_memoryR#   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRP      s    c         K` s   |  j  j | |  d S(   sy  
        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.

        Notes
        -----
        This method is rarely used. See the corresponding function in the
        `KalmanSmoother` class for details.
        N(   RD   t   set_smoother_output(   R9   t   smoother_outputR#   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRR     s    c         C` s   |  j  j | |  d S(   s   Initialize knownN(   RD   t   initialize_known(   R9   t   initial_statet   initial_state_cov(    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRT   &  s    c         C` s   |  j  j |  d S(   s   Initialize approximate diffuseN(   RD   t   initialize_approximate_diffuse(   R9   t   variance(    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRW   *  s    c         C` s   |  j  j   d S(   s   Initialize stationaryN(   RD   t   initialize_stationary(   R9   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRY   .  s    c         C` s
   |  j  j S(   N(   RD   t   initialization(   R9   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRZ   2  s    c         C` s   | |  j  _ d  S(   N(   RD   RZ   (   R9   R(   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRZ   6  s    c         C` s
   |  j  j S(   N(   RD   t   initial_variance(   R9   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR[   :  s    c         C` s   | |  j  _ d  S(   N(   RD   R[   (   R9   R(   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR[   >  s    c         C` s
   |  j  j S(   N(   RD   t   loglikelihood_burn(   R9   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR\   B  s    c         C` s   | |  j  _ d  S(   N(   RD   R\   (   R9   R(   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR\   F  s    c         C` s
   |  j  j S(   N(   RD   t	   tolerance(   R9   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR]   J  s    c         C` s   | |  j  _ d  S(   N(   RD   R]   (   R9   R(   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR]   N  s    t   opgt   lbfgsi2   i   i   c         K` s  | d k r |  j } t } n  | d k rY | d k rY | j d t  | j d d  n | d k rn d } n  | d k r |  j j } n! | r |  j j r t d   n  | r |  j t j	 |   } n  | d k r i  } n  | j
 i t d 6| d 6| d	 6 | d k	 r| | d
 <n  | f } t t |   j | d | d | d | d | d | d |	 d t | } |
 r|  j | j  S|  j | j d t d | d | } | | _ | j | _ | j | _ | Sd S(   s  
        Fits the model by maximum likelihood via Kalman filter.

        Parameters
        ----------
        start_params : array_like, optional
            Initial guess of the solution for the loglikelihood maximization.
            If None, the default is given by Model.start_params.
        transformed : boolean, optional
            Whether or not `start_params` is already transformed. Default is
            True.
        cov_type : str, optional
            The `cov_type` keyword governs the method for calculating the
            covariance matrix of parameter estimates. Can be one of:

            - 'opg' for the outer product of gradient estimator
            - 'oim' for the observed information matrix estimator, calculated
              using the method of Harvey (1989)
            - 'approx' for the observed information matrix estimator,
              calculated using a numerical approximation of the Hessian matrix.
            - 'robust' for an approximate (quasi-maximum likelihood) covariance
              matrix that may be valid even in the presense of some
              misspecifications. Intermediate calculations use the 'oim'
              method.
            - 'robust_approx' is the same as 'robust' except that the
              intermediate calculations use the 'approx' method.
            - 'none' for no covariance matrix calculation.
        cov_kwds : dict or None, optional
            A dictionary of arguments affecting covariance matrix computation.

            **opg, oim, approx, robust, robust_approx**

            - 'approx_complex_step' : boolean, optional - If True, numerical
              approximations are computed using complex-step methods. If False,
              numerical approximations are computed using finite difference
              methods. Default is True.
            - 'approx_centered' : boolean, optional - If True, numerical
              approximations computed using finite difference methods use a
              centered approximation. Default is False.
        method : str, optional
            The `method` determines which solver from `scipy.optimize`
            is used, and it can be chosen from among the following strings:

            - 'newton' for Newton-Raphson, 'nm' for Nelder-Mead
            - 'bfgs' for Broyden-Fletcher-Goldfarb-Shanno (BFGS)
            - 'lbfgs' for limited-memory BFGS with optional box constraints
            - 'powell' for modified Powell's method
            - 'cg' for conjugate gradient
            - 'ncg' for Newton-conjugate gradient
            - 'basinhopping' for global basin-hopping solver

            The explicit arguments in `fit` are passed to the solver,
            with the exception of the basin-hopping solver. Each
            solver has several optional arguments that are not the same across
            solvers. See the notes section below (or scipy.optimize) for the
            available arguments and for the list of explicit arguments that the
            basin-hopping solver supports.
        maxiter : int, optional
            The maximum number of iterations to perform.
        full_output : boolean, optional
            Set to True to have all available output in the Results object's
            mle_retvals attribute. The output is dependent on the solver.
            See LikelihoodModelResults notes section for more information.
        disp : boolean, optional
            Set to True to print convergence messages.
        callback : callable callback(xk), optional
            Called after each iteration, as callback(xk), where xk is the
            current parameter vector.
        return_params : boolean, optional
            Whether or not to return only the array of maximizing parameters.
            Default is False.
        optim_score : {'harvey', 'approx'} or None, optional
            The method by which the score vector is calculated. 'harvey' uses
            the method from Harvey (1989), 'approx' uses either finite
            difference or complex step differentiation depending upon the
            value of `optim_complex_step`, and None uses the built-in gradient
            approximation of the optimizer. Default is None. This keyword is
            only relevant if the optimization method uses the score.
        optim_complex_step : bool, optional
            Whether or not to use complex step differentiation when
            approximating the score; if False, finite difference approximation
            is used. Default is True. This keyword is only relevant if
            `optim_score` is set to 'harvey' or 'approx'.
        optim_hessian : {'opg','oim','approx'}, optional
            The method by which the Hessian is numerically approximated. 'opg'
            uses outer product of gradients, 'oim' uses the information
            matrix formula from Harvey (1989), and 'approx' uses numerical
            approximation. This keyword is only relevant if the
            optimization method uses the Hessian matrix.
        **kwargs
            Additional keyword arguments to pass to the optimizer.

        Returns
        -------
        MLEResults

        See Also
        --------
        statsmodels.base.model.LikelihoodModel.fit
        MLEResults
        R_   t   approx_gradt   epsilongh㈵>t   approxsH   Cannot use complex step derivatives when data or parameters are complex.t   transformedt   score_methodt   approx_complex_stept   hessian_methodt   methodt   fargst   maxitert   full_outputt   dispt   callbackt   skip_hessiant   cov_typet   cov_kwdsN(   RA   t   start_paramst   Truet
   setdefaultRD   t   _complex_endogt
   ValueErrort   untransform_paramsR<   R=   t   updatet   FalseR1   R*   t   fitt   transform_paramst   paramst   smootht   mlefitt   mle_retvalst   mle_settings(   R9   Rp   Rc   Rn   Ro   Rg   Ri   Rj   Rk   Rl   t   return_paramst   optim_scoret   optim_complex_stept   optim_hessianR%   R#   Rh   R|   t   res(    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRx   R  sJ    j							c         C` s   i t  t f d 6S(   NRx   (   t
   MLEResultst   MLEResultsWrapper(   R9   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   _res_classes  s    c   
      C` s   | s i  } | d  k	 r% | | d <n  | d  k	 r> | | d <n  | d  k r^ |  j d d } n  | d  k r~ |  j d d } n  | |  | | |  }	 | |	  } n  | S(   NRn   Ro   Rx   i    i   (   RA   R   (
   R9   Rz   t   resultt
   return_rawRn   Ro   t   results_classt   wrapper_classt   result_kwargsR   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   _wrap_results  s    c	         K` s   t  j | d d } | s- |  j |  } n  |  j | d t d | |  j |  j _ | rl t t B|	 d <n  |  j	 j
 d | |	  }
 |  j | |
 | | | | |  S(   s  
        Kalman filtering

        Parameters
        ----------
        params : array_like
            Array of parameters at which to evaluate the loglikelihood
            function.
        transformed : boolean, optional
            Whether or not `params` is already transformed. Default is True.
        return_ssm : boolean,optional
            Whether or not to return only the state space output or a full
            results object. Default is to return a full results object.
        cov_type : str, optional
            See `MLEResults.fit` for a description of covariance matrix types
            for results object.
        cov_kwds : dict or None, optional
            See `MLEResults.get_robustcov_results` for a description required
            keywords for alternative covariance estimators
        **kwargs
            Additional keyword arguments to pass to the Kalman filter. See
            `KalmanFilter.filter` for more details.
        t   ndmini   Rc   t   complex_stepRM   (   R<   R=   Ry   Rv   Rq   t   param_namesR>   R   R   RD   t   filterR   (   R9   Rz   Rc   R   Rn   Ro   t
   return_ssmR   t   results_wrapper_classR#   R   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR   	  s    c	         K` s   t  j | d d } | s- |  j |  } n  |  j | d t d | |  j |  j _ | rl t t B|	 d <n  |  j	 j
 d | |	  }
 |  j | |
 | | | | |  S(   s  
        Kalman smoothing

        Parameters
        ----------
        params : array_like
            Array of parameters at which to evaluate the loglikelihood
            function.
        transformed : boolean, optional
            Whether or not `params` is already transformed. Default is True.
        return_ssm : boolean,optional
            Whether or not to return only the state space output or a full
            results object. Default is to return a full results object.
        cov_type : str, optional
            See `MLEResults.fit` for a description of covariance matrix types
            for results object.
        cov_kwds : dict or None, optional
            See `MLEResults.get_robustcov_results` for a description required
            keywords for alternative covariance estimators
        **kwargs
            Additional keyword arguments to pass to the Kalman filter. See
            `KalmanFilter.filter` for more details.
        R   i   Rc   R   RM   (   R<   R=   Ry   Rv   Rq   R   R>   R   R   RD   R{   R   (   R9   Rz   Rc   R   Rn   Ro   R   R   R   R#   R   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR{   7  s    Rc   R   c         O` s   t  t j t j | |  \ } } } | s< |  j |  } n  |  j | d t d | | rl t t B| d <n  |  j	 j
 d | |  } | S(   s  
        Loglikelihood evaluation

        Parameters
        ----------
        params : array_like
            Array of parameters at which to evaluate the loglikelihood
            function.
        transformed : boolean, optional
            Whether or not `params` is already transformed. Default is True.
        kwargs
            Additional keyword arguments to pass to the Kalman filter. See
            `KalmanFilter.filter` for more details.

        Notes
        -----
        [1]_ recommend maximizing the average likelihood to avoid scale issues;
        this is done automatically by the base Model fit method.

        References
        ----------
        .. [1] Koopman, Siem Jan, Neil Shephard, and Jurgen A. Doornik. 1999.
           Statistical Algorithms for Models in State Space Using SsfPack 2.2.
           Econometrics Journal 2 (1): 107-60. doi:10.1111/1368-423X.00023.

        See Also
        --------
        update : modifies the internal state of the state space model to
                 reflect new params
        Rc   R   RM   (   R)   R*   t   _loglike_param_namest   _loglike_param_defaultsRy   Rv   Rq   R   R   RD   t   loglike(   R9   Rz   R"   R#   Rc   R   R   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR   h  s    c         K` s^   | s |  j  |  } n  | r/ t t B| d <n  |  j | d t d | |  j j d | |  S(   s   
        Loglikelihood evaluation

        Parameters
        ----------
        params : array_like
            Array of parameters at which to evaluate the loglikelihood
            function.
        transformed : boolean, optional
            Whether or not `params` is already transformed. Default is True.
        **kwargs
            Additional keyword arguments to pass to the Kalman filter. See
            `KalmanFilter.filter` for more details.

        Notes
        -----
        [1]_ recommend maximizing the average likelihood to avoid scale issues;
        this is done automatically by the base Model fit method.

        References
        ----------
        .. [1] Koopman, Siem Jan, Neil Shephard, and Jurgen A. Doornik. 1999.
           Statistical Algorithms for Models in State Space Using SsfPack 2.2.
           Econometrics Journal 2 (1): 107-60. doi:10.1111/1368-423X.00023.

        See Also
        --------
        update : modifies the internal state of the Model to reflect new params
        RM   Rc   R   (   Ry   R   R   Rv   Rq   RD   t
   loglikeobs(   R9   Rz   Rc   R   R#   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR     s    c         K` s   |  j  j d | |  S(   s  
        Retrieve a simulation smoother for the state space model.

        Parameters
        ----------
        simulation_output : int, optional
            Determines which simulation smoother output is calculated.
            Default is all (including state and disturbances).
        **kwargs
            Additional keyword arguments, used to set the simulation output.
            See `set_simulation_output` for more details.

        Returns
        -------
        SimulationSmoothResults
        t   simulation_output(   RD   t   simulation_smoother(   R9   R   R#   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR     s    c         K` s  t  j | d d } | d  k r* | } n  | rF | rF t d   n  | r] t t B| d <n  | d  k r |  j | d | d | |  j j d | |  } n  t	 |  } t  j
 |  j |  j | f  } t  j
 |  j |  j |  j | f  }	 | rt | d d  |  }
 t  j |  d |
 } xt |  D] \ } } |  j | | d | d t |  j j d t |  } | j j |
 | | d  d   d  d   | f <| j j |
 | |	 d  d   d  d   d  d   | f <q*Wn<| st | d d  |  }
 t  j
 | f t  } x	t |  D] } |
 | | | <|  j | | d | d t |  j j d t |  } | j | j |
 | | d  d   d  d   | f <| j | j |
 | |	 d  d   d  d   d  d   | f <d	 | | <qWn:t | d
 d  |  d }
 t  j
 | f t  } x	t |  D] } |
 | | | <|  j | | d | d t |  j j d t |  } |  j | | d | d t |  j j d t |  } | j | j d |
 | | d  d   d  d   | f <| j | j d |
 | |	 d  d   d  d   d  d   | f <d	 | | <qW| |	 f S(   NR   i   sr   Cannot use complex-step approximations to calculate the observed_information_matrix with untransformed parameters.RM   Rc   R   i   y              ?g        i   g       @(   R<   R=   RA   Rt   R   R   Rv   RD   R   R   t   zerosRF   R6   R   R   t	   enumerateRq   t   forecasts_errort   imagt   forecasts_error_covt   floatR   Rw   (   R9   Rz   Rc   Re   t   approx_centeredR   R#   t   nt   partials_forecasts_errort   partials_forecasts_error_covRa   t
   incrementsR&   t   iht   _rest   eit   _res1t   _res2(    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt$   _forecasts_error_partial_derivatives  sf    	$-=14(1c         K` s%  t  j | d d } t |  } | d k r6 | } n  | rR | rR t d   n  |  j | d | d | | r t t B| d <n  |  j j	 d | |  } |  j j
 } | j j   }	 |  j | d | d | d | d	 | | \ }
 } t  j |  j |  j |  j | f d
 | } t  j | | f d
 | } xt |  j j |  j  D]} t  j j | j d d  d d  | f  |	 d d  d d  | f <xw t |  D]i } t  j |	 d d  d d  | f | d d  d d  | | f  | d d  d d  | | f <qWx t |  D] } x t |  D] } | | | f c d t  j t  j | d d  d d  | | f | d d  d d  | | f   7<| | | f c t  j |
 d d  | | f t  j |	 d d  d d  | f |
 d d  | | f   7<q*WqWqCW| |  j |  j j S(   s  
        Observed information matrix

        Parameters
        ----------
        params : array_like, optional
            Array of parameters at which to evaluate the loglikelihood
            function.
        **kwargs
            Additional keyword arguments to pass to the Kalman filter. See
            `KalmanFilter.filter` for more details.

        Notes
        -----
        This method is from Harvey (1989), which shows that the information
        matrix only depends on terms from the gradient. This implementation is
        partially analytic and partially numeric approximation, therefore,
        because it uses the analytic formula for the information matrix, with
        numerically computed elements of the gradient.

        References
        ----------
        Harvey, Andrew C. 1990.
        Forecasting, Structural Time Series Models and the Kalman Filter.
        Cambridge University Press.

        R   i   sr   Cannot use complex-step approximations to calculate the observed_information_matrix with untransformed parameters.Rc   R   RM   Re   R   R   t   dtypeNg      ?(   R<   R=   R   RA   Rt   Rv   R   R   RD   R   R   R   t   copyR   R   RF   R6   R   R\   t   linalgt   invt   dott   tracet   inner(   R9   Rz   Rc   Re   R   R#   R   R   R   t   inv_forecasts_error_covR   R   t   tmpt   information_matrixt   tR&   t   j(    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   observed_information_matrix8  sF    	*GE.)"+c         K` sv   | d k r | } n  | r1 | r1 t d   n  |  j | d | d | | j   } t j | |  |  j |  j j S(   s0  
        Outer product of gradients information matrix

        Parameters
        ----------
        params : array_like, optional
            Array of parameters at which to evaluate the loglikelihood
            function.
        **kwargs
            Additional arguments to the `loglikeobs` method.

        References
        ----------
        Berndt, Ernst R., Bronwyn Hall, Robert Hall, and Jerry Hausman. 1974.
        Estimation and Inference in Nonlinear Structural Models.
        NBER Chapters. National Bureau of Economic Research, Inc.

        sr   Cannot use complex-step approximations to calculate the observed_information_matrix with untransformed parameters.Rc   Re   N(	   RA   Rt   t	   score_obst	   transposeR<   R   R6   RD   R\   (   R9   Rz   Rc   Re   R#   R   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   opg_information_matrix  s    	c         K` sK   t  | d d  t |   } t | d <t | d <t | |  j d | d | S(   Ng       @Rc   R   Ra   R#   (   R   RA   R   Rq   R
   R   (   R9   Rz   R#   Ra   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   _score_complex_step  s
    

c         K` s&   t  | d <t | |  j d | d | S(   NRc   R#   t   centered(   Rq   R   R   (   R9   Rz   R   R#   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   _score_finite_difference  s    
c         K` s+   |  j  | d | | } t j | d d S(   NRe   t   axisi    (   t   _score_obs_harveyR<   t   sum(   R9   Rz   Re   R#   R   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   _score_harvey  s    c         K` s  t  j | d d } t |  } |  j | d t d | | rQ t t B| d <n  |  j j d | |  } |  j	 | d t d | d | d | | \ } } t  j
 |  j | f  }	 |  j }
 xRt |  j  D]A} t  j j | j d	 d	  d	 d	  | f  } x
t |  D] } |	 | | f c t  j t  j t  j | | d	 d	  d	 d	  | | f  t  j |
  t  j | t  j | j d	 d	  | f | j d	 d	  | f     7<|	 | | f c d
 t  j | d	 d	  | | f t  j | | j d	 d	  | f   7<qWq W|	 d S(   s]  
        Score

        Parameters
        ----------
        params : array_like, optional
            Array of parameters at which to evaluate the loglikelihood
            function.
        **kwargs
            Additional keyword arguments to pass to the Kalman filter. See
            `KalmanFilter.filter` for more details.

        Notes
        -----
        This method is from Harvey (1989), section 3.4.5

        References
        ----------
        Harvey, Andrew C. 1990.
        Forecasting, Structural Time Series Models and the Kalman Filter.
        Cambridge University Press.

        R   i   Rc   R   RM   Re   R   R   Ni   g       @(   R<   R=   R   Rv   Rq   R   R   RD   R   R   R   R6   RF   R   R   R   R   R   R   t   eyet   outerR   (   R9   Rz   Re   R   R#   R   R   R   R   t   partialsRF   R   R   R&   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR     s6    		%	"	&1Rd   Re   R   Rb   c   
      O` sa  t  j | d d } t t j t j | |  \ } } } } } d | k r] | j d  } n  | d
 k ry |  j j	 } n  | r |  j j	 r t
 d   n  | s |  j |  } |  j |  } n  | d k r |  j | d | | }	 nZ | d k r| r|  j | |  }	 n3 | d k r6|  j | d | | }	 n t d	   | s]t  j | |	  }	 n  |	 S(   s/  
        Compute the score function at params.

        Parameters
        ----------
        params : array_like
            Array of parameters at which to evaluate the score.
        args
            Additional positional arguments to the `loglike` method.
        kwargs
            Additional keyword arguments to the `loglike` method.

        Returns
        -------
        score : array
            Score, evaluated at `params`.

        Notes
        -----
        This is a numerical approximation, calculated using first-order complex
        step differentiation on the `loglike` method.

        Both args and kwargs are necessary because the optimizer from
        `fit` must call this function and only supports passing arguments via
        args (for example `scipy.optimize.fmin_l_bfgs`).
        R   i   Rg   sH   Cannot use complex step derivatives when data or parameters are complex.t   harveyRe   Rb   R   s   Invalid score method.N(   R<   R=   R)   R*   t   _score_param_namest   _score_param_defaultsR   RA   RD   Rs   Rt   t   transform_jacobianRy   R   R   R   t   NotImplementedErrorR   (
   R9   Rz   R"   R#   Rc   Rg   Re   R   t   transform_scoret   score(    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR     s0    	!c   	      K` sD  t  j | d d } | r1 | r1 t d   n  | d k rM |  j j } n  | rn |  j j rn t d   n  | d k r |  j | d | d | | } n | d k r | r t | d	 d t |   } t	 | d
 <t	 | d <t
 | |  j d | d | } nC | d k r4| | d <t | |  j d | d | } n t d   | S(   s+  
        Compute the score per observation, evaluated at params

        Parameters
        ----------
        params : array_like
            Array of parameters at which to evaluate the score.
        kwargs
            Additional arguments to the `loglike` method.

        Returns
        -------
        score : array
            Score per observation, evaluated at `params`.

        Notes
        -----
        This is a numerical approximation, calculated using first-order complex
        step differentiation on the `loglikeobs` method.
        R   i   sp   Cannot use complex-step approximations to calculate the score at each observation with untransformed parameters.sH   Cannot use complex step derivatives when data or parameters are complex.R   Rc   Re   Rb   g       @R   Ra   R#   R   s   Invalid scoreobs method.N(   R<   R=   Rt   RA   RD   Rs   R   R   R   Rq   R
   R   R   R   (	   R9   Rz   Rg   Rc   Re   R   R#   R   Ra   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR   N  s.    


Rf   c   	   	   O` sq  t  t j t j | |  \ } } } } } d | k rH | j d  } n  | rd | rd t d   n  | d k r |  j j } n  | r |  j j r t d   n  | d k r |  j	 | d | d | d | | } n | d k r|  j
 | d | d | d | | } nf | d	 k r4| r4|  j | d | | } n9 | d	 k ra|  j | d | d | | } n t d
   | S(   s  
        Hessian matrix of the likelihood function, evaluated at the given
        parameters

        Parameters
        ----------
        params : array_like
            Array of parameters at which to evaluate the hessian.
        args
            Additional positional arguments to the `loglike` method.
        kwargs
            Additional keyword arguments to the `loglike` method.

        Returns
        -------
        hessian : array
            Hessian matrix evaluated at `params`

        Notes
        -----
        This is a numerical approximation.

        Both args and kwargs are necessary because the optimizer from
        `fit` must call this function and only supports passing arguments via
        args (for example `scipy.optimize.fmin_l_bfgs`).
        Rg   s^   Cannot use complex-step approximations to calculate the hessian with untransformed parameters.sH   Cannot use complex step derivatives when data or parameters are complex.t   oimRc   Re   R   R^   Rb   s#   Invalid Hessian calculation method.N(   R)   R*   t   _hessian_param_namest   _hessian_param_defaultsR   Rt   RA   RD   Rs   t   _hessian_oimt   _hessian_opgt   _hessian_complex_stept   _hessian_finite_differenceR   (	   R9   Rz   R"   R#   Rc   Rg   Re   R   t   hessian(    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR     s<    	c         K` s   |  j  | |  S(   sT   
        Hessian matrix computed using the Harvey (1989) information matrix
        (   R   (   R9   Rz   R#   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR     s    c         K` s   |  j  | |  S(   si   
        Hessian matrix computed using the outer product of gradients
        information matrix
        (   R   (   R9   Rz   R#   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR     s    c      	   K` s   t  j | d d } t j d t  | sI t | d d  t |   } n t | d d  t |   d } t | |  j	 d | d | d	 | } | |  j
 |  j j S(
   NR   i   sk   Calculation of the Hessian using finite differences is usually subject to substantial approximation errors.i   i   i   Ra   R#   R   (   R<   R=   t   warningst   warnR   R   RA   R   R   R   R6   RD   R\   (   R9   Rz   R   R#   Ra   R   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR     s    		c         K` sb   t  | d d t |   } t | d <t | d <t | |  j d | d | } | |  j |  j j S(   sy   
        Hessian matrix computed by second-order complex-step differentiation
        on the `loglike` function.
        g      @Rc   R   Ra   R#   N(	   R   RA   R   Rq   R	   R   R6   RD   R\   (   R9   Rz   R#   Ra   R   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR     s    

c         C` s    t  |  d  r |  j St  d S(   sP   
        (array) Starting parameters for maximum likelihood estimation.
        t   _start_paramsN(   t   hasattrR   R   (   R9   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRp     s    c         C` sh   t  |  d  r |  j Sy0 g  t t |  j   D] } d | ^ q/ } Wn t k
 r_ g  } n X| Sd S(   s   
        (list of str) List of human readable parameter names (for parameters
        actually included in the model).
        t   _param_namess   param.%dN(   R   R   R   R   Rp   R   (   R9   R&   R    (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR     s    0
c         C` s   t  | |  j d | S(   s  
        Jacobian matrix for the parameter transformation function

        Parameters
        ----------
        unconstrained : array_like
            Array of unconstrained parameters used by the optimizer.

        Returns
        -------
        jacobian : array
            Jacobian matrix of the transformation, evaluated at `unconstrained`

        Notes
        -----
        This is a numerical approximation using finite differences. Note that
        in general complex step methods cannot be used because it is not
        guaranteed that the `transform_params` method is a real function (e.g.
        if Cholesky decomposition is used).

        See Also
        --------
        transform_params
        R   (   R   Ry   (   R9   t   unconstrainedR   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR     s    c         C` s   t  j | d d S(   sZ  
        Transform unconstrained parameters used by the optimizer to constrained
        parameters used in likelihood evaluation

        Parameters
        ----------
        unconstrained : array_like
            Array of unconstrained parameters used by the optimizer, to be
            transformed.

        Returns
        -------
        constrained : array_like
            Array of constrained parameters which may be used in likelihood
            evalation.

        Notes
        -----
        This is a noop in the base class, subclasses should override where
        appropriate.
        R   i   (   R<   R=   (   R9   R   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRy   0  s    c         C` s   t  j | d d S(   sA  
        Transform constrained parameters used in likelihood evaluation
        to unconstrained parameters used by the optimizer

        Parameters
        ----------
        constrained : array_like
            Array of constrained parameters used in likelihood evalution, to be
            transformed.

        Returns
        -------
        unconstrained : array_like
            Array of unconstrained parameters used by the optimizer.

        Notes
        -----
        This is a noop in the base class, subclasses should override where
        appropriate.
        R   i   (   R<   R=   (   R9   t   constrained(    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRu   H  s    c         C` s1   t  j | d d } | s- |  j |  } n  | S(   sE  
        Update the parameters of the model

        Parameters
        ----------
        params : array_like
            Array of new parameters.
        transformed : boolean, optional
            Whether or not `params` is already transformed. If set to False,
            `transform_params` is called. Default is True.

        Returns
        -------
        params : array_like
            Array of parameters.

        Notes
        -----
        Since Model is a base class, this method should be overridden by
        subclasses to perform actual updating steps.
        R   i   (   R<   R=   Ry   (   R9   Rz   Rc   R   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRv   _  s    c         C` s^   |  j  |  |  j j | | | |  \ } } | j d d k rZ | d d  d f } n  | S(   s_  
        Simulate a new time series following the state space model

        Parameters
        ----------
        params : array_like
            Array of model parameters.
        nsimulations : int
            The number of observations to simulate. If the model is
            time-invariant this can be any number. If the model is
            time-varying, then this number must be less than or equal to the
            number
        measurement_shocks : array_like, optional
            If specified, these are the shocks to the measurement equation,
            :math:`\varepsilon_t`. If unspecified, these are automatically
            generated using a pseudo-random number generator. If specified,
            must be shaped `nsimulations` x `k_endog`, where `k_endog` is the
            same as in the state space model.
        state_shocks : array_like, optional
            If specified, these are the shocks to the state equation,
            :math:`\eta_t`. If unspecified, these are automatically
            generated using a pseudo-random number generator. If specified,
            must be shaped `nsimulations` x `k_posdef` where `k_posdef` is the
            same as in the state space model.
        initial_state : array_like, optional
            If specified, this is the state vector at time zero, which should
            be shaped (`k_states` x 1), where `k_states` is the same as in the
            state space model. If unspecified, but the model has been
            initialized, then that initialization is used. If unspecified and
            the model has not been initialized, then a vector of zeros is used.
            Note that this is not included in the returned `simulated_states`
            array.

        Returns
        -------
        simulated_obs : array
            An (nsimulations x k_endog) array of simulated observations.
        i   Ni    (   Rv   RD   t   simulateR5   (   R9   Rz   t   nsimulationst   measurement_shockst   state_shocksRU   t   simulated_obst   simulated_states(    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR   |  s    (	i    c         K` s[   |  j  |  |  j j | | | | |  } | j d d k rW | d d  d f } n  | S(   s9  
        Impulse response function

        Parameters
        ----------
        params : array_like
            Array of model parameters.
        steps : int, optional
            The number of steps for which impulse responses are calculated.
            Default is 1. Note that the initial impulse is not counted as a
            step, so if `steps=1`, the output will have 2 entries.
        impulse : int or array_like
            If an integer, the state innovation to pulse; must be between 0
            and `k_posdef-1`. Alternatively, a custom impulse vector may be
            provided; must be shaped `k_posdef x 1`.
        orthogonalized : boolean, optional
            Whether or not to perform impulse using orthogonalized innovations.
            Note that this will also affect custum `impulse` vectors. Default
            is False.
        cumulative : boolean, optional
            Whether or not to return cumulative impulse responses. Default is
            False.
        **kwargs
            If the model is time-varying and `steps` is greater than the number
            of observations, any of the state space representation matrices
            that are time-varying must have updated values provided for the
            out-of-sample steps.
            For example, if `design` is a time-varying component, `nobs` is 10,
            and `steps` is 15, a (`k_endog` x `k_states` x 5) matrix must be
            provided with the new design matrix values.

        Returns
        -------
        impulse_responses : array
            Responses for each endogenous variable due to the impulse
            given by the `impulse` argument. A (steps + 1 x k_endog) array.

        Notes
        -----
        Intercepts in the measurement and state equation are ignored when
        calculating impulse responses.

        i   Ni    (   Rv   RD   t   impulse_responsesR5   (   R9   Rz   t   stepst   impulset   orthogonalizedt
   cumulativeR#   t   irfs(    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR     s    -	c         C` s
   t   d S(   s8   
        Not implemented for state space models
        N(   R   (   t   clst   formulaR>   t   subset(    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   from_formula  s    N(?   t   __name__t
   __module__t   __doc__RA   R2   R4   R8   RG   RI   RJ   RL   RN   RP   RR   RT   RW   RY   t   propertyRZ   t   setterR[   R\   R]   Rq   Rw   Rx   R   R   R   R{   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   R   Rp   R   R   Ry   Ru   Rv   R   R   t   classmethodR   (    (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR*   A   s   /								,	,	2+\W$		?	@6	E			
		26R   c           B` s'  e  Z d  Z d d+ d  Z d d  Z e d    Z e d    Z e	 e
 d  Z e d    Z e	 e
 d  Z e d	    Z e	 e
 d
  Z e d    Z e d    Z e	 e
 d  Z e d    Z e	 e
 d  Z e d    Z d d  Z e d    Z e d    Z e d    Z e d    Z e d    Z e d    Z e d    Z e d    Z d   Z d e	 d  Z  d+ d  Z! d+ d+ e
 d+ d  Z" d  d!  Z# d+ d+ e
 d"  Z$ d  d#  Z% d+ d+ d+ d$  Z& d  d% e
 e
 d&  Z' d% d' d+ d+ d(  Z( d) d+ d+ d+ e	 d*  Z) RS(,   s  
    Class to hold results from fitting a state space model.

    Parameters
    ----------
    model : MLEModel instance
        The fitted model instance
    params : array
        Fitted parameters
    filter_results : KalmanFilter instance
        The underlying state space model and Kalman filter output

    Attributes
    ----------
    model : Model instance
        A reference to the model that was fit.
    filter_results : KalmanFilter instance
        The underlying state space model and Kalman filter output
    nobs : float
        The number of observations used to fit the model.
    params : array
        The parameters of the model.
    scale : float
        This is currently set to 1.0 unless the model uses concentrated
        filtering.

    See Also
    --------
    MLEModel
    statsmodels.tsa.statespace.kalman_filter.FilterResults
    statsmodels.tsa.statespace.representation.FrozenRepresentation
    R^   c         K` s!  | j  |  _  | j } t j j |  | | d d  d | | |  _ t | t  r[ | |  _	 n	 d  |  _	 |  j j
 |  _
 |  j j |  _ |  j d k r |  j d k r t j d  n  |  j
 |  j |  _ |  j j } | d  k r d n t j t j |  d k  |  _ |  j j |  j |  j j |  _ |  j |  j |  _ t |  d  sPi  |  _ n  | |  _ i  |  _ | d  k rwi  } n  | j d t  |  _  | j d t!  |  _" y& d  |  _# |  j$ d	 | d
 t |  Wn[ t j% j& k
 r$d |  _# t' |  j  }	 t j( |	 |	 f  t j) |  _* d |  j d	 <n X|  j+ j, |  j  d d d d d d d d d d d d d d d d d d d d g }
 x- |
 D]% } t- |  | t. |  j | d    qWt. |  d  g   |  _/ |  j/ j0 d! g  |  j1 j0 |
  |  j1 j0 d" d# g  t. |  d$ g   |  _2 |  j2 j0 g   d  S(%   Nt   normalized_cov_paramst   scalei    s   Care should be used when applying a loglikelihood burn to a model with exact diffuse initialization. Some results objects, e.g. degrees of freedom, expect only one of the two to be set.i   Ro   Re   R   Rn   t   use_selfsH   Covariance matrix could not be calculated: singular. information matrix.t   filtered_statet   filtered_state_covt   predicted_statet   predicted_state_covt	   forecastsR   R   t   standardized_forecasts_errort   forecasts_error_diffuse_covt   predicted_diffuse_state_covt   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_covt   _data_attr_modelRD   t   filter_resultst   smoother_resultst   data_in_cache(3   R>   R   t   tsbaset   TimeSeriesModelResultsR2   RA   R  R   R   R  R6   t   nobs_diffuseR\   R   R   t   nobs_effectivet   initial_diffuse_state_covR<   R   t   diagonalt   k_diffuse_statesRz   t   sizet   filter_concentratedt   df_modelt   df_residR   Ro   Rn   t   _cacheR   Rq   t   _cov_approx_complex_stepRw   t   _cov_approx_centeredt   _rankt   _get_robustcov_resultsR   t   LinAlgErrorR   R   t   nant   cov_params_defaultt   modelRv   t   setattrt   getattrR  t   extendt
   _data_attrR  (   R9   R  Rz   t   resultsRn   Ro   R#   R   t   Pt   k_paramst   extra_arraysR'   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR2     sr    			3								#c   	      K` s  d d l  m } | j d t  } | r1 |  } n0 t  |  j |  j |  j d |  j d |  j	 } | | _
 i  | _ |  j } | r d } n |  j r d } n d } t |  j  } | d k r t j d  | _ d | _ d	 | j d
 <n| d k r;| d | _
 | d | _ | d | j d
 <t j j | j  | _ n| d k rt j | | f  t j | _ t j | _ | d | j d
 <nB|  j
 d k r| j | _ | d j d |  | j d
 <n|  j
 d k r| j | _ | d j d |  | j d
 <n |  j
 d k r7| j | _ | d j d |  | j d
 <n |  j
 d k sU|  j
 d k r| j | _ | d j d |  | j d
 <nG |  j
 d k r| j | _ | d j d |  | j d
 <n t d   | S(   s  
        Create new results instance with specified covariance estimator as
        default

        Note: creating new results instance currently not supported.

        Parameters
        ----------
        cov_type : string
            the type of covariance matrix estimator to use. See Notes below
        kwargs : depends on cov_type
            Required or optional arguments for covariance calculation.
            See Notes below.

        Returns
        -------
        results : results instance
            This method creates a new results instance with the requested
            covariance as the default covariance of the parameters.
            Inferential statistics like p-values and hypothesis tests will be
            based on this covariance matrix.

        Notes
        -----
        The following covariance types and required or optional arguments are
        currently available:

        - 'opg' for the outer product of gradient estimator
        - 'oim' for the observed information matrix estimator, calculated
          using the method of Harvey (1989)
        - 'approx' for the observed information matrix estimator,
          calculated using a numerical approximation of the Hessian matrix.
          Uses complex step approximation by default, or uses finite
          differences if `approx_complex_step=False` in the `cov_kwds`
          dictionary.
        - 'robust' for an approximate (quasi-maximum likelihood) covariance
          matrix that may be valid even in the presense of some
          misspecifications. Intermediate calculations use the 'oim'
          method.
        - 'robust_approx' is the same as 'robust' except that the
          intermediate calculations use the 'approx' method.
        - 'none' for no covariance matrix calculation.
        i    (   t   descriptionsR   R   R   s   complex-steps   centered finite differencess   finite differencess   No parameters estimated.t   descriptiont   customt   custom_cov_typet   custom_cov_paramst   custom_descriptionR0   Rb   t   approx_typeR   t   OIMR^   t   OPGt   robustt
   robust_oims
   robust-OIMt   robust_approxs   robust-approxs   Invalid covariance matrix type.(   i    i    (   t   statsmodels.base.covtypeR%  R   Rw   R   t	   __class__R  Rz   R   R   Rn   Ro   R  R  R   R<   R   R  R  R   t   matrix_rankR  t   cov_params_approxt   formatt   cov_params_oimt   cov_params_opgt   cov_params_robust_oimt   cov_params_robust_approx(	   R9   Rn   R#   R%  R   R   Re   t   approx_type_strR#  (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR  n  sj    ,									c         C` s   t  |  j |  j |  j  S(   s6   
        (float) Akaike Information Criterion
        (   R   t   llfR  R  (   R9   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR     s    c         C` s   t  |  j |  j |  j  S(   s5   
        (float) Bayes Information Criterion
        (   R   R;  R  R  (   R9   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR     s    c         C` s   |  j  |  j j d |  j d t d d d | d |  } t |  \ } } |  j j |  j  |  j d  k r t	 j
 j t	 j |   |  _ n  | S(   NRz   Rc   Rg   Rb   Re   R   (   R  R  R   Rz   Rq   R   Rv   R  RA   R<   R   R3  t   diag(   R9   Re   R   t   evaluated_hessiant   neg_covt   singular_values(    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   _cov_params_approx  s    
!c         C` s   |  j  |  j |  j  S(   s   
        (array) The variance / covariance matrix. Computed using the numerical
        Hessian approximated by complex step or finite differences methods.
        (   R@  R  R  (   R9   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR4    s    c         C` s   |  j  |  j j |  j d d d t d | d | } t |  \ } } |  j j |  j  |  j d  k r t	 j
 j t	 j |   |  _ n  | S(   NRf   R   Rc   Re   R   (   R  R  R   Rz   Rq   R   Rv   R  RA   R<   R   R3  R<  (   R9   Re   R   R=  R>  R?  (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   _cov_params_oim  s    
!c         C` s   |  j  |  j |  j  S(   sq   
        (array) The variance / covariance matrix. Computed using the method
        from Harvey (1989).
        (   RA  R  R  (   R9   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR6    s    c      	   C` s   |  j  |  j j |  j d t d | d | } t |  \ } } |  j j |  j  |  j d  k r t	 j
 j t	 j |   |  _ n  | S(   NRc   Re   R   (   R  R  R   Rz   Rq   R   Rv   R  RA   R<   R   R3  R<  (   R9   Re   R   R=  R>  R?  (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   _cov_params_opg  s    
!c         C` s   |  j  |  j |  j  S(   sy   
        (array) The variance / covariance matrix. Computed using the outer
        product of gradients method.
        (   RB  R  R  (   R9   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR7  '  s    c         C` s   |  j  S(   sj   
        (array) The QMLE variance / covariance matrix. Alias for
        `cov_params_robust_oim`
        (   R8  (   R9   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   cov_params_robust0  s    c         C` s   |  j  d | d |  } |  j |  j j |  j d d d t d | d | } t t j t j | |  |   \ } } |  j j	 |  j  |  j
 d  k r t j j t j |   |  _
 n  | S(   NRe   R   Rf   R   Rc   (   RB  R  R  R   Rz   Rq   R   R<   R   Rv   R  RA   R   R3  R<  (   R9   Re   R   t   cov_opgR=  t
   cov_paramsR?  (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   _cov_params_robust_oim8  s    	
'!c         C` s   |  j  |  j |  j  S(   s   
        (array) The QMLE variance / covariance matrix. Computed using the
        method from Harvey (1989) as the evaluated hessian.
        (   RF  R  R  (   R9   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR8  K  s    c      	   C` s   |  j  d | d |  } |  j |  j j |  j d t d d d | } t t j t j | |  |   \ } } |  j j	 |  j  |  j
 d  k r t j j t j |   |  _
 n  | S(   NRe   R   Rc   Rg   Rb   (   RB  R  R  R   Rz   Rq   R   R<   R   Rv   R  RA   R   R3  R<  (   R9   Re   R   RD  R=  RE  R?  (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   _cov_params_robust_approxT  s    	
'!c         C` s   |  j  |  j |  j  S(   s   
        (array) The QMLE variance / covariance matrix. Computed using the
        numerical Hessian as the evaluated hessian.
        (   RG  R  R  (   R9   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR9  h  s    t   standardc         C` s  | j    } | j    } | d k r6 t |  |  } nY| d k r|  j j j d d k rj t d   n  |  j j d d  d d  d f } | d k r t j t j j	 |  d d	 |  j
 |  j  } q| d
 k rt j t j j	 |  d |  j
 t j |  j  |  j  } q| d k rtt j t j j	 |  d d	 |  j
 t j t j |  j   |  j  } qt d   n t d   | S(   sk  
        Information criteria

        Parameters
        ----------
        criteria : {'aic', 'bic', 'hqic'}
            The information criteria to compute.
        method : {'standard', 'lutkepohl'}
            The method for information criteria computation. Default is
            'standard' method; 'lutkepohl' computes the information criteria
            as in Lütkepohl (2007). See Notes for formulas.

        Notes
        -----
        The `'standard'` formulas are:

        .. math::

            AIC & = -2 \log L(Y_n | \hat \psi) + 2 k \\
            BIC & = -2 \log L(Y_n | \hat \psi) + k \log n \\
            HQIC & = -2 \log L(Y_n | \hat \psi) + 2 k \log \log n \\

        where :math:`\hat \psi` are the maximum likelihood estimates of the
        parameters, :math:`n` is the number of observations, and `k` is the
        number of estimated parameters.

        Note that the `'standard'` formulas are returned from the `aic`, `bic`,
        and `hqic` results attributes.

        The `'lutkepohl'` formuals are (Lütkepohl, 2010):

        .. math::

            AIC_L & = \log | Q | + \frac{2 k}{n} \\
            BIC_L & = \log | Q | + \frac{k \log n}{n} \\
            HQIC_L & = \log | Q | + \frac{2 k \log \log n}{n} \\

        where :math:`Q` is the state covariance matrix. Note that the Lütkepohl
        definitions do not apply to all state space models, and should be used
        with care outside of SARIMAX and VARMAX models.

        References
        ----------
        .. [*] Lütkepohl, Helmut. 2007. *New Introduction to Multiple Time*
           *Series Analysis.* Berlin: Springer.
        RH  t	   lutkepohlii   sZ   Cannot compute Lütkepohl statistics for models with time-varying state covariance matrix.Ni    R   i   R   R   s   Invalid information criterias/   Invalid information criteria computation method(   t   lowerR  R  t	   state_covR5   Rt   R<   t   squeezeR   t   slogdetR  R  t   log(   R9   t   criteriaRg   t   outt   cov(    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   info_criteriaq  s,    /%#c         C` sB   |  j  } | j d d k r5 | d d d  f } n	 | j } | S(   sW   
        (array) The predicted values of the model. An (nobs x k_endog) array.
        i    i   N(   R   R5   RC   (   R9   t   fittedvalues(    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRS    s
    		c         C` s   t  |  j |  j |  j  S(   s<   
        (float) Hannan-Quinn Information Criterion
        (   R   R;  R  R  (   R9   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR     s    c         C` s
   |  j  j S(   sY   
        (float) The value of the log-likelihood function evaluated at `params`.
        (   R  t   llf_obs(   R9   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRT    s    c         C` s   |  j  |  j j j   S(   sY   
        (float) The value of the log-likelihood function evaluated at `params`.
        (   RT  R  R\   R   (   R9   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR;    s    c         C` s
   |  j  j S(   sj   
        (float) The number of observations during which the likelihood is not
        evaluated.
        (   R  R\   (   R9   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR\     s    c         C` s   t  j t j |  j   d S(   s   
        (array) The p-values associated with the z-statistics of the
        coefficients. Note that the coefficients are assumed to have a Normal
        distribution.
        i   (   R   t   sfR<   t   abst   zvalues(   R9   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   pvalues  s    c         C` sB   |  j  } | j d d k r5 | d d d  f } n	 | j } | S(   sI   
        (array) The model residuals. An (nobs x k_endog) array.
        i    i   N(   R   R5   RC   (   R9   t   resid(    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRY    s
    		c         C` s   |  j  |  j S(   s@   
        (array) The z-statistics for the coefficients.
        (   Rz   t   bse(   R9   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRW    s    c         C` s   | d k r d } n  | d k r d d l m } t j |  j |  j  } g  } xl t |  j j	  D]I } |  j
 j | | d  f } t j |  } | j | | |   qb Wn t d   t j |  S(   sV  
        Test for normality of standardized residuals.

        Null hypothesis is normality.

        Parameters
        ----------
        method : string {'jarquebera'} or None
            The statistical test for normality. Must be 'jarquebera' for
            Jarque-Bera normality test. If None, an attempt is made to select
            an appropriate test.

        Notes
        -----
        Let `d` = max(loglikelihood_burn, nobs_diffuse); this test is
        calculated ignoring the first `d` residuals.

        In the case of missing data, the maintained hypothesis is that the
        data are missing completely at random. This test is then run on the
        standardized residuals excluding those corresponding to missing
        observations.

        See Also
        --------
        statsmodels.stats.stattools.jarque_bera

        t
   jarqueberai    (   t   jarque_beraNs   Invalid normality test method.(   RA   t   statsmodels.stats.stattoolsR\  R<   t   maximumR\   R  R   R  RF   R  R   t   isnanR   R   R=   (   R9   Rg   R\  t   dt   outputR&   RY  t   mask(    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   test_normality  s    	s	   two-sidedc         ` s  | d k r d } n  | d k r|  j j d } t j |  j |  j  } |  j | } g  } g  } x2t |  j	 j
  D]}	 t t j | d   }
 | |	 |
 d  f } | t j |  } t |   | |	 | | |
  f } | t j |  } t |    d k  r.t j d |	  t j } n   d k  rWt j d |	  t j } n  t j |  t j |  } | rd d l m     f d	   }    f d
   } n: d d l m       f d   }     f d   } | j   } | d k r| |  } nb | d k r<d | } | |  } n= | d k rmd t j | |  | |   } n t d   | j |  | j |  qu Wt j | | f } n t d   | S(   s  
        Test for heteroskedasticity of standardized residuals

        Tests whether the sum-of-squares in the first third of the sample is
        significantly different than the sum-of-squares in the last third
        of the sample. Analogous to a Goldfeld-Quandt test. The null hypothesis
        is of no heteroskedasticity.

        Parameters
        ----------
        method : string {'breakvar'} or None
            The statistical test for heteroskedasticity. Must be 'breakvar'
            for test of a break in the variance. If None, an attempt is
            made to select an appropriate test.
        alternative : string, 'increasing', 'decreasing' or 'two-sided'
            This specifies the alternative for the p-value calculation. Default
            is two-sided.
        use_f : boolean, optional
            Whether or not to compare against the asymptotic distribution
            (chi-squared) or the approximate small-sample distribution (F).
            Default is True (i.e. default is to compare against an F
            distribution).

        Returns
        -------
        output : array
            An array with `(test_statistic, pvalue)` for each endogenous
            variable. The array is then sized `(k_endog, 2)`. If the method is
            called as `het = res.test_heteroskedasticity()`, then `het[0]` is
            an array of size 2 corresponding to the first endogenous variable,
            where `het[0][0]` is the test statistic, and `het[0][1]` is the
            p-value.

        Notes
        -----
        The null hypothesis is of no heteroskedasticity. That means different
        things depending on which alternative is selected:

        - Increasing: Null hypothesis is that the variance is not increasing
          throughout the sample; that the sum-of-squares in the later
          subsample is *not* greater than the sum-of-squares in the earlier
          subsample.
        - Decreasing: Null hypothesis is that the variance is not decreasing
          throughout the sample; that the sum-of-squares in the earlier
          subsample is *not* greater than the sum-of-squares in the later
          subsample.
        - Two-sided: Null hypothesis is that the variance is not changing
          throughout the sample. Both that the sum-of-squares in the earlier
          subsample is not greater than the sum-of-squares in the later
          subsample *and* that the sum-of-squares in the later subsample is
          not greater than the sum-of-squares in the earlier subsample.

        For :math:`h = [T/3]`, the test statistic is:

        .. math::

            H(h) = \sum_{t=T-h+1}^T  \tilde v_t^2
            \Bigg / \sum_{t=d+1}^{d+1+h} \tilde v_t^2

        where :math:`d` = max(loglikelihood_burn, nobs_diffuse)` (usually
        corresponding to diffuse initialization under either the approximate
        or exact approach).

        This statistic can be tested against an :math:`F(h,h)` distribution.
        Alternatively, :math:`h H(h)` is asymptotically distributed according
        to :math:`\chi_h^2`; this second test can be applied by passing
        `asymptotic=True` as an argument.

        See section 5.4 of [1]_ for the above formula and discussion, as well
        as additional details.

        TODO

        - Allow specification of :math:`h`

        References
        ----------
        .. [1] Harvey, Andrew C. 1990. *Forecasting, Structural Time Series*
               *Models and the Kalman Filter.* Cambridge University Press.
        t   breakvari   i   Nsg   Early subset of data for variable %d  has too few non-missing observations to calculate test statistic.sg   Later subset of data for variable %d  has too few non-missing observations to calculate test statistic.i    (   t   fc         ` s    j  |      S(   N(   t   cdf(   t   test_statistics(   t	   denom_dofRe  t	   numer_dof(    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   <lambda>  s   c         ` s    j  |      S(   N(   RU  (   Rg  (   Rh  Re  Ri  (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRj    s   (   t   chi2c         ` s     j   |    S(   N(   Rf  (   Rg  (   Rk  Rh  Ri  (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRj    s   c         ` s     j   |    S(   N(   RU  (   Rg  (   Rk  Rh  Ri  (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRj    s   R&   t   inct
   increasingR`  t   dect
   decreasingg      ?t   2s   2-sideds	   two-sideds   Invalid alternative.s'   Invalid heteroskedasticity test method.(   R&   Rl  Rm  (   R`  Rn  Ro  (   Rp  s   2-sideds	   two-sided(   RA   R  R   R<   R^  R\   R  R6   R   R  RF   t   intt   roundR_  R   R   R   R  R   t   scipy.statsRe  Rk  RJ  t   minimumRt   R   t   c_R   (   R9   Rg   t   alternativet   use_ft   squared_residR`  R  Rg  t   p_valuesR&   t   ht   numer_residt   denom_residt   test_statistict
   pval_lowert
   pval_uppert   p_valueRa  (    (   Rk  Rh  Re  Ri  sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   test_heteroskedasticity9  s`    R			
		c   	      C` s'  | d
 k r d } n  | d k s- | d k rd d l m } t j |  j |  j  } |  j | } g  } | d
 k r t d | d  } n  xz t	 |  j
 j  D]f } | |  j j | | d | d | d k } | d k r | j | d d ! q | j | d  q Wt j | } n t d	   | S(   s}  
        Ljung-box test for no serial correlation of standardized residuals

        Null hypothesis is no serial correlation.

        Parameters
        ----------
        method : string {'ljungbox','boxpierece'} or None
            The statistical test for serial correlation. If None, an attempt is
            made to select an appropriate test.
        lags : None, int or array_like
            If lags is an integer then this is taken to be the largest lag
            that is included, the test result is reported for all smaller lag
            length.
            If lags is a list or array, then all lags are included up to the
            largest lag in the list, however only the tests for the lags in the
            list are reported.
            If lags is None, then the default maxlag is 12*(nobs/100)^{1/4}

        Returns
        -------
        output : array
            An array with `(test_statistic, pvalue)` for each endogenous
            variable and each lag. The array is then sized
            `(k_endog, 2, lags)`. If the method is called as
            `ljungbox = res.test_serial_correlation()`, then `ljungbox[i]`
            holds the results of the Ljung-Box test (as would be returned by
            `statsmodels.stats.diagnostic.acorr_ljungbox`) for the `i` th
            endogenous variable.

        Notes
        -----
        Let `d` = max(loglikelihood_burn, nobs_diffuse); this test is
        calculated ignoring the first `d` residuals.

        Output is nan for any endogenous variable which has missing values.

        See Also
        --------
        statsmodels.stats.diagnostic.acorr_ljungbox

        t   ljungboxt	   boxpiercei    (   t   acorr_ljungboxi(   i   t   lagsi   s'   Invalid serial correlation test method.N(   RA   t   statsmodels.stats.diagnosticR  R<   R^  R\   R  R6   t   minR   R  RF   R  R   R   Ru  R   (	   R9   Rg   R  R  R`  R  Ra  R&   R!  (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   test_serial_correlation  s&    +	c   
      K` s   | d k r |  j j d } n  |  j j | | |  \ } } } } t | t t f  rv |  j j |  \ } } } n  |  j j	 | | | d | |  }	 t
 t |  |	 d |  S(   s  
        In-sample prediction and out-of-sample forecasting

        Parameters
        ----------
        start : int, str, or datetime, optional
            Zero-indexed observation number at which to start forecasting,
            i.e., the first forecast is start. Can also be a date string to
            parse or a datetime type. Default is the the zeroth observation.
        end : int, str, or datetime, optional
            Zero-indexed observation number at which to end forecasting, i.e.,
            the last forecast is end. Can also be a date string to
            parse or a datetime type. However, if the dates index does not
            have a fixed frequency, end must be an integer index if you
            want out of sample prediction. Default is the last observation in
            the sample.
        dynamic : boolean, int, str, or datetime, optional
            Integer offset relative to `start` at which to begin dynamic
            prediction. Can also be an absolute date string to parse or a
            datetime type (these are not interpreted as offsets).
            Prior to this observation, true endogenous values will be used for
            prediction; starting with this observation and continuing through
            the end of prediction, forecasted endogenous values will be used
            instead.
        **kwargs
            Additional arguments may required for forecasting beyond the end
            of the sample. See `FilterResults.predict` for more details.

        Returns
        -------
        forecast : array
            Array of out of in-sample predictions and / or out-of-sample
            forecasts. An (npredict x k_endog) array.
        i    i   t
   row_labelsN(   RA   R  t   _indext   _get_prediction_indexR   t   bytest   unicodet   _get_index_locR  t   predictt   PredictionResultsWrappert   PredictionResults(
   R9   t   startt   endt   dynamict   indexR#   t   out_of_samplet   prediction_indext   _t   prediction_results(    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   get_prediction"	  s    $$	i   c         K` sK   t  | t t f  r) |  j | d } n | } |  j d |  j d | |  S(   s  
        Out-of-sample forecasts

        Parameters
        ----------
        steps : int, str, or datetime, optional
            If an integer, the number of steps to forecast from the end of the
            sample. Can also be a date string to parse or a datetime type.
            However, if the dates index does not have a fixed frequency, steps
            must be an integer. Default
        **kwargs
            Additional arguments may required for forecasting beyond the end
            of the sample. See `FilterResults.predict` for more details.

        Returns
        -------
        forecast : array
            Array of out of sample forecasts. A (steps x k_endog) array.
        i   R  R  (   R   Rq  R   R6   R  (   R9   R   R#   R  (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   get_forecast[	  s    c         K` s   |  j  | | | |  } | j S(   s  
        In-sample prediction and out-of-sample forecasting

        Parameters
        ----------
        start : int, str, or datetime, optional
            Zero-indexed observation number at which to start forecasting,
            i.e., the first forecast is start. Can also be a date string to
            parse or a datetime type. Default is the the zeroth observation.
        end : int, str, or datetime, optional
            Zero-indexed observation number at which to end forecasting, i.e.,
            the last forecast is end. Can also be a date string to
            parse or a datetime type. However, if the dates index does not
            have a fixed frequency, end must be an integer index if you
            want out of sample prediction. Default is the last observation in
            the sample.
        dynamic : boolean, int, str, or datetime, optional
            Integer offset relative to `start` at which to begin dynamic
            prediction. Can also be an absolute date string to parse or a
            datetime type (these are not interpreted as offsets).
            Prior to this observation, true endogenous values will be used for
            prediction; starting with this observation and continuing through
            the end of prediction, forecasted endogenous values will be used
            instead.
        **kwargs
            Additional arguments may required for forecasting beyond the end
            of the sample. See `FilterResults.predict` for more details.

        Returns
        -------
        forecast : array
            Array of out of in-sample predictions and / or out-of-sample
            forecasts. An (npredict x k_endog) array.
        (   R  t   predicted_mean(   R9   R  R  R  R#   R  (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR  u	  s    $c         K` sK   t  | t t f  r) |  j | d } n | } |  j d |  j d | |  S(   s  
        Out-of-sample forecasts

        Parameters
        ----------
        steps : int, str, or datetime, optional
            If an integer, the number of steps to forecast from the end of the
            sample. Can also be a date string to parse or a datetime type.
            However, if the dates index does not have a fixed frequency, steps
            must be an integer. Default
        **kwargs
            Additional arguments may required for forecasting beyond the end
            of the sample. See `FilterResults.predict` for more details.

        Returns
        -------
        forecast : array
            Array of out of sample forecasts. A (steps x k_endog) array.
        i   R  R  (   R   Rq  R   R6   R  (   R9   R   R#   R  (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   forecast	  s    c      
   C` s\   |  j  j r |  j n d } |  j j j |  & |  j j |  j | | | |  } Wd QX| S(   s  
        Simulate a new time series following the state space model

        Parameters
        ----------
        nsimulations : int
            The number of observations to simulate. If the model is
            time-invariant this can be any number. If the model is
            time-varying, then this number must be less than or equal to the
            number
        measurement_shocks : array_like, optional
            If specified, these are the shocks to the measurement equation,
            :math:`\varepsilon_t`. If unspecified, these are automatically
            generated using a pseudo-random number generator. If specified,
            must be shaped `nsimulations` x `k_endog`, where `k_endog` is the
            same as in the state space model.
        state_shocks : array_like, optional
            If specified, these are the shocks to the state equation,
            :math:`\eta_t`. If unspecified, these are automatically
            generated using a pseudo-random number generator. If specified,
            must be shaped `nsimulations` x `k_posdef` where `k_posdef` is the
            same as in the state space model.
        initial_state : array_like, optional
            If specified, this is the state vector at time zero, which should
            be shaped (`k_states` x 1), where `k_states` is the same as in the
            state space model. If unspecified, but the model has been
            initialized, then that initialization is used. If unspecified and
            the model has not been initialized, then a vector of zeros is used.
            Note that this is not included in the returned `simulated_states`
            array.

        Returns
        -------
        simulated_obs : array
            An (nsimulations x k_endog) array of simulated observations.
        N(	   R  R  R   RA   R  RD   t   fixed_scaleR   Rz   (   R9   R   R   R   RU   R   t   sim(    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR   	  s    &i    c         K` s_   |  j  j r |  j n d } |  j j j |  ) |  j j |  j | | | | |  } Wd QX| S(   s  
        Impulse response function

        Parameters
        ----------
        steps : int, optional
            The number of steps for which impulse responses are calculated.
            Default is 1. Note that the initial impulse is not counted as a
            step, so if `steps=1`, the output will have 2 entries.
        impulse : int or array_like
            If an integer, the state innovation to pulse; must be between 0
            and `k_posdef-1`. Alternatively, a custom impulse vector may be
            provided; must be shaped `k_posdef x 1`.
        orthogonalized : boolean, optional
            Whether or not to perform impulse using orthogonalized innovations.
            Note that this will also affect custum `impulse` vectors. Default
            is False.
        cumulative : boolean, optional
            Whether or not to return cumulative impulse responses. Default is
            False.
        **kwargs
            If the model is time-varying and `steps` is greater than the number
            of observations, any of the state space representation matrices
            that are time-varying must have updated values provided for the
            out-of-sample steps.
            For example, if `design` is a time-varying component, `nobs` is 10,
            and `steps` is 15, a (`k_endog` x `k_states` x 5) matrix must be
            provided with the new design matrix values.

        Returns
        -------
        impulse_responses : array
            Responses for each endogenous variable due to the impulse
            given by the `impulse` argument. A (steps + 1 x k_endog) array.

        Notes
        -----
        Intercepts in the measurement and state equation are ignored when
        calculating impulse responses.

        N(	   R  R  R   RA   R  RD   R  R   Rz   (   R9   R   R   R   R   R#   R   R   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR   	  s    +i
   c         C` s  d d l  m } m } |   | | |  } t j |  j |  j  } |  j j | | d  f } | j	 d  }	 t
 |  j d  r |  j j d k	 r |  j j | j   }
 n t j t |   }
 |	 j |
 |  |	 j d |
 d |
 d d d |	 j |
 d |
 d  |	 j d	  | t j |  } | j	 d
  }	 y |	 j | d t d d Wn* t k
 r|	 j | d t d d n Xd d l m } m } | |  } d! d" f } t j | d | d  }
 |	 j |
 | |
  d d |	 j |
 | j |
  d d |	 j |  |	 j   |	 j d  | j	 d  }	 d d l m  } | | d d d |	 |	 j d  | j	 d  }	 d d l! m" } | | d |	 d | |	 j d   |	 j# d d  | S(#   s   
        Diagnostic plots for standardized residuals of one endogenous variable

        Parameters
        ----------
        variable : integer, optional
            Index of the endogenous variable for which the diagnostic plots
            should be created. Default is 0.
        lags : integer, optional
            Number of lags to include in the correlogram. Default is 10.
        fig : Matplotlib Figure instance, optional
            If given, subplots are created in this figure instead of in a new
            figure. Note that the 2x2 grid will be created in the provided
            figure using `fig.add_subplot()`.
        figsize : tuple, optional
            If a figure is created, this argument allows specifying a size.
            The tuple is (width, height).

        Notes
        -----
        Produces a 2x2 plot grid with the following plots (ordered clockwise
        from top left):

        1. Standardized residuals over time
        2. Histogram plus estimated density of standardized residulas, along
           with a Normal(0,1) density plotted for reference.
        3. Normal Q-Q plot, with Normal reference line.
        4. Correlogram

        See Also
        --------
        statsmodels.graphics.gofplots.qqplot
        statsmodels.graphics.tsaplots.plot_acf
        i    (   t   _import_mplt   create_mpl_figNi   R-   it   alphag      ?s   Standardized residuali   t   densityt   labelt   Histt   normed(   t   gaussian_kdeR   g\(\i   g\(\?i   t   KDEs   N(0,1)s    Histogram plus estimated densityi   (   t   qqplott   linet   st   axs
   Normal Q-Qi   (   t   plot_acfR  t   Correlogramg\(\g\(\@($   t   statsmodels.graphics.utilsR  R  R<   R^  R\   R  R  R   t   add_subplotR   R>   R-   RA   t	   _mpl_reprt   arangeR   t   plott   hlinest   set_xlimt	   set_titleR_  t   histRq   t   AttributeErrorRs  R  R   t   linspacet   pdft   legendt   statsmodels.graphics.gofplotsR  t   statsmodels.graphics.tsaplotsR  t   set_ylim(   R9   t   variableR  t   figt   figsizeR  R  R`  RY  R  t   xt   resid_nonmissingR  R   t   kdet   xlimR  R  (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   plot_diagnostics
  sL    #$!
g?c         C` s  d d l  m } |  j } | d$ k r. d } n  | d$ k rC d } n  |  j j r |  j j } | | }	 d |	 j |	 j |	 j f g }
 | d }	 |
 d d |	 j |	 j |	 j f g 7}
 n t	 |  d t	 |  j
  g }
 | d$ k r | j j } n  y |  j d d	  } Wn- t k
 r7t j t j g d
 g  } n Xy |  j d d  } Wn< t k
 rt j t j g d
 g  j d d
 d  } n Xy |  j d d  } Wn- t k
 rt j t j g d g  } n Xt | t  s| g } n  d7 g } | j d | d g f  x; t d t |   D]$ } | j d d | | g f  q'W| d8 d9 d |
 d g f d |
 d g f g 7} d |  j
 g f d d |  j g f g } t |  d  r| j d d |  j g f  n  | d d |  j g f d d |  j g f d d |  j g f g 7} |  j  d$ k	 rT|  j  j! rT| j d d |  j" g f  n  t |  d   r| j d! |  j# g f  n  d"   } d# | | d$ d$  d d f  f d% | | d$ d$  d d f  f d& | | d$ d$  d f  f d' | | d$ d$  d f  f g } d( | | d$ d$  d f  f d) | | d$ d$  d f  f d* | | d$ d$  d
 f  f d+ | | d$ d$  d, f  f g } |   } | j$ |  d- | d. | d/ | t |  j%  d k r| r| j& |  d0 | d1 |  j' j( d2 t) n  | j$ |  d- | d. | d/ d g  } t |  d   rWd3 |  j* k rW| j |  j* d3  n  |  j+ t |  j%  k  r| j d4 t j, j- |  j.     n  | rg  t/ |  D]" \ } } d5 j0 | d |  ^ q} | j1 d d6  | j2 |  n  | S(:   s  
        Summarize the Model

        Parameters
        ----------
        alpha : float, optional
            Significance level for the confidence intervals. Default is 0.05.
        start : int, optional
            Integer of the start observation. Default is 0.
        model_name : string
            The name of the model used. Default is to use model class name.

        Returns
        -------
        summary : Summary instance
            This holds the summary table and text, which can be printed or
            converted to various output formats.

        See Also
        --------
        statsmodels.iolib.summary.Summary
        i    (   t   Summarys   Statespace Model Resultss   %02d-%02d-%02dis   - s    - Rg   Rd  i   R  i   R[  i   s   Dep. Variable:s   Model:t    s   + s   Date:s   Time:s   Sample:s   No. Observations:s   Log Likelihoods   %#5.3ft   rsquareds
   R-squared:s   %#8.3ft   AICt   BICt   HQICt   ScaleRn   s   Covariance Type:c         S` s,   d j  g  |  D] } d j |  ^ q  g S(   Ns   , s   {0:.2f}(   t   joinR5  (   R=   R&   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyRj  
  s    s   Ljung-Box (Q):Ns   Prob(Q):s   Heteroskedasticity (H):s   Prob(H) (two-sided):s   Jarque-Bera (JB):s	   Prob(JB):s   Skew:s	   Kurtosis:i   t   gleftt   grightt   titleR  t   xnamet   use_tR&  sm   Covariance matrix is singular or near-singular, with condition number %6.3g. Standard errors may be unstable.s	   [{0}] {1}s	   Warnings:(   s   Dep. Variable:N(   s   Date:N(   s   Time:N(3   t   statsmodels.iolib.summaryR  R  RA   t   _index_datesR  t   montht   dayt   yeart   strR6   R2  R   R  t	   ExceptionR<   R=   R  R  t   reshapeRc  R   t   listR   R   R   R;  R   R  R   R   R   R  R  R   Rn   t   add_table_2colsRz   t   add_table_paramsR>   R   Rw   Ro   R  R   t   condRE  R   R5  t   insertt   add_extra_txt(   R9   R  R  R  t
   model_namet   display_paramsR  R  t   ixR`  t   samplet   hett   lbt   jbt   top_leftR&   t	   top_rightt
   format_strt
   diagn_leftt   diagn_rightt   summaryt   etextt   text(    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR  p
  s    			

* / 	"  	""%%		2N(*   R   R   R   RA   R2   R  R   R   R   Rq   Rw   R@  R4  RA  R6  RB  R7  RC  RF  R8  RG  R9  RR  RS  R   RT  R;  R\   RX  RY  RW  Rc  R  R  R  R  R  R  R   R   R  R  (    (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR     sZ    ^l						O			,K	8',	1[R   c           B` s   e  Z i d  d 6d d 6d d 6d d 6d d 6d d 6d d 6d d	 6Z e j e j j e  Z i d
 d 6d d 6d d 6Z e j e j j	 e  Z	 RS(   t   columnsRW  RQ  R4  R  R6  R7  RC  R9  R8  R-   R  t   ynamesR   R   (
   R   R   t   _attrst   wrapt   union_dictsR	  t   TimeSeriesResultsWrappert   _wrap_attrst   _methodst   _wrap_methods(    (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR   
  s"   
	
R  c           B` sJ   e  Z d  Z d	 d  Z e d    Z d d d  Z d d d d  Z RS(
   s*  

    Parameters
    ----------
    prediction_results : kalman_filter.PredictionResults instance
        Results object from prediction after fitting or filtering a state space
        model.
    row_labels : iterable
        Row labels for the predicted data.

    Attributes
    ----------

    c      	   C` sQ  | j  j d k rC t j | j d  d   d f d | j  j } n! t j | j j d | j  j } t d | j	 j
 d | d |   |  _  | |  _ |  j j } | j d d k r | d d  d   f } n | j   } |  j j } | j d d k r| d d d  d   f } n | j   } t t |   j | | d d	 d
 | d t   d  S(   Ni   i    R'   R  R>   R+   t   predict_datest   distR   R  t   link(   R  RF   t   pdt   SeriesR+   t   endog_namest	   DataFrameRC   R   R>   R2  R  R   R5   R   R   R1   R  R2   R   (   R9   R  R  R  R+   R  t   var_pred_mean(    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR2     s(    	c         C` sF   |  j  j d k r' t j |  j   } n t j |  j  j j    } | S(   Ni   (   R  RB   R<   t   sqrtRC   R  (   R9   t   se_mean(    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR  :  s    t   endpointg?c         K` s   t  t |   j | | |  } |  j d  k	 r t j | d |  j } |  j j j	 } t
 |  t k sr | g } n  g  | D] } d | ^ qy g  | D] } d | ^ q } | | _ n  | S(   NR  s   lower %ss   upper %s(   R1   R  t   conf_intR  RA   R  R   R  R>   R  t   typeR  R  (   R9   Rg   R  t   kwdsR  R  R'   R    (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR  B  s    i    t   allc   
      C` sA  d d l  m } t j |  j d |   } |   } |  j j d k rx |  j j j	 } |  j | d <|  j
 | d <d } n] |  j j j	 | } |  j d  d   | f | d <|  j
 d  d   | f | d <|  j j d } | d  d   | f | d <| d  d   | | f | d <t j | d	 |  j d
 | j   }	 | |	 j _ |	 S(   Ni    (   t   OrderedDictR  i   t   meant   mean_set   mean_ci_lowert   mean_ci_upperR  R  (   t   collectionsR	  R<   t   asarrayR  R  RB   R  R>   R  R  R5   R  R   R  t   keysR  R'   (
   R9   R+   t   whatR  R	  t   ci_meant
   to_includet   ynameRF   R   (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   summary_frameW  s$    		N(	   R   R   R   RA   R2   R   R  R  R  (    (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR    s
   R  c           B` sG   e  Z i d  d 6d  d 6d  d 6Z e j e  Z i  Z e j e  Z RS(   R-   R  R  t   t_values(   R   R   R  R  R  R  R  R  (    (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyR  u  s   
(@   R   t
   __future__R    R   R   R   t   numpyR<   t   pandasR  Rs  R   t   statsmodels.compat.pythonR   t   statsmodels.tools.toolsR   R   t   statsmodels.tools.sm_exceptionsR   t   statsmodels.tools.numdiffR   R	   R
   R   t   statsmodels.tools.decoratorsR   t   statsmodels.tools.eval_measuresR   R   R   t   statsmodels.base.wrappert   baset   wrapperR  t   statsmodels.genmod._predictiont   genmodt   _predictiont   predt!   statsmodels.genmod.families.linksR   t   statsmodels.tsa.base.tsa_modelt   tsat	   tsa_modelR	  R   R   t   kalman_smootherR   t   kalman_filterR   R   R  R  R  R)   t   TimeSeriesModelR*   R
  R   t   ResultsWrapperR   t   populate_wrapperR  R  (    (    (    sB   lib/python2.7/site-packages/statsmodels/tsa/statespace/mlemodel.pyt   <module>   sL   "		          h
