U
    ÃmœdlZ  ã                   @  s†  d dl mZ d dl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 d dlmZmZ d dlmZ d d	lmZ d d
lmZmZmZmZ dddddddddddgZdFdd„ZdGdd„ZdHdd„ZdId"d#d$d%d&d'œd(d„ZdJd)d„Z d*d„ Z!d+d„ Z"d,d-„ Z#d.d/„ Z$d0d1„ Z%d2d„ Z&d3d„ Z'd4d„ Z(d5d„ Z)d6d„ Z*d7d8„ Z+d9d:„ Z,d;d<„ Z-d=d>„ Z.d?d@„ Z/dAdB„ Z0dCd"dDœdEd„Z1dS )Ké    )Úannotations)ÚlrangeÚLiteralN)Ú	DataFrame)Úoffsets)Ú	to_offset)Ú_is_recarrayÚ_is_using_pandas)ÚValueWarning)ÚNDArray)Ú
array_likeÚ	bool_likeÚint_likeÚstring_likeÚlagmatÚ	lagmat2dsÚ	add_trendÚduplication_matrixÚelimination_matrixÚcommutation_matrixÚvecÚvechÚunvecÚunvechÚfreq_to_periodÚcFÚskipc                 C  s²  t |dƒ}t|ddd�}t|ddd�}dddg}|d	kr@|  ¡ S |d
krZ|dd… }d}nB|dksj|dkr�|dd… }|dkrŠ|dd… }d}n|dkrœd}t| ƒr¸ddlm} t|ƒ‚t| dƒ}|rèt| t	j
ƒrÞt	 | ¡} qò|  ¡ } n
t | ¡} t| ƒ}t tjd|d tjd�|d ¡}	t |	¡}	|dk�r@|	dd…df }	d
|k�rJ|�rfdd„ }
|  |
d¡}n0tjt | ¡dd�}|dk}|| d dk@ }|}t |¡�rJ|dk�r | jdk�r¾d}nHt | jd ¡| }t| t	jƒ�ræ| j}d dd„ |D ƒ¡}d|› d�}|› d|› d�}t|ƒ‚n*|d k�rJ|dd… }|	dd…dd…f }	|�rTdnd!}|�r’t	j|	| j|d"�}	|	| g} t	j| dd|… dd�} n|	| g} t | dd|… ¡} | S )#aØ  
    Add a trend and/or constant to an array.

    Parameters
    ----------
    x : array_like
        Original array of data.
    trend : str {'n', 'c', 't', 'ct', 'ctt'}
        The trend to add.

        * 'n' add no trend.
        * 'c' add constant only.
        * 't' add trend only.
        * 'ct' add constant and linear trend.
        * 'ctt' add constant and linear and quadratic trend.
    prepend : bool
        If True, prepends the new data to the columns of X.
    has_constant : str {'raise', 'add', 'skip'}
        Controls what happens when trend is 'c' and a constant column already
        exists in x. 'raise' will raise an error. 'add' will add a column of
        1s. 'skip' will return the data without change. 'skip' is the default.

    Returns
    -------
    array_like
        The original data with the additional trend columns.  If x is a
        pandas Series or DataFrame, then the trend column names are 'const',
        'trend' and 'trend_squared'.

    See Also
    --------
    statsmodels.tools.tools.add_constant
        Add a constant column to an array.

    Notes
    -----
    Returns columns as ['ctt','ct','c'] whenever applicable. There is currently
    no checking for an existing trend.
    ÚprependÚtrend)Únr   ÚtÚctÚctt©ÚoptionsÚhas_constant)ÚraiseÚaddr   ÚconstZtrend_squaredr   r   Né   r   r!   r    é   r"   )Úrecarray_exception)Údtypec                 S  s2   zt  | ¡dkot  | dk¡W S    Y dS X d S )Ng        F)ÚnpÚptpÚany)Ús© r1   úQ/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/statsmodels/tsa/tsatools.pyÚsafe_is_const}   s    z add_trend.<locals>.safe_is_const©Úaxisr&   zx is constant.z, c                 S  s   g | ]}t |ƒ‘qS r1   ©Ústr©Ú.0r   r1   r1   r2   Ú
<listcomp>’   s     zadd_trend.<locals>.<listcomp>z3x contains one or more constant columns. Column(s) z are constant.z Adding a constant with trend='z' is not allowed.r   éÿÿÿÿ©ÚindexÚcolumns)r   r   Úcopyr   Ústatsmodels.tools.sm_exceptionsr+   ÚNotImplementedErrorr	   Ú
isinstanceÚpdZSeriesr   r-   Ú
asanyarrayÚlenÚvanderÚarangeZfloat64ZfliplrÚapplyr.   r/   ÚndimÚshaper>   ÚjoinÚ
ValueErrorr=   ÚconcatÚcolumn_stack)Úxr   r   r%   r>   Z
trendorderr+   Ú	is_pandasÚnobsZtrendarrr3   Z	col_constZptp0Zcol_is_constZnz_constZbase_errZ
const_colsÚmsgÚorderr1   r1   r2   r   &   sˆ    (
  ÿ



 ÿ




ÿ

r)   Tc           
      C  sV  t |dƒ}t|dƒ}t| ddd�} |dkr.d}|dk rD| jd | }| jdkr^| dd…df } | dd…|f }|d	kr€|d }nV|d
kr”| jd }nB|dk r®| jd | d }|| jd krÒ| jd }t dt¡ |}t||dd�}t	|ƒ}t	|| jd ƒ}	|�r.||k�r| 
| |¡¡ n|	 
|	 |¡¡ t | |d…|f || |d…|	f f¡S )aˆ  
    Returns an array with lags included given an array.

    Parameters
    ----------
    x : array_like
        An array or NumPy ndarray subclass. Can be either a 1d or 2d array with
        observations in columns.
    col : int or None
        `col` can be an int of the zero-based column index. If it's a
        1d array `col` can be None.
    lags : int
        The number of lags desired.
    drop : bool
        Whether to keep the contemporaneous variable for the data.
    insert : bool or int
        If True, inserts the lagged values after `col`. If False, appends
        the data. If int inserts the lags at int.

    Returns
    -------
    array : ndarray
        Array with lags

    Examples
    --------

    >>> import statsmodels.api as sm
    >>> data = sm.datasets.macrodata.load()
    >>> data = data.data[['year','quarter','realgdp','cpi']]
    >>> data = sm.tsa.add_lag(data, 'realgdp', lags=2)

    Notes
    -----
    Trims the array both forward and backward, so that the array returned
    so that the length of the returned array is len(`X`) - lags. The lags are
    returned in increasing order, ie., t-1,t-2,...,t-lags
    ÚlagsÚdroprO   r*   )rI   Nr   r)   TFz<insert > number of variables, inserting at the last positionZBoth)Útrim)r   r   r   rJ   rI   ÚwarningsÚwarnr
   r   r   Úpopr=   r-   rN   )
rO   ÚcolrT   rU   ÚinsertZcontempZins_idxZndlagsZ
first_colsZ	last_colsr1   r1   r2   Úadd_lag©   s>    '




ý
r\   c                 C  sÆ   t |dƒ}t |dƒ}| jdkr2t|ƒdkr2| j} n| jdkrDtdƒ‚| jd }|dkrh| | jdd� }n>tjt 	t
|ƒ¡|d d�}tj |¡ | ¡}| t ||¡ }| jdkrÂt|ƒdkrÂ|j}|S )	a˜  
    Detrend an array with a trend of given order along axis 0 or 1.

    Parameters
    ----------
    x : array_like, 1d or 2d
        Data, if 2d, then each row or column is independently detrended with
        the same trendorder, but independent trend estimates.
    order : int
        The polynomial order of the trend, zero is constant, one is
        linear trend, two is quadratic trend.
    axis : int
        Axis can be either 0, observations by rows, or 1, observations by
        columns.

    Returns
    -------
    ndarray
        The detrended series is the residual of the linear regression of the
        data on the trend of given order.
    rS   r5   r*   r)   z0x.ndim > 2 is not implemented until it is neededr   r4   )ÚN)r   rI   ÚintÚTrA   rJ   Zmeanr-   rF   rG   ÚfloatZlinalgZpinvÚdot)rO   rS   r5   rQ   ZresidZtrendsÚbetar1   r1   r2   Údetrendù   s"    


ÿ
rc   ÚforwardÚexr^   z0Literal[('forward', 'backward', 'both', 'none')]zLiteral[('ex', 'sep', 'in')]ÚboolzKNDArray | DataFrame | tuple[NDArray, NDArray] | tuple[DataFrame, DataFrame])ÚmaxlagrV   ÚoriginalÚ
use_pandasÚreturnc                   sz  t |dƒ}t|dƒ}t|dddd�}t|ddd	�}| }t| d
ddd�} t|dƒoR|}|dkr`dn|}| ¡ }|r€|dkr€tdƒ‚d}| j\}}	|dkrš|	}||krªtdƒ‚t 	|| |	|d  f¡}
t
dt|d ƒƒD ]8}| |
|| || | …|	||  |	|| d  …f< qÖ|dk�r d}n|dk�r0|}ntdƒ‚|dk�rLt|
ƒ}n|}|�r.|} t| tƒ�r˜dd„ | jD ƒ}tt|ƒƒ| jd k�r¤tdƒ‚nt| jƒg}dd„ |D ƒ}t
|ƒD ]*}t|d ƒ‰ | ‡ fdd„|D ƒ¡ �qºt|
d|… | j|d�}
|
j|d… }|dk�r`|| }|j|dd�}n2|
||…|d…f }|d k�r`|
||…d|…f }|d k�rr||fS |S dS )!a,	  
    Create 2d array of lags.

    Parameters
    ----------
    x : array_like
        Data; if 2d, observation in rows and variables in columns.
    maxlag : int
        All lags from zero to maxlag are included.
    trim : {'forward', 'backward', 'both', 'none', None}
        The trimming method to use.

        * 'forward' : trim invalid observations in front.
        * 'backward' : trim invalid initial observations.
        * 'both' : trim invalid observations on both sides.
        * 'none', None : no trimming of observations.
    original : {'ex','sep','in'}
        How the original is treated.

        * 'ex' : drops the original array returning only the lagged values.
        * 'in' : returns the original array and the lagged values as a single
          array.
        * 'sep' : returns a tuple (original array, lagged values). The original
                  array is truncated to have the same number of rows as
                  the returned lagmat.
    use_pandas : bool
        If true, returns a DataFrame when the input is a pandas
        Series or DataFrame.  If false, return numpy ndarrays.

    Returns
    -------
    lagmat : ndarray
        The array with lagged observations.
    y : ndarray, optional
        Only returned if original == 'sep'.

    Notes
    -----
    When using a pandas DataFrame or Series with use_pandas=True, trim can only
    be 'forward' or 'both' since it is not possible to consistently extend
    index values.

    Examples
    --------
    >>> from statsmodels.tsa.tsatools import lagmat
    >>> import numpy as np
    >>> X = np.arange(1,7).reshape(-1,2)
    >>> lagmat(X, maxlag=2, trim="forward", original='in')
    array([[ 1.,  2.,  0.,  0.,  0.,  0.],
       [ 3.,  4.,  1.,  2.,  0.,  0.],
       [ 5.,  6.,  3.,  4.,  1.,  2.]])

    >>> lagmat(X, maxlag=2, trim="backward", original='in')
    array([[ 5.,  6.,  3.,  4.,  1.,  2.],
       [ 0.,  0.,  5.,  6.,  3.,  4.],
       [ 0.,  0.,  0.,  0.,  5.,  6.]])

    >>> lagmat(X, maxlag=2, trim="both", original='in')
    array([[ 5.,  6.,  3.,  4.,  1.,  2.]])

    >>> lagmat(X, maxlag=2, trim="none", original='in')
    array([[ 1.,  2.,  0.,  0.,  0.,  0.],
       [ 3.,  4.,  1.,  2.,  0.,  0.],
       [ 5.,  6.,  3.,  4.,  1.,  2.],
       [ 0.,  0.,  5.,  6.,  3.,  4.],
       [ 0.,  0.,  0.,  0.,  5.,  6.]])
    rg   ri   rV   T©rd   ÚbackwardÚbothÚnone©Úoptionalr$   rh   )re   ÚsepÚinr#   rO   r*   N)rI   r,   rn   )rn   rl   zEtrim cannot be 'none' or 'backward' when used on Series or DataFramesr   )re   rq   zmaxlag should be < nobsr)   )rn   rd   )rl   rm   ztrim option not validc                 S  s   g | ]}t |ƒ‘qS r1   r6   r8   r1   r1   r2   r:   £  s     zlagmat.<locals>.<listcomp>zSColumns names must be distinct after conversion to string (if not already strings).c                 S  s   g | ]}t |ƒ‘qS r1   r6   ©r9   rZ   r1   r1   r2   r:   «  s     c                   s   g | ]}t |ƒd  ˆ  ‘qS )z.L.r6   rs   ©Zlag_strr1   r2   r:   ®  s     r<   )rq   re   r4   rq   )r   r   r   r   r	   ÚlowerrL   rJ   r-   ÚzerosÚranger^   rE   rB   r   r>   Úsetr7   ÚnameÚextendr=   ÚilocrU   )rO   rg   rV   rh   ri   ÚorigrP   ZdropidxrQ   ÚnvarZlmÚkZstartobsZstopobsZ	x_columnsr>   ZlagrT   Zleadsr1   rt   r2   r   (  s„    I

üÿ
ý 
ÿ
 þ



ÿ


c              	   C  sÔ  t |dƒ}t |ddd�}t|dddd�}|dkr4|}t||ƒ}t| dƒ}| jd	krt|rbt | ¡} q�| dd…df } n| jd
ksˆ| jdkr�tdƒ‚| j\}}	|�r@|�r@t	| j
dd…d
f ||ddd�}
|
j
dd…d|d	 …f g}td	|	ƒD ]D}t	| j
dd…|f ||ddd�}
| |
j
dd…||d	 …f ¡ qìtj|d	d�S |�rPt | ¡} t	| dd…d
f ||dd�dd…d|d	 …f g}td	|	ƒD ]<}| t	| dd…|f ||dd�dd…||d	 …f ¡ �qŒt |¡S )a©  
    Generate lagmatrix for 2d array, columns arranged by variables.

    Parameters
    ----------
    x : array_like
        Data, 2d. Observations in rows and variables in columns.
    maxlag0 : int
        The first variable all lags from zero to maxlag are included.
    maxlagex : {None, int}
        The max lag for all other variables all lags from zero to maxlag are
        included.
    dropex : int
        Exclude first dropex lags from other variables. For all variables,
        except the first, lags from dropex to maxlagex are included.
    trim : str
        The trimming method to use.

        * 'forward' : trim invalid observations in front.
        * 'backward' : trim invalid initial observations.
        * 'both' : trim invalid observations on both sides.
        * 'none' : no trimming of observations.
    use_pandas : bool
        If true, returns a DataFrame when the input is a pandas
        Series or DataFrame.  If false, return numpy ndarrays.

    Returns
    -------
    ndarray
        The array with lagged observations, columns ordered by variable.

    Notes
    -----
    Inefficient implementation for unequal lags, implemented for convenience.
    Úmaxlag0ÚmaxlagexT)rp   rV   rk   ro   Nr)   r   r*   z'Only supports 1 and 2-dimensional data.rr   )rV   rh   ri   r4   )rV   rh   )r   r   Úmaxr	   rI   rC   r   rL   rJ   r   r{   rw   ÚappendrM   r-   rD   rN   )rO   r   r€   ZdropexrV   ri   rg   rP   rQ   r}   rT   Zlagslir~   r1   r1   r2   r   ¿  sd    &
ü



    ÿ    ÿ"
.ÿ  ÿÿc                 C  s
   |   d¡S )NÚF)Úravel©Úmatr1   r1   r2   r     s    c                 C  s   | j  tt| ƒƒ¡S ©N)r_   ÚtakeÚ_triu_indicesrE   r…   r1   r1   r2   r     s    c                 C  s   t  | ¡\}}||  | S r‡   )r-   Ztril_indices©r   ÚrowsÚcolsr1   r1   r2   Ú_tril_indices"  s    r�   c                 C  s   t  | ¡\}}||  | S r‡   )r-   Útriu_indicesrŠ   r1   r1   r2   r‰   '  s    r‰   c                 C  s   t  | ¡\}}||  | S r‡   )r-   Údiag_indicesrŠ   r1   r1   r2   Ú_diag_indices,  s    r�   c                 C  s8   t t t| ƒ¡ƒ}|| t| ƒks&t‚| j||fdd�S )Nrƒ   ©rS   )r^   r-   ÚsqrtrE   ÚAssertionErrorÚreshape)Úvr~   r1   r1   r2   r   1  s    c                 C  sl   ddt  ddt| ƒ  ¡  }tt  |¡ƒ}t  ||f¡}| |t  |¡< ||j }|t  |¡  d  < |S )Ng      à?r;   r)   é   r*   )	r-   r’   rE   r^   Úroundrv   rŽ   r_   r�   )r•   r‹   Úresultr1   r1   r2   r   7  s    
c                 C  s6   t | dƒ} t | | d  d ¡}t dd„ |D ƒ¡jS )z’
    Create duplication matrix D_n which satisfies vec(S) = D_n vech(S) for
    symmetric matrix S

    Returns
    -------
    D_n : ndarray
    r   r)   r*   c                 S  s   g | ]}t |ƒ ¡ ‘qS r1   )r   r„   )r9   rO   r1   r1   r2   r:   Q  s     z&duplication_matrix.<locals>.<listcomp>)r   r-   ÚeyeÚarrayr_   )r   Útmpr1   r1   r2   r   F  s    	
c                 C  s8   t | dƒ} tt t | | f¡¡ƒ}t | |  ¡|dk S )z�
    Create the elimination matrix L_n which satisfies vech(M) = L_n vec(M) for
    any matrix M

    Parameters
    ----------

    Returns
    -------
    r   r   )r   r   r-   ZtrilZonesr™   )r   Zvech_indicesr1   r1   r2   r   T  s    
c                 C  sP   t | dƒ} t |dƒ}t | | ¡}t | | ¡j| |fdd�}|j| ¡ dd�S )z½
    Create the commutation matrix K_{p,q} satisfying vec(A') = K_{p,q} vec(A)

    Parameters
    ----------
    p : int
    q : int

    Returns
    -------
    K : ndarray (pq x pq)
    ÚpÚqrƒ   r‘   r   r4   )r   r-   r™   rG   r”   rˆ   r„   )rœ   r�   ÚKÚindicesr1   r1   r2   r   d  s
    

c              	   C  s~   t  | d ¡}t  | d ¡}tdt| ƒƒD ]N}|| }t|ƒD ]$}||  |||| d   8  < q>|d|… |d|…< q*|S )zÁ
    Transforms params to induce stationarity/invertability.

    Parameters
    ----------
    params : array_like
        The AR coefficients

    Reference
    ---------
    Jones(1980)
    r*   r)   N)r-   Útanhrw   rE   )ÚparamsÚ	newparamsr›   ÚjÚaÚkiterr1   r1   r2   Ú_ar_transparamsy  s    "r¦   c                 C  s’   |   ¡ } |   ¡ }tt| ƒd ddƒD ]Z}| | }t|ƒD ]0}| | || || d    d|d   ||< q8|d|… | d|…< q$dt | ¡ }|S )z�
    Inverse of the Jones reparameterization

    Parameters
    ----------
    params : array_like
        The transformed AR coefficients
    r)   r   r;   r*   N)r?   rw   rE   r-   Zarctanh)r¡   r›   r£   r¤   r¥   Z
invarcoefsr1   r1   r2   Ú_ar_invtransparams�  s    	
ÿ
r§   c              	   C  sª   dt  |  ¡ dt  |  ¡   ¡ }dt  |  ¡ dt  |  ¡   ¡ }tdt| ƒƒD ]N}|| }t|ƒD ]$}||  |||| d   7  < qj|d|… |d|…< qV|S )zÒ
    Transforms params to induce stationarity/invertability.

    Parameters
    ----------
    params : ndarray
        The ma coeffecients of an (AR)MA model.

    Reference
    ---------
    Jones(1980)
    r)   N)r-   Úexpr?   rw   rE   )r¡   r¢   r›   r£   Úbr¥   r1   r1   r2   Ú_ma_transparams¦  s    $$"rª   c                 C  s”   |   ¡ }tt| ƒd ddƒD ]Z}| | }t|ƒD ]0}| | || || d    d|d   ||< q0|d|… | d|…< qt d|  d|   ¡ }|S )z�
    Inverse of the Jones reparameterization

    Parameters
    ----------
    params : ndarray
        The transformed MA coefficients
    r)   r   r;   r*   N)r?   rw   rE   r-   Úlog)Zmacoefsr›   r£   r©   r¥   Z
invmacoefsr1   r1   r2   Ú_ma_invtransparams¿  s    	
ÿ
r¬   c                   s8   t ˆ dƒ‰ ˆdˆ … ‰t ‡ ‡fdd„tˆ ddƒD ƒ¡S )a“  
    Returns the successive differences needed to unintegrate the series.

    Parameters
    ----------
    x : array_like
        The original series
    d : int
        The number of differences of the differenced series.

    Returns
    -------
    y : array_like
        The increasing differences from 0 to d-1 of the first d elements
        of x.

    See Also
    --------
    unintegrate
    ÚdNc                   s    g | ]}t  ˆˆ | ¡d  ‘qS )r   )r-   Údiff)r9   Úi©r­   rO   r1   r2   r:   ë  s     z&unintegrate_levels.<locals>.<listcomp>r   r;   )r   r-   Zasarrayrw   )rO   r­   r1   r°   r2   Úunintegrate_levelsÔ  s    
r±   c                 C  s\   t |ƒdd… }t|ƒdkr@| d¡}tt tj|| f ¡|ƒS |d }t tj|| f ¡S )ay  
    After taking n-differences of a series, return the original series

    Parameters
    ----------
    x : array_like
        The n-th differenced series
    levels : list
        A list of the first-value in each differenced series, for
        [first-difference, second-difference, ..., n-th difference]

    Returns
    -------
    y : array_like
        The original series de-differenced

    Examples
    --------
    >>> x = np.array([1, 3, 9., 19, 8.])
    >>> levels = unintegrate_levels(x, 2)
    >>> levels
    array([ 1.,  2.])
    >>> unintegrate(np.diff(x, 2), levels)
    array([  1.,   3.,   9.,  19.,   8.])
    Nr)   r;   r   )ÚlistrE   rY   Úunintegrater-   ZcumsumZr_)rO   ZlevelsZx0r1   r1   r2   r³   î  s    
r³   zstr | offsets.DateOffset)Úfreqrj   c                 C  s¼   t | tjƒst| ƒ} t | tjƒs$t‚| j ¡ } | dks@|  d¡rDdS | dksV|  d¡rZdS | dksl|  d¡rpd	S | d
ks‚|  d¡r†dS | dkr’dS | dkrždS | dkrªdS td 	| ¡ƒ‚dS )a$  
    Convert a pandas frequency to a periodicity

    Parameters
    ----------
    freq : str or offset
        Frequency to convert

    Returns
    -------
    int
        Periodicity of freq

    Notes
    -----
    Annual maps to 1, quarterly maps to 4, monthly to 12, weekly to 52.
    ÚA)zA-zAS-r)   ÚQ)zQ-zQS-é   ÚM)zM-ZMSé   ÚWzW-é4   ÚDé   ÚBé   ÚHé   zDfreq {} not understood. Please report if you think this is in error.N)
rB   r   Z
DateOffsetr   r“   Z	rule_codeÚupperÚ
startswithrL   Úformat)r´   r1   r1   r2   r     s.    
ÿÿ)r   Fr   )Nr)   FT)r)   r   )rd   re   F)Nr   rd   F)2Ú
__future__r   Zstatsmodels.compat.pythonr   r   rW   Únumpyr-   ZpandasrC   r   Zpandas.tseriesr   Zpandas.tseries.frequenciesr   Zstatsmodels.tools.datar   r	   r@   r
   Zstatsmodels.tools.typingr   Zstatsmodels.tools.validationr   r   r   r   Ú__all__r   r\   rc   r   r   r   r   r�   r‰   r�   r   r   r   r   r   r¦   r§   rª   r¬   r±   r³   r   r1   r1   r1   r2   Ú<module>   sl   õ
 
P
1   ü        ÿ
W"