U
    Kvf`_                     @   s   d Z ddl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  m  mZ ddlm  m  mZ ejZG dd dZG dd deZdS )z
Impulse reponse-related code
    N)cache_readonlyc                   @   sz   e Zd ZdZdddZdddZd	d
 Zdd ZdddddddddddddddZdddddddddddd
ddZ	dS )BaseIRAnalysisz
    Base class for plotting and computing IRF-related statistics, want to be
    able to handle known and estimated processes
    N
   Fc                 C   s  || _ || _|j|j|j  | _| _| _|| _|d krF|j}t	
|}|| _|| _||| _|rt|j||d| _n|j||d| _| jjdd| _|r| jjdd| _n| jjdd| _|s| | _|rt| || _nt| || _|rt|j| _ nt|j!| _ d S )N)Pr   Zaxis)"modelperiodsneqsZk_arZnobslagsTorderZsigma_ulaZcholeskyr   svarZma_repirfsZsvar_ma_rep	svar_irfsZorth_ma_rep	orth_irfsZcumsumcum_effectsZsvar_cum_effectsorth_cum_effectsZlong_run_effects
lr_effectsnpdotZsvar_lr_effectsorth_lr_effectsutilZcomp_matrixZvar_rep_AZcoefs)selfr   r   r   r   r   vecmsigma r   A/tmp/pip-unpacked-wheel-2v6byqio/statsmodels/tsa/vector_ar/irf.py__init__   s2    


zBaseIRAnalysis.__init__c                 C   s   |r
| j S |r| jS | jS d S N)r   r   r   )r   orthr   r   r   r   _choose_irfsK   s
    zBaseIRAnalysis._choose_irfsc                 O   s   t d S r    NotImplementedErrorr   argskwargsr   r   r   covS   s    zBaseIRAnalysis.covc                 O   s   t d S r    r#   r%   r   r   r   cum_effect_covV   s    zBaseIRAnalysis.cum_effect_cov皙?)r   r   Tasym  )impulseresponsesignifplot_paramsfigsizesubplot_paramsplot_stderrstderr_typereplseed	componentc                C   s  | j }| j}| j}|r"|r"td| ||}|r8d}n|rBd}nd}|dkrTd}n|	dkrftdn|	d	krz| j|d
}|	dkr| j|||
||d}|	dkr| j|||
|||d}|	dkr| j|||
|||d}|	dkr| j	|||
|||d}t
j||||| jj||||||	d}|S )a  
        Plot impulse responses

        Parameters
        ----------
        orth : bool, default False
            Compute orthogonalized impulse responses
        impulse : {str, int}
            variable providing the impulse
        response : {str, int}
            variable affected by the impulse
        signif : float (0 < signif < 1)
            Significance level for error bars, defaults to 95% CI
        subplot_params : dict
            To pass to subplot plotting funcions. Example: if fonts are too big,
            pass {'fontsize' : 8} or some number to your taste.
        plot_params : dict

        figsize : (float, float), default (10, 10)
            Figure size (width, height in inches)
        plot_stderr : bool, default True
            Plot standard impulse response error bands
        stderr_type : str
            'asym': default, computes asymptotic standard errors
            'mc': monte carlo standard errors (use rpl)
        repl : int, default 1000
            Number of replications for Monte Carlo and Sims-Zha standard errors
        seed : int
            np.random.seed for Monte Carlo replications
        component: array or vector of principal component indices
        zFor SVAR system, set orth=Falsez"Impulse responses (orthogonalized)zImpulse responses (structural)zImpulse responsesFN)r+   mcsz1sz2sz3z<Error type must be either 'asym', 'mc','sz1','sz2', or 'sz3'r+   r!   r8   )r!   r   r5   r/   r6   r9   )r!   r   r5   r/   r6   r7   r:   r;   )r/   r2   r0   r1   r4   )r   r   r   
ValueErrorr"   r(   
errband_mcerr_band_sz1err_band_sz2err_band_sz3plottingirf_grid_plotnames)r   r!   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   r   r   r   r   titlestderrfigr   r   r   plotY   sl    #
      zBaseIRAnalysis.plot)
r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   c       
         C   s   |rd}| j }| j}nd}| j}| j}|	dkr8tdn.|	dkrL| j|d}|	dkrf| j||
||d}|snd	}tj||||| j	j
|||||||	d
}|S )a  
        Plot cumulative impulse response functions

        Parameters
        ----------
        orth : bool, default False
            Compute orthogonalized impulse responses
        impulse : {str, int}
            variable providing the impulse
        response : {str, int}
            variable affected by the impulse
        signif : float (0 < signif < 1)
            Significance level for error bars, defaults to 95% CI
        subplot_params : dict
            To pass to subplot plotting funcions. Example: if fonts are too big,
            pass {'fontsize' : 8} or some number to your taste.
        plot_params : dict

        figsize: (float, float), default (10, 10)
            Figure size (width, height in inches)
        plot_stderr : bool, default True
            Plot standard impulse response error bands
        stderr_type : str
            'asym': default, computes asymptotic standard errors
            'mc': monte carlo standard errors (use rpl)
        repl : int, default 1000
            Number of replications for monte carlo standard errors
        seed : int
            np.random.seed for Monte Carlo replications
        z/Cumulative responses responses (orthogonalized)zCumulative responses)r+   r8   z)`stderr_type` must be one of 'asym', 'mc'r+   r<   r8   )r!   r5   r/   r6   N)r/   Zhlinesr2   r0   r1   r4   )r   r   r   r   r=   r)   cum_errband_mcrB   rC   r   rD   )r   r!   r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   rE   r   r   rF   rG   r   r   r   plot_cum_effects   s:    #
   zBaseIRAnalysis.plot_cum_effects)Nr   NFF)FF)F)F)
__name__
__module____qualname____doc__r   r"   r(   r)   rH   rJ   r   r   r   r   r      s8     
3
      V     r   c                   @   s   e Zd ZdZd,ddZd-ddZd.ddZd/ddZd0ddZd1ddZ	dd Z
edd Zdd Zd2ddZd3ddZd4ddZd5d d!Zd6d"d#Zd7d$d%Zd&d' Zed(d) Zd*d+ ZdS )8
IRAnalysisu   
    Impulse response analysis class. Computes impulse responses, asymptotic
    standard errors, and produces relevant plots

    Parameters
    ----------
    model : VAR instance

    Notes
    -----
    Using Lütkepohl (2005) notation
    Nr   Fc              	   C   s@   t j| ||||||d |r&|j| _n|j| _|j| _i | _d S )N)r   r   r   r   r   )r   r   Zcov_var_reprcov_aZ
_cov_alphaZ
_cov_sigmacov_sig_g_memo)r   r   r   r   r   r   r   r   r   r   r      s      
zIRAnalysis.__init__c                 C   sv   |r|   S | | jd }t| jd | jd f|d< td| jd D ]&}| j|d  }|| j |j	 ||< qJ|S )u   
        Compute asymptotic standard errors for impulse response coefficients

        Notes
        -----
        Lütkepohl eq 3.7.5

        Returns
        -------
              r   )
	_orth_cov_empty_covmr   r   zerosr	   rangeGrP   r   )r   r!   covsiZGir   r   r   r(     s    zIRAnalysis.covr,   r*   d   c           	   	   C   sD   | j }| j}|r(|j||||||ddS |j||||||ddS dS )z8
        IRF Monte Carlo integrated error bands
        Fr!   r5   stepsr/   r6   burnZcumN)r   r   Zsirf_errband_mcirf_errband_mc)	r   r!   r   r5   r/   r6   r_   r   r   r   r   r   r>   !  s    
  
  zIRAnalysis.errband_mcc                 C   s  | j }| j}	| ||}
| j}|j|||	||d}t|}| |\}}}|dk	rt	|||fkrt
dt| d t| t|||	 krt
dn|}t|
}t|
}t|D ]}t|D ]}|
dd||f |||dd|||f f | t||||||f f   |dd||f< |
dd||f |||dd|||f f | t||||||f f   |dd||f< qq||fS )a  
        IRF Sims-Zha error band method 1. Assumes symmetric error bands around
        mean.

        Parameters
        ----------
        orth : bool, default False
            Compute orthogonalized impulse responses
        repl : int, default 1000
            Number of MC replications
        signif : float (0 < signif < 1)
            Significance level for error bars, defaults to 95% CI
        seed : int, default None
            np.random seed
        burn : int, default 100
            Number of initial simulated obs to discard
        component : neqs x neqs array, default to largest for each
            Index of column of eigenvector/value to use for each error band
            Note: period of impulse (t=0) is not included when computing
            principle component

        References
        ----------
        Sims, Christopher A., and Tao Zha. 1999. "Error Bands for Impulse
        Response". Econometrica 67: 1113-1155.
        r!   r5   r^   r6   r_   NComponent array must be  x ,Atleast one of the components does not existrS   )r   r   r"   r	   	irf_resimr   Znorm_signif_level_eigval_decomp_SZr   shaper=   strargmaxcopyrX   sqrt)r   r!   r   r5   r/   r6   r_   r7   r   r   r   r	   re   qWeigvaklowerupperr[   jr   r   r   r?   1  s.    
 



\`zIRAnalysis.err_band_sz1c              	   C   s  | j }| j}	| ||}
| j}|j|||	|dd}| |\}}}|dk	rt|||fkrxtdt	| d t	| t
|||	 krtdn|}t||	d ||f}t|D ]`}t|D ]R}t|D ]D}||||||f ddf ||dd||f  ||dd||f< qqqtj|dd	}t|d
 | d td|d
  | d f}t|
}t|
}t|D ]}t|D ]v}|
dd||f ||d dd||f  |dd||f< |
dd||f ||d dd||f  |dd||f< qzqn||fS )a  
        IRF Sims-Zha error band method 2.

        This method Does not assume symmetric error bands around mean.

        Parameters
        ----------
        orth : bool, default False
            Compute orthogonalized impulse responses
        repl : int, default 1000
            Number of MC replications
        signif : float (0 < signif < 1)
            Significance level for error bars, defaults to 95% CI
        seed : int, default None
            np.random seed
        burn : int, default 100
            Number of initial simulated obs to discard
        component : neqs x neqs array, default to largest for each
            Index of column of eigenvector/value to use for each error band
            Note: period of impulse (t=0) is not included when computing
            principle component

        References
        ----------
        Sims, Christopher A., and Tao Zha. 1999. "Error Bands for Impulse
        Response". Econometrica 67: 1113-1155.
        r\   ra   Nrb   rc   rd   rS   r   r   rT   )r   r   r"   r	   re   rf   r   rg   r=   rh   ri   rW   rX   sortroundrj   )r   r!   r   r5   r/   r6   r_   r7   r   r   r   r	   re   rm   rn   ro   gammapr[   rr   
gamma_sortindxrp   rq   r   r   r   r@   j  s8    
F,

8@zIRAnalysis.err_band_sz2c              	   C   s4  | j }| j}	| ||}
| j}|j|||	|dd}t|||	| f}t|D ]@}t|D ]2}t||dddd|f j	|||ddf< qZqNt||	| |	| f}t||	| |	| f}t||	| f}tj|t
d}|dk	r,t||kr
tdt| t|||	 kr(tdn|}t|D ]<}tj|| dd	||< t|| \||< ||< ||< q4t||	d ||f}t|D ]}d}t|D ]}t|D ]}|||| ||	 |d |	 f ||dd||f  ||dd||f< ||d kr|||| ||	 df ||dd||f  ||dd||f< qqqtj|dd
}t|d | d td|d  | d f}t|
}t|
}t|D ]}t|D ]v}|
dd||f ||d dd||f  |dd||f< |
dd||f ||d dd||f  |dd||f< qq||fS )a  
        IRF Sims-Zha error band method 3. Does not assume symmetric error bands around mean.

        Parameters
        ----------
        orth : bool, default False
            Compute orthogonalized impulse responses
        repl : int, default 1000
            Number of MC replications
        signif : float (0 < signif < 1)
            Significance level for error bars, defaults to 95% CI
        seed : int, default None
            np.random seed
        burn : int, default 100
            Number of initial simulated obs to discard
        component : vector length neqs, default to largest for each
            Index of column of eigenvector/value to use for each error band
            Note: period of impulse (t=0) is not included when computing
            principle component

        References
        ----------
        Sims, Christopher A., and Tao Zha. 1999. "Error Bands for Impulse
        Response". Econometrica 67: 1113-1155.
        r\   ra   rS   NZdtypez"Component array must be of length rd   r   Zrowvarr   rT   )r   r   r"   r	   re   r   rW   rX   Zravelr   intsizer=   rh   ri   r(   r   eigval_decomprs   rt   rj   )r   r!   r   r5   r/   r6   r_   r7   r   r   r   r	   re   stackrv   r[   Z	stack_covrm   rn   ro   ru   crr   rw   rx   rp   rq   r   r   r   rA     sT    
 2

$FJ,

8@zIRAnalysis.err_band_sz3c           
      C   s  | j }| j}t||||f}t|D ]H}t|D ]:}tj|dddd||f dd|||ddddf< q2q&t||||f}t|||df}tj||ftd}	t|D ]b}t|D ]T}t|||ddddf \|||ddddf< |||dddf< |	||f< qq|||	fS )z
        Returns
        -------
        W: array of eigenvectors
        eigva: list of eigenvalues
        k: matrix indicating column # of largest eigenvalue for each c_i,j
        NrS   r   rz   ry   )	r	   r   r   rW   rX   r(   r{   r   r}   )
r   re   r	   r   Zcov_holdr[   rr   rm   rn   ro   r   r   r   rf     s    :TzIRAnalysis._eigval_decomp_SZc                    s2   j   fddfddtdjd D S )Nc                    sx   d}t | D ]f}| d | }|jkr2j| }n&tjj|}|d   }|j|< t|j| }|| }q|S )N        rS   )	rX   rR   r   Zmatrix_powerr   r   r   kronr   )r[   rY   midxZapowZpiece)Kr   r   r   _make_g  s    


zIRAnalysis.G.<locals>._make_gc                    s   g | ]} |qS r   r   ).0r[   )r   r   r   
<listcomp>1  s     z IRAnalysis.G.<locals>.<listcomp>rS   )r	   rX   r   r   r   )r   r   r   r   rY     s    zIRAnalysis.Gc           
      C   s   t | j}t | jj|}| j}| | jd }t	| jd D ]t}|dkrRd}n&t 
|| j|d  }|| j |j }t 
t || j| |}|| j |j | j }	||	 ||< q@|S )NrS   r   )r   eyer	   r   r   r   HrV   r   rX   r   rY   rP   r   rQ   )
r   IkPIkr   rZ   r[   apieceZCiZCibarbpiecer   r   r   rU   3  s    zIRAnalysis._orth_covc                 C   s  t | j}t | jj|}d}| | jd }t| jd D ]}|dkr\|| j	|d   }|r|dkrnd}nt 
||}|| j |j }t 
t || j| | j}	|	| j |	j | j }
||
 ||< q>|dkrt | jd | jd f||< q>|| j |j ||< q>|S )a  
        Compute asymptotic standard errors for cumulative impulse response
        coefficients

        Parameters
        ----------
        orth : bool

        Notes
        -----
        eq. 3.7.7 (non-orth), 3.7.10 (orth)

        Returns
        -------
        r   rS   r   rT   )r   r   r	   r   r   r   rV   r   rX   rY   r   rP   r   r   rQ   rW   )r   r!   r   r   FrZ   r[   r   ZBnZBnbarr   r   r   r   r)   J  s(    zIRAnalysis.cum_effect_covc              	   C   s$   | j }| j}|j||||||ddS )zM
        IRF Monte Carlo integrated error bands of cumulative effect
        Tr]   )r   r   r`   )r   r!   r5   r/   r6   r_   r   r   r   r   r   rI   w  s       zIRAnalysis.cum_errband_mcc                 C   s   | j }tt|j| j|}t| j}|rtt| j	jt| j|}tt||| j
}|| j |j || j |j  S || j |j S dS )z)
        Returns
        -------
        N)r   r   r   Ztiler   r
   r   r	   r   r   r   rP   rQ   )r   r!   ZlreZFinftyr   ZBinfZBinfbarr   r   r   lr_effect_cov  s     zIRAnalysis.lr_effect_covc                 C   s   t dd | j|dD S )Nc              	   S   s"   g | ]}t tt|qS r   tsaunvecr   rk   diagr   r   r   r   r   r     s   z%IRAnalysis.stderr.<locals>.<listcomp>r<   )r   arrayr(   r   r!   r   r   r   rF     s    

zIRAnalysis.stderrc                 C   s   t dd | j|dD S )Nc              	   S   s"   g | ]}t tt|qS r   r   r   r   r   r   r     s   z0IRAnalysis.cum_effect_stderr.<locals>.<listcomp>r<   )r   r   r)   r   r   r   r   cum_effect_stderr  s    

zIRAnalysis.cum_effect_stderrc                 C   s"   | j |d}ttt|S )Nr<   )r   r   r   r   rk   r   )r   r!   r(   r   r   r   lr_effect_stderr  s    zIRAnalysis.lr_effect_stderrc                 C   s    t j|| jd | jd ftdS )NrT   ry   )r   rW   r	   float)r   r   r   r   r   rV     s    zIRAnalysis._empty_covmc                 C   sd   | j }t|}t||}t|}|t|| j| t| j|  |j }t	|jt
|S r    )r	   r   Zelimination_matrixZcommutation_matrixr   r   r   r   r   r   Linv)r   ro   ZLkZKkkr   Br   r   r   r     s    

*zIRAnalysis.Hc                 C   s   t d S r    r#   r   r   r   r   
fevd_table  s    zIRAnalysis.fevd_table)Nr   NFF)F)FFr,   r*   Nr\   )FFr,   r*   Nr\   N)FFr,   r*   Nr\   N)FFr,   r*   Nr\   N)F)Fr,   r*   Nr\   )F)F)F)F)rK   rL   rM   rN   r   r(   r>   r?   r@   rA   rf   r   rY   rU   r)   rI   r   rF   r   r   rV   r   r   r   r   r   r   rO      sX     

      
        
9      
@      
Q

-      





rO   )rN   Znumpyr   Znumpy.linalgZlinalgr   Zscipy.linalgr   Zstatsmodels.tools.decoratorsr   Zstatsmodels.tsa.tsatoolsr   ZtsatoolsZ"statsmodels.tsa.vector_ar.plottingZ	vector_arrB   Zstatsmodels.tsa.vector_ar.utilr   r   matr   rO   r   r   r   r   <module>   s    _