U
    KvfD                     @   s
  d Z ddlZddlmZ ddlZddlZddlm	Z	 ddl
mZ ddlmZ ddlmZ ddlm  mZ ddlmZ d	d
lmZmZ d	dlmZmZmZ d	dlmZ d	dlm Z m!Z!m"Z"m#Z#m$Z$m%Z%m&Z& G dd deZ'G dd deZ(G dd deZ)e*e)e( dS )zs
Vector Autoregressive Moving Average with eXogenous regressors model

Author: Chad Fulton
License: Simplified-BSD
    N)warn)Appender)Bunch)_is_using_pandas)	var_model)EstimationWarning   )INVERT_UNIVARIATESOLVE_LU)MLEModel
MLEResultsMLEResultsWrapper)Initialization)is_invertibleconcatprepare_exog!constrain_stationary_multivariate#unconstrain_stationary_multivariateprepare_trend_specprepare_trend_datac                       s   e Zd ZdZd fd	d
	Zd ddZedd Zedd Zedd Z	dd Z
dd Z fddZd!ddZejdd Zeejjd" fdd	Z  ZS )#VARMAXuM  
    Vector Autoregressive Moving Average with eXogenous regressors model

    Parameters
    ----------
    endog : array_like
        The observed time-series process :math:`y`, , shaped nobs x k_endog.
    exog : array_like, optional
        Array of exogenous regressors, shaped nobs x k.
    order : iterable
        The (p,q) order of the model for the number of AR and MA parameters to
        use.
    trend : str{'n','c','t','ct'} or iterable, optional
        Parameter controlling the deterministic trend polynomial :math:`A(t)`.
        Can be specified as a string where 'c' indicates a constant (i.e. a
        degree zero component of the trend polynomial), 't' indicates a
        linear trend with time, and 'ct' is both. Can also be specified as an
        iterable defining the non-zero polynomial exponents to include, in
        increasing order. For example, `[1,1,0,1]` denotes
        :math:`a + bt + ct^3`. Default is a constant trend component.
    error_cov_type : {'diagonal', 'unstructured'}, optional
        The structure of the covariance matrix of the error term, where
        "unstructured" puts no restrictions on the matrix and "diagonal"
        requires it to be a diagonal matrix (uncorrelated errors). Default is
        "unstructured".
    measurement_error : bool, optional
        Whether or not to assume the endogenous observations `endog` were
        measured with error. Default is False.
    enforce_stationarity : bool, optional
        Whether or not to transform the AR parameters to enforce stationarity
        in the autoregressive component of the model. Default is True.
    enforce_invertibility : bool, optional
        Whether or not to transform the MA parameters to enforce invertibility
        in the moving average component of the model. Default is True.
    trend_offset : int, optional
        The offset at which to start time trend values. Default is 1, so that
        if `trend='t'` the trend is equal to 1, 2, ..., nobs. Typically is only
        set when the model created by extending a previous dataset.
    **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
    ----------
    order : iterable
        The (p,q) order of the model for the number of AR and MA parameters to
        use.
    trend : str{'n','c','t','ct'} or iterable
        Parameter controlling the deterministic trend polynomial :math:`A(t)`.
        Can be specified as a string where 'c' indicates a constant (i.e. a
        degree zero component of the trend polynomial), 't' indicates a
        linear trend with time, and 'ct' is both. Can also be specified as an
        iterable defining the non-zero polynomial exponents to include, in
        increasing order. For example, `[1,1,0,1]` denotes
        :math:`a + bt + ct^3`.
    error_cov_type : {'diagonal', 'unstructured'}, optional
        The structure of the covariance matrix of the error term, where
        "unstructured" puts no restrictions on the matrix and "diagonal"
        requires it to be a diagonal matrix (uncorrelated errors). Default is
        "unstructured".
    measurement_error : bool, optional
        Whether or not to assume the endogenous observations `endog` were
        measured with error. Default is False.
    enforce_stationarity : bool, optional
        Whether or not to transform the AR parameters to enforce stationarity
        in the autoregressive component of the model. Default is True.
    enforce_invertibility : bool, optional
        Whether or not to transform the MA parameters to enforce invertibility
        in the moving average component of the model. Default is True.

    Notes
    -----
    Generically, the VARMAX model is specified (see for example chapter 18 of
    [1]_):

    .. math::

        y_t = A(t) + A_1 y_{t-1} + \dots + A_p y_{t-p} + B x_t + \epsilon_t +
        M_1 \epsilon_{t-1} + \dots M_q \epsilon_{t-q}

    where :math:`\epsilon_t \sim N(0, \Omega)`, and where :math:`y_t` is a
    `k_endog x 1` vector. Additionally, this model allows considering the case
    where the variables are measured with error.

    Note that in the full VARMA(p,q) case there is a fundamental identification
    problem in that the coefficient matrices :math:`\{A_i, M_j\}` are not
    generally unique, meaning that for a given time series process there may
    be multiple sets of matrices that equivalently represent it. See Chapter 12
    of [1]_ for more information. Although this class can be used to estimate
    VARMA(p,q) models, a warning is issued to remind users that no steps have
    been taken to ensure identification in this case.

    References
    ----------
    .. [1] Lütkepohl, Helmut. 2007.
       New Introduction to Multiple Time Series Analysis.
       Berlin: Springer.
    Nr   r   cunstructuredFTr   c
                    s>  | _ | _| _| _| _t|d  _t|d  _|dkrJtd jdkrf jdkrftd jdkr jdkrt	dt
 | _|	 _t j\ _ _ jjdko jd dk _t|\ _} jdk _t|d st|}t jd}| j  _|jd }|}| j }|
dd |
d	ttB  tt j |f|||d
|
  jdksx jdkr jsd j!_"i  _# j$ j  j#d<  j$d  j  j#d<  j$d  j  j#d<  j$ j  j#d<  j dkr j$ j#d< n* j dkrt j$ j$d  d  j#d<  j$ j  j#d< t% j#&  _'t( j j j)d  jd}|d d  _*|dd   _+ jdkr jr jdkrt, j- j)f j!d< t. j$}d j!d| <  jdkrt. jd  j$ }|d  j$ |d f}d j!d| < t. jd  j$ }|d |d  j$  |d | j$  f}d j!d| < t. j$}d j!d| < |d | j$  |d f} jdkrd j!d| <  jrֈ jdkrtj/dd |d d f  _0n2 jdks jdkrtj/dd |d df  _0 jdkr0tj/dd |d d f  _1ntj/dd ||d f  _1 j dkrjdt. j$  _2n j dkrt3 j$ _4 jrdt. j$  _5 fdd}d}|d|\ _6}|d|\ _7}|d|\ _8}|d|\ _9}|d|\ _:}|d|\ _;}d  _<  j=d dd!d"d#d$gt>|
?  7  _=d S )%Nr   r   )diagonalr   z3Invalid error covariance matrix type specification.zNInvalid VARMAX(p,q) specification; at least one p,q must be greater than zero.zcEstimation of VARMA(p,q) models is not generically robust, due especially to identification issues.initialization
stationaryZinversion_method)exogk_statesk_posdefFtrend   armaZ
regressionr   	state_covr   obs_cov)offsetstate_intercept)Zdesign)
transition)Z	selectionr)   )r$   )r%   c                    s,    j |  }tj|||  }||7 }||fS )N)
parametersnps_)keyr&   lengthZparam_sliceself E/tmp/pip-unpacked-wheel-2v6byqio/statsmodels/tsa/statespace/varmax.py_slice!  s    
zVARMAX.__init__.<locals>._sliceordererror_cov_typemeasurement_errorenforce_stationarityenforce_invertibility)@r5   r6   r7   r8   r4   intk_ark_ma
ValueErrorr   r   r    trend_offsetr   polynomial_trendk_trendsize_trend_is_constr   k_exogmle_regressionr   r+   Z
asanyarraymaxZ_k_ordershape
setdefaultr	   r
   superr   __init__ssmZ_time_invariantr*   k_endogsumvaluesk_paramsr   nobs_trend_data_final_trendzerosr   Zdiag_indicesr,   _idx_state_intercept_idx_transition_idx_state_covZtril_indices_idx_lower_state_cov_idx_obs_cov_params_trend
_params_ar
_params_ma_params_regression_params_state_cov_params_obs_cov_final_exogZ
_init_keyslistkeys)r0   endogr   r4   r    r5   r6   r7   r8   r=   kwargsZ	_min_k_arrJ   r   r   Z
trend_dataidxr3   r&   	__class__r/   r2   rH      s    




       
zVARMAX.__init__c                 K   s   | j |fd|i|S )Nr   )Z_clone_from_init_kwds)r0   r`   r   ra   r1   r1   r2   clone8  s    zVARMAX.clonec                 C   s   dt tfiS )Nfit)VARMAXResultsVARMAXResultsWrapperr/   r1   r1   r2   _res_classes;  s    zVARMAX._res_classesc                 C   s  t j| jt jd}t| j }| }t j	|
 dd}d }| jdkrh| jdkrht j| j| jf }n"| jdkrz| j}n| jdkr| j}t t |rt jt |dd }|| }|d k	r|| }t d}t d}| jdks| jdkrLt j||}|t ||8 }| jdkr0|d | j j}| jdkrL|| jd  j}g }| jdkrb| jnd}	t|}
|
j|	d dd}| jdkrt |jj }|j}| jdkr| jr| | j| j | jj | j| j| jj}t!dgt"|  }|st#d	 |d9 }g }| j$dkrt|}|j| j$d dd}t |jj }| j%r| | j| j$ | jj | j| j| j$j}t!dgt"|  }|st#d
 |d9 }| jdkr:| jdks| j&r:| | j| j | jj | j| j| jj}t '| jt j(|dd }| jdkr"t ||}| j&dkr:t ||}| jdkrT| || j)< | jdkrj||| j*< | j$dkr||| j+< | j&r| || j,< | j-dkr|j./ || j0< n.| j-dkrt j1|j.}|| j2  || j0< | j3r| j$dkr|j./ || j4< n|j./ || j4< |S )NdtypeW)requirementsr   r   )Zaxisn)ZmaxlagsZicr    z\Non-stationary starting autoregressive parameters found. Using zeros as starting parameters.z\Non-stationary starting moving-average parameters found. Using zeros as starting parameters.r   r   )5r+   rQ   rM   Zfloat64pdZ	DataFramer`   copyZinterpolaterequireZbfillr?   rB   c_rO   r   anyisnanZlinalgZpinvdotTrJ   r:   r   VARrf   arrayparamsravelZresidr7   reshaper   r^   r   r;   r8   rC   eyerK   rW   rX   rY   rZ   r5   Zsigma_ur   r[   ZcholeskyrU   r6   r\   )r0   ry   r`   r   masktrend_paramsexog_paramsZtrendexog_params	ar_paramsr:   Zmod_arZres_arcoefficient_matricesr   	ma_paramsZmod_maZres_maZ
invertibletmpZ
cov_factorr1   r1   r2   start_params?  s    





   

    
   

zVARMAX.start_paramsc                    sl  g }j  tj ts g jdkrtjD ]f}j d D ]R}|dkrb|d |  g7 }qB|dkr~|d |  g7 }qB|d| | f g7 }qBq0| fddtjD 7 }| fddtjD 7 }| fd	dtjD 7 }jd
kr| fddtjD 7 }n(jdkrD| fddtjD 7 }j	rh| fddtjD 7 }|S )Nr   zintercept.%sr   zdrift.%sztrend.%d.%sc              	      sF   g | ]>}t jD ].}t jD ]}d |d  |  | f q qqS )z	L%d.%s.%sr   )ranger:   rJ   .0jikendog_namesr0   r1   r2   
<listcomp>  s     z&VARMAX.param_names.<locals>.<listcomp>c              	      sF   g | ]>}t jD ].}t jD ]}d |d  |  | f q qqS )zL%d.e(%s).%sr   )r   r;   rJ   r   r   r1   r2   r     s     c                    s2   g | ]*}t jD ]}d j|  | f qqS )z
beta.%s.%s)r   rB   Z
exog_namesr   r   r   r   r1   r2   r     s    r   c                    s   g | ]}d  |  qS )z	sigma2.%sr1   r   r   r   r1   r2   r     s   r   c                    sF   g | ]>}t |d  D ],}||kr,d |  nd |  | f qqS )r   zsqrt.var.%szsqrt.cov.%s.%s)r   r   r   r1   r2   r     s
    c                    s   g | ]}d  |  qS )zmeasurement_variance.%sr1   r   r   r1   r2   r     s   )
r   
isinstancer^   r?   r   rJ   r>   Znonzeror5   r6   )r0   param_namesr   r   r1   r   r2   r     sD    

zVARMAX.param_namesc                 C   s  t j|dd}t j|j|jd}|| j || j< | jdkr| jr| jdkr`t 	|| j
 d }n@| jdkrt j| jd j|jd}|| j
 || j< t ||j}|| j | j| j| j }t||\}}| || j< n|| j || j< | jdkrJ| jrJt j| j|jd}|| j | j| j| j }t||\}}| || j< n|| j || j< || j || j< | jdkr|| j
 d || j
< n| jdkr|| j
 || j
< | jr|| j d || j< |S )	a[  
        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
            evaluation.

        Notes
        -----
        Constrains the factor transition to be stationary and variances to be
        positive.
        r   Zndminrj   r   r   r!   r   r$   )r+   rx   rQ   rE   rk   rW   r:   r7   r5   diagr[   rI   rU   ru   rv   rX   r{   rJ   r   rz   r;   r8   r|   rY   rZ   r6   r\   )r0   unconstrainedconstrainedr$   state_cov_lowercoefficientsr   variancer1   r1   r2   transform_params   sV    


 

 

zVARMAX.transform_paramsc                 C   s  t j|dd}t j|j|jd}|| j || j< | jdkr| jr| jdkr\t 	|| j
 }n@| jdkrt j| jd j|jd}|| j
 || j< t ||j}|| j | j| j| j }t||\}}| || j< n|| j || j< | jdkrF| jrFt j| j|jd}|| j | j| j| j }t||\}}| || j< n|| j || j< || j || j< | jdkr|| j
 d || j
< n| jdkr|| j
 || j
< | jr|| j d || j< |S )	a  
        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 evaluation, to
            be transformed.

        Returns
        -------
        unconstrained : array_like
            Array of unconstrained parameters used by the optimizer.
        r   r   rj   r   r   r   r$   g      ?)r+   rx   rQ   rE   rk   rW   r:   r7   r5   r   r[   rI   rU   ru   rv   rX   r{   rJ   r   rz   r;   r8   r|   rY   rZ   r6   r\   )r0   r   r   r$   r   r   Zunconstrained_matricesr   r1   r1   r2   untransform_paramsS  sV    


 

 

zVARMAX.untransform_paramsc                    s   t t| | tt| j d d }dd t| j	|D \}}}}}}| j
r| jdkr| jdkst| jdkr||}t||dk}|r|std| jr| jdkr| js| jdkr||}t||dk}|r|stdd S )Nr'   c                 S   s   g | ]}|  qS r1   )tolist)r   Zarrr1   r1   r2   r     s    z3VARMAX._validate_can_fix_params.<locals>.<listcomp>r   r   zCannot fix individual autoregressive parameters when `enforce_stationarity=True`. In this case, must either fix all autoregressive parameters or none.zCannot fix individual moving average parameters when `enforce_invertibility=True`. In this case, must either fix all moving average parameters or none.)rG   r   _validate_can_fix_paramsr+   Zcumsumr^   r*   rL   Zarray_splitr   r7   r:   rJ   
issupersetlenintersectionr<   r8   r;   )r0   r   ix_Zar_namesZma_namesZfix_allZfix_anyrc   r1   r2   r     s.    

zVARMAX._validate_can_fix_paramsc                 C   s\  | j |||d}| jr||| j | j| jj}t| j	dd  |}|j| j
| j< | jd k	r|t| j|| j
dd | jdf< | jdkrL| jstjd|jd}|| j
dd d f< || j | j| jj}| jr|}nt| jdd  |}| j
| j  |j7  < | jd k	rL| jd jdkrL| j
dd | jdd f  t| j|j7  < | jr| jd krtjtj|jd}	|	| j
dd | jdf< || j | j| j| j }
|| j | j| j| j }tj|
|f | j
| j< | jdkr|| j | j
| j< nH| jdkr>tj| j
d	 j |jd}|| j || j!< t||j| j
d	< | j"rX|| j# | j
| j$< d S )
N)transformedincludes_fixedr   r(   r'   r   rj   r   r   r$   )%Zhandle_paramsrC   rZ   r{   rJ   rB   rv   r+   ru   r   rI   rR   r]   r?   rx   rk   rW   rA   rO   rP   stopnanrX   r:   rY   r;   rr   rS   r5   r[   rT   rQ   rE   rU   r6   r\   rV   )r0   ry   r   r   Zcomplex_stepr   	interceptZzeror~   r   r"   r#   r   r1   r1   r2   update  st    
 
 
  

 

 
zVARMAX.updatec                 c   s   | j }| jdkr|dk	rt|}|jdkr8|dd }zt|dd | jf}W n2 tk
r   tdt| jft|jf Y nX || _ z
dV  W 5 || _ X dS )a8  
        Set the final state intercept value using out-of-sample `exog` / trend

        Parameters
        ----------
        exog : ndarray
            Out-of-sample `exog` values, usually produced by
            `_validate_out_of_sample_exog` to ensure the correct shape (this
            method does not do any additional validation of its own).
        out_of_sample : int
            Number of out-of-sample periods.

        Notes
        -----
        We need special handling for simulating or forecasting with `exog` or
        trend, because if we had these then the last predicted_state has been
        set to NaN since we did not have the appropriate `exog` to create it.
        Since we handle trend in the same way as `exog`, we still have this
        issue when only trend is used without `exog`.
        r   Nr!   r   zPProvided exogenous values are not of the appropriate shape. Required %s, got %s.)	r]   rB   r+   Z
atleast_1dndimr{   r<   strrE   )r0   r   cache_valuer1   r1   r2   _set_final_exog  s$    




zVARMAX._set_final_exogc                    sJ   |  |6 tt| j||f|||||||	|
||d
|}W 5 Q R X |S )N)
measurement_shocksstate_shocksinitial_stateanchorrepetitionsr   extend_modelextend_kwargsr   r   )r   rG   r   simulate)r0   ry   nsimulationsr   r   r   r   r   r   r   r   r   r   ra   outrc   r1   r2   r   *  s&    
      zVARMAX.simulate)Nr   r   r   FTTr   )N)TFF)
NNNNNNNNTF)__name__
__module____qualname____doc__rH   re   propertyri   r   r   r   r   r   r   
contextlibcontextmanagerr   r   r   r   __classcell__r1   r1   rc   r2   r       sJ   d         4


 
?SM  
C
(
                r   c                	       s   e Zd ZdZd fdd	ZdddZejdd Zejd	d
 Z	e
ejjd fdd	Ze
ejjd fdd	ZdddZe
ejjd fdd	Z  ZS )rg   a  
    Class to hold results from fitting an VARMAX model.

    Parameters
    ----------
    model : VARMAX instance
        The fitted model instance

    Attributes
    ----------
    specification : dictionary
        Dictionary including all attributes from the VARMAX model instance.
    coefficient_matrices_var : ndarray
        Array containing autoregressive lag polynomial coefficient matrices,
        ordered from lowest degree to highest.
    coefficient_matrices_vma : ndarray
        Array containing moving average lag polynomial coefficients,
        ordered from lowest degree to highest.

    See Also
    --------
    statsmodels.tsa.statespace.kalman_filter.FilterResults
    statsmodels.tsa.statespace.mlemodel.MLEResults
    Nc                    s  t t| j|||||f| tf | jj| jj| jj| jj| jj	| jj
| jj| jj| jj| jj| jjd| _d | _d | _| jjdkrt| j| jj }| jj}| jj}	|||	 |j|||	j| _| jjdkrt| j| jj }
| jj}| jj}|
|| |j|||j| _d S )N)r5   r6   r7   r8   r=   r4   r:   r;   r    r?   rB   r   )rG   rg   rH   r   modelr5   r6   r7   r8   r=   r4   r:   r;   r    r?   rB   specificationZcoefficient_matrices_varZcoefficient_matrices_vmar+   rx   ry   rX   rJ   r{   rv   rY   )r0   r   ry   filter_resultsZcov_typeZcov_kwdsra   r   rJ   r:   r   r;   rc   r1   r2   rH   T  sR     
    zVARMAXResults.__init__c           
      K   s   |d k	r@| j | j| j|d d d}|j}|jd }|jd }n| jd }| jd }|d| j| jj  | jj|fd|i|}t	|j
d||d|j_| jd k	r|| j}	n|| j}	|	S )	Nr   )r   ).r   ).r'   r=   r   Zknownconstantstationary_cov)get_predictionrN   Zprediction_resultspredicted_statepredicted_state_covrF   r   r=   re   r   r   rI   r   smoother_resultsZsmoothry   filter)
r0   r`   r   ra   ZfcastZfcast_resultsr   Zinitial_state_covmodresr1   r1   r2   extend  s&    


  

zVARMAXResults.extendc                 c   s   | j }||n | jjdddf }|| j |dd|jdf | jjd|jdf< z
dV  W 5 || jjdddf< X W 5 Q R X dS )az  
        Set the final state intercept value using out-of-sample `exog` / trend

        Parameters
        ----------
        exog : ndarray
            Out-of-sample `exog` values, usually produced by
            `_validate_out_of_sample_exog` to ensure the correct shape (this
            method does not do any additional validation of its own).
        out_of_sample : int
            Number of out-of-sample periods.

        Notes
        -----
        This context manager calls the model-level context manager and
        additionally updates the last element of filter_results.state_intercept
        appropriately.
        Nr'   r(   )r   r   r   r(   r   ry   rJ   )r0   r   r   r   r1   r1   r2   r     s    
zVARMAXResults._set_final_exogc              
   c   s4  |o| j jdk}|rt| j jdd td| j jfg}| j jdkrjt| j jdd |dd g}nd}| j j| j	 d }| j j
|||d}| jjdddf }| jjdddddf }	|jj||	d |j| jdddd	}
|
jdddf | jjdddf< z
dV  W 5 |r.tj| jjdddf< X dS )
a  
        Set the final predicted state value using out-of-sample `exog` / trend

        Parameters
        ----------
        exog : ndarray
            Out-of-sample `exog` values, usually produced by
            `_validate_out_of_sample_exog` to ensure the correct shape (this
            method does not do any additional validation of its own).
        out_of_sample : int
            Number of out-of-sample periods.

        Notes
        -----
        We need special handling for forecasting with `exog`, because
        if we had these then the last predicted_state has been set to NaN since
        we did not have the appropriate `exog` to create it.
        r   r'   Nr   )r   r=   r   T)r   r   Z
return_ssm)r   rB   r   r`   r+   rQ   rJ   r   r=   rN   re   r   r   r   rI   Zinitialize_knownr   ry   r   )r0   r   out_of_sampleflagZ	tmp_endogZtmp_exogZtmp_trend_offsetZtmp_modr   r   Ztmp_resr1   r1   r2   _set_final_predicted_state  s8     "

 
z(VARMAXResults._set_final_predicted_stateF	predictedc                    s   |d krd}| j j|||dd\}}	}
}| j ||
}i }| j jdkrX| j j| j |d< | |D | ||
, tt	| j
f |||||||d|}W 5 Q R X W 5 Q R X |S )Nr   T)Zsilentr=   )startenddynamicinformation_setindexr   r   )r   Z_get_prediction_index_validate_out_of_sample_exogr?   r=   rN   r   r   rG   rg   r   )r0   r   r   r   r   r   r   ra   _startZ_endr   r   r   r   rc   r1   r2   r     s.    
    zVARMAXResults.get_predictionc
                    s   |d ks|dkrd}n"|dkr&| j }n| j|\}}}|dk rJ| j | }|| j kr\tdt|| | j  d}| j||}| ||0 tt| j	|f||||||||	d|
}W 5 Q R X |S )Nr   r   r   z4Cannot anchor simulation after the estimated sample.)r   r   r   r   r   r   r   r   )
rN   r   Z_get_index_locr<   rD   r   r   rG   rg   r   )r0   r   r   r   r   r   r   r   r   r   ra   Zilocr   r   r   rc   r1   r2   r     s6    


    zVARMAXResults.simulatec              	   C   s   d }| j |j  }| jjdkr6|dkr6| jj| d  }t B}	|	|j| |	||| | j	j
|j	||||d}
W 5 Q R X |
S )Nr   )r   r   revisions_details_startstate_index)rN   r   rB   r   r   	ExitStackenter_contextr   r   r   news)r0   previousr   r   Zperiodsr   r   r   r   stackr   r1   r1   r2   _news_previous_results(  s$    
   z$VARMAXResults._news_previous_results皙?Tc              	      sl  ddl m | j}|jdkr<|jdkr<d}d|j|jf }n(|jdkrVd}d|j }nd}d|j }|jdkrv|d7 }|| g}|jdkr|d	 |jr|d
 t	t
| j ||| d}|rhtt| j}d fdd	}	| jj}
| jj}| jj}| jj}| jj}g }t|
D ]}g }d}|dkrX|t|||
|  |
 ||
| 7 }|dkr||
 | }|d |
 | }||t||  |||
d  7 }|dkr||
 | }|d |
 | }||t||  |||
d  7 }|dkr(||t|| |d |   ||
| 7 }| jjrR|tj| jj| d dd t|}|| | jj}t|ts|g}d||  }|	| ||}|j| qtt| j| jj }|	| |ddd}|j| g }||gfD ],}t| }t|dkr|| qt|}ttt|t|}t|dkrh|	| |ddd}|j| |S )Nr   )summary_paramsZVARMAz(%s,%s)rw   z(%s)ZVMAXr   zmeasurement error)alphar   
model_nameZdisplay_paramsTc                    s   | | j | | j| | j| | j| |  | f}g }t| jj| 	 D ]B}|rnd
|dd d }n|}|| jkrd| }|| qL|d | d|dS )N.r'   z
%s (fixed)F)ZynameZxnamer   Zuse_ttitle)ry   ZbseZzvaluesZpvaluesZconf_intr+   rx   datar   r   joinsplitZfixed_paramsappend)r0   r}   r   	strip_endr   r   name
param_namer   r   r1   r2   
make_tablef  s$     
  z)VARMAXResults.summary.<locals>.make_tabler   r!   r   zResults for equation %szError covariance matrixF)r   zOther parameters)T)Zstatsmodels.iolib.summaryr   r   r:   r;   rB   r?   r   r6   rG   rg   summaryr+   Zaranger   ry   r   rJ   r   rx   rM   Zconcatenater   r   r^   Ztablesr[   flattenset
difference)r0   r   r   Zseparate_paramsspecr   r4   r   indicesr   rJ   r:   r;   r?   rB   Zendog_masksr   masksr&   r   r}   r   r   tableZstate_cov_maskmZinverse_maskrc   r   r2   r   E  s    







  







zVARMAXResults.summary)NN)N)NNFr   NN)NNNNNNNN)FN)r   NT)r   r   r   r   rH   r   r   r   r   r   r   r   r   r   r   r   r   r1   r1   rc   r2   rg   ;  s<     +


0
      
            !  

rg   c                   @   s0   e Zd Zi ZeejeZi Zeej	eZ	dS )rh   N)
r   r   r   _attrswrapZunion_dictsr   Z_wrap_attrsZ_methodsZ_wrap_methodsr1   r1   r1   r2   rh     s   rh   )+r   r   warningsr   Zpandasro   Znumpyr+   Zstatsmodels.compat.pandasr   Zstatsmodels.tools.toolsr   Zstatsmodels.tools.datar   Zstatsmodels.tsa.vector_arr   Zstatsmodels.base.wrapperbasewrapperr   Zstatsmodels.tools.sm_exceptionsr   Zkalman_filterr	   r
   Zmlemodelr   r   r   r   r   Ztoolsr   r   r   r   r   r   r   r   rg   rh   Zpopulate_wrapperr1   r1   r1   r2   <module>   s6   $      !   