
    M/Phk@                    :   d Z ddlZddlm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mZmZmZmZmZ d	Zd
Zej        ej        ej        ej        dZej        ej        ej        ej        dZ ej!        ej"        ej#        ej$        dZ%ej&        ej'        ej(        ej)        dZ*ej+        ej,        ej-        ej.        dZ/ej0        ej1        ej2        ej3        dZ4ej5        ej6        ej7        ej8        dZ9ej:        ej;        ej<        ej=        dZ>ej?        ej@        ejA        ejB        dZCejD        ejE        ejF        ejG        dZHejI        ejJ        ejK        ejL        dZMejN        ejO        ejP        ejQ        dZRejS        ejT        ejU        ejV        dZWejX        ejY        ejZ        ej[        dZ\ej]        ej^        ej_        ej`        dZaejb        ejc        ejd        eje        dZfd2dZgd Zhd3dZid4dZjd5dZkd6dZld Zmd Zn	 	 d7dZo	 	 d8dZp	 	 d9dZq eeqj                   	 	 d9d            Zrd7dZsd Zt	 	 d:dZud Zv	 d7dZw	 d7dZxd Zyd  Zzd! Z{	 	 	 d;d"Z|d9d#Z}	 	 d;d$Z~d9d%Z	 	 d;d&Zd9d'Zd( Zd) Zd<d*Zd+ Z	 	 d=d-Z	 	 d>d.Z	 	 d>d/Zd0 Zd1 ZdS )?z?
Statespace Tools

Author: Chad Fulton
License: Simplified-BSD
    N)solve_sylvester)Appender_is_using_pandas)find_best_blas_type   )_initialization_representation_kalman_filter_kalman_smoother_simulation_smoother_cfa_simulation_smoother_toolsFT)sdczc                 (    | rt          d          d S )Nz:Compatibility mode is only available in statsmodels <= 0.9)NotImplementedError)compatibilitys    `/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/tsa/statespace/tools.pyset_moder   r   s+     9! #8 9 9 	99 9    c                 f   d}t          | t          t          j        f          rt          |           }d}d} nt	          |           dz
  }|dk     rt          d          t          | t          t          f          rj	 t	          | d                   }n# t          $ r d}Y nw xY w|dk    rt          j	        |           } n<| d         dk    rt          j
        |          | d<   d}nd}t          j	        |           } t          j        ||z  ||z  ft          j	        |           j                  }t          j        |dz
  |z            }|d         |d         |z   f}d||<   | |dk    r|dk    r| dd          | d         z  |dddf<   n|r6t          |          D ]%}| |dz            j         |||z  |dz   |z  d|f<   &nmt          j                            | d                   }t          |          D ]8}t          j        || |dz                      j         |||z  |dz   |z  d|f<   9|S )a	  
    Create a companion matrix

    Parameters
    ----------
    polynomial : array_like or list
        If an iterable, interpreted as the coefficients of the polynomial from
        which to form the companion matrix. Polynomial coefficients are in
        order of increasing degree, and may be either scalars (as in an AR(p)
        model) or coefficient matrices (as in a VAR(p) model). If an integer,
        it is interpreted as the size of a companion matrix of a scalar
        polynomial, where the polynomial coefficients are initialized to zeros.
        If a matrix polynomial is passed, :math:`C_0` may be set to the scalar
        value 1 to indicate an identity matrix (doing so will improve the speed
        of the companion matrix creation).

    Returns
    -------
    companion_matrix : ndarray

    Notes
    -----
    Given coefficients of a lag polynomial of the form:

    .. math::

        c(L) = c_0 + c_1 L + \dots + c_p L^p

    returns a matrix of the form

    .. math::
        \begin{bmatrix}
            \phi_1 & 1      & 0 & \cdots & 0 \\
            \phi_2 & 0      & 1 &        & 0 \\
            \vdots &        &   & \ddots & 0 \\
                   &        &   &        & 1 \\
            \phi_n & 0      & 0 & \cdots & 0 \\
        \end{bmatrix}

    where some or all of the :math:`\phi_i` may be non-zero (if `polynomial` is
    None, then all are equal to zero).

    If the coefficients provided are scalars :math:`(c_0, c_1, \dots, c_p)`,
    then the companion matrix is an :math:`n \times n` matrix formed with the
    elements in the first column defined as
    :math:`\phi_i = -\frac{c_i}{c_0}, i \in 1, \dots, p`.

    If the coefficients provided are matrices :math:`(C_0, C_1, \dots, C_p)`,
    each of shape :math:`(m, m)`, then the companion matrix is an
    :math:`nm \times nm` matrix formed with the elements in the first column
    defined as :math:`\phi_i = -C_0^{-1} C_i', i \in 1, \dots, p`.

    It is important to understand the expected signs of the coefficients. A
    typical AR(p) model is written as:

    .. math::
        y_t = a_1 y_{t-1} + \dots + a_p y_{t-p} + \varepsilon_t

    This can be rewritten as:

    .. math::
        (1 - a_1 L - \dots - a_p L^p )y_t = \varepsilon_t \\
        (1 + c_1 L + \dots + c_p L^p )y_t = \varepsilon_t \\
        c(L) y_t = \varepsilon_t

    The coefficients from this form are defined to be :math:`c_i = - a_i`, and
    it is the :math:`c_i` coefficients that this function expects to be
    provided.
    Fr   Nz=Companion matrix polynomials must include at least two terms.r   Tdtype)
isinstanceintnpintegerlen
ValueErrorlisttuple	TypeError
asanyarrayeyezerosr   diag_indicesrangeTlinalginvdot)
polynomialidentity_matrixnmmatrixidxir-   s           r   companion_matrixr6   x   s   L O*sBJ/00 3
OO


OOaq55 1 2 2 2 j4-00 	3 
1&&    Avv]:66

 A!## "q		
1"&Az22JXq1ua!enBM*,E,E,KLLLF
/1q5A+
&
&Cq63q6A:
CF3K!a%%66&qrrN?Z]:F111a4LL 	P1XX C C1;AaC1B0Bq1ua!eq[("1",--C )--
1..C1XX P P13Z!_1M1M1O0Oq1ua!eq[("1",--Ms   <B B! B!c                 z   t          | d          }|st          j        |           n| }|I|dk    rC|s||d         |d|          z
  }n|                    |          }||d         }|dz  }|dk    C|st          j        ||d          }n-|dk    r'|                                dd         }|dz  }|dk    '|S )a  
    Difference a series simply and/or seasonally along the zero-th axis.

    Given a series (denoted :math:`y_t`), performs the differencing operation

    .. math::

        \Delta^d \Delta_s^D y_t

    where :math:`d =` `diff`, :math:`s =` `seasonal_periods`,
    :math:`D =` `seasonal\_diff`, and :math:`\Delta` is the difference
    operator.

    Parameters
    ----------
    series : array_like
        The series to be differenced.
    k_diff : int, optional
        The number of simple differences to perform. Default is 1.
    k_seasonal_diff : int or None, optional
        The number of seasonal differences to perform. Default is no seasonal
        differencing.
    seasonal_periods : int, optional
        The seasonal lag. Default is 1. Unused if there is no seasonal
        differencing.

    Returns
    -------
    differenced : ndarray
        The differenced array.
    Nr   r   axis)r   r   r&   diff)seriesk_diffk_seasonal_diffseasonal_periodspandasdifferencedsdiffeds          r   r:   r:      s   @ fd++F/5A"-'''6K "!! 9*+;+<+<=*+=-=,=+=> ? &**+;<<%&6&7&78q O !!  gk6:::qjj%**,,QRR0KaKF qjj r   c                    t           j        d | D                      }t           j        d | D                      }t          j        |          }|dk    rt          d          t	          | t
                    rt          |           } t          t          |                     D ]}||         dk    r$|dk    rt          j	        | |                   | |<   2||         dk    r$|dk    rt          j
        | |                   | |<   b||         dk    rG|dk    rA||         r9| |         j        }| |                                         | |<   |g| |         _        ||         dk    r0|dk    r*||         s"t          j
        | |                   j        | |<   t          j        |          rit	          | d         t           j                  r| d         j        }n t!          j        | d         j        g          }t          dt          |                     D ]}| |         }	t	          |	t           j                  rD|	j                            t!          j        dg                    r|dd         |	_        |	j        }
nt!          j        |	j        g          }
|dk    r$|                    |
          st          d          |dk    r4| d         j                            |	j                  st          d	          t!          j        | |
          }n=t          j        |           s|rt          j        | |
          }nt          d          |S )a{  
    Concatenate a set of series.

    Parameters
    ----------
    series : iterable
        An iterable of series to be concatenated
    axis : int, optional
        The axis along which to concatenate. Default is 1 (columns).
    allow_mix : bool
        Whether or not to allow a mix of pandas and non-pandas objects. Default
        is False. If true, the returned object is an ndarray, and additional
        pandas metadata (e.g. column names, indices, etc) is lost.

    Returns
    -------
    concatenated : array or pd.DataFrame
        The concatenated array. Will be a DataFrame if series are pandas
        objects.
    c                 .    g | ]}t          |d           S Nr   .0r   s     r   
<listcomp>zconcat.<locals>.<listcomp>>  s#    AAAQ'400AAAr   c                 6    g | ]}t          j        |          S  )r   ndimrE   s     r   rG   zconcat.<locals>.<listcomp>?  s     ---"'!**---r      zA`tools.concat` does not support arrays with 3 or more dimensions.r   r   Nz-Columns must match to concatenate along rows.z.Index must match to concatenate along columns.r8   zWAttempted to concatenate Pandas objects with non-Pandas objects with `allow_mix=False`.)r   r_maxr"   r   r$   r#   r*   r!   
atleast_1d
atleast_2dnameto_framecolumnsr+   allpd	DataFrameIndexequalsindexconcatconcatenate)r;   r9   	allow_mix	is_pandasrJ   max_ndimr5   rP   base_columnsr   	s_columnsconcatenateds               r   rY   rY   )  sC   * AA&AAABI5--f---.Dvd||H!|| - . . 	. &%   f 3v;; 
3 
37a<<HMMfQi00F1II!W\\h!mmfQi00F1II!W\\h!mm	!m!9>Dq	**,,F1I!%F1I!W\\h!mmIaLmfQi002F1I	vi HfQi.. 	6!!9,LL8VAY^$455Lq#f++&& 	. 	.Aq	A!R\** / 9##BHdV$4$455 1 ,RaR 0AII		HafX..	qyy!4!4Y!?!?y  "* + + +6!9?#9#9!'#B#B  "- . . .yd333	
		 Hy H~f4888 G H H 	H r   A?c                     t           j                            t          |                     }t          j        t          j        |          |k               S )a  
    Determine if a polynomial is invertible.

    Requires all roots of the polynomial lie inside the unit circle.

    Parameters
    ----------
    polynomial : array_like or tuple, list
        Coefficients of a polynomial, in order of increasing degree.
        For example, `polynomial=[1, -0.5]` corresponds to the polynomial
        :math:`1 - 0.5x` which has root :math:`2`. If it is a matrix
        polynomial (in which case the coefficients are coefficient matrices),
        a tuple or list of matrices should be passed.
    threshold : number
        Allowed threshold for `is_invertible` to return True. Default is 1.

    See Also
    --------
    companion_matrix

    Notes
    -----

    If the coefficients provided are scalars :math:`(c_0, c_1, \dots, c_n)`,
    then the corresponding polynomial is :math:`c_0 + c_1 L + \dots + c_n L^n`.


    If the coefficients provided are matrices :math:`(C_0, C_1, \dots, C_n)`,
    then the corresponding polynomial is :math:`C_0 + C_1 L + \dots + C_n L^n`.

    There are three equivalent methods of determining if the polynomial
    represented by the coefficients is invertible:

    The first method factorizes the polynomial into:

    .. math::

        C(L) & = c_0 + c_1 L + \dots + c_n L^n \\
             & = constant (1 - \lambda_1 L)
                 (1 - \lambda_2 L) \dots (1 - \lambda_n L)

    In order for :math:`C(L)` to be invertible, it must be that each factor
    :math:`(1 - \lambda_i L)` is invertible; the condition is then that
    :math:`|\lambda_i| < 1`, where :math:`\lambda_i` is a root of the
    polynomial.

    The second method factorizes the polynomial into:

    .. math::

        C(L) & = c_0 + c_1 L + \dots + c_n L^n \\
             & = constant (L - \zeta_1) (L - \zeta_2) \dots (L - \zeta_3)

    The condition is now :math:`|\zeta_i| > 1`, where :math:`\zeta_i` is a root
    of the polynomial with reversed coefficients and
    :math:`\lambda_i = \frac{1}{\zeta_i}`.

    Finally, a companion matrix can be formed using the coefficients of the
    polynomial. Then the eigenvalues of that matrix give the roots of the
    polynomial. This last method is the one actually used.
    )r   r,   eigvalsr6   rS   abs)r/   	thresholdrc   s      r   is_invertiblerf   x  s@    F i 0 < <==G6"&//I-...r   c           	         t          j        | j        d         | j                  }|s|                                                                 }t           j                            ||z             }t          j        ||z
  |          }dt          j        t          j        t           j                            | |z             |          |          z  }t          |                                                                ||           S |                                 }t           j                            ||z             }t          j        ||z
  |          }dt          j        t          j        t           j                            | |z             |          |          z  }t          |                                ||           S )a  
    Solves the discrete Lyapunov equation using a bilinear transformation.

    Notes
    -----
    This is a modification of the version in Scipy (see
    https://github.com/scipy/scipy/blob/master/scipy/linalg/_solvers.py)
    which allows passing through the complex numbers in the matrix a
    (usually the transition matrix) in order to allow complex step
    differentiation.
    r   r   rK   )
r   r'   shaper   conj	transposer,   r-   r.   r   )aqcomplex_stepr'   aHaHI_invbr   s           r   solve_discrete_lyapunovrq     sR    &17
+
+
+C 5VVXX!!)--S))F28W%%bfRVBIMM!c'22A66@@@qvvxx1133Q;;;[[]])--S))F28W%%bfRVBIMM!c'22A66@@@q{{}}a!444r   c                 R   | j         d         }t          j        ||f| j                  }| d| dz  z   dz  z  }t	          |          D ]P}t	          |          D ]1}||dz
  |f         ||         ||dz
  ||z
  dz
  f         z  z   |||f<   2||         |||f<   Q||dz
  ddf          S )a  
    Transform unconstrained parameters used by the optimizer to constrained
    parameters used in likelihood evaluation

    Parameters
    ----------
    unconstrained : ndarray
        Unconstrained parameters used by the optimizer, to be transformed to
        stationary coefficients of, e.g., an autoregressive or moving average
        component.

    Returns
    -------
    constrained : ndarray
        Constrained parameters of, e.g., an autoregressive or moving average
        component, to be transformed to arbitrary parameters used by the
        optimizer.

    References
    ----------
    .. [*] Monahan, John F. 1984.
       "A Note on Enforcing Stationarity in
       Autoregressive-moving Average Models."
       Biometrika 71 (2) (August 1): 403-404.
    r   r   r   rK         ?N)rh   r   r(   r   r*   )unconstrainedr1   yrkr5   s         r   constrain_stationary_univariaterx     s    6 	AA
!Q}2333AM1,,s23A1XX  q 	? 	?AAqkAaD1QUAEAI-=+>$>>AadGGA$!Q$a!eQQQhK<r   c                    | j         d         }t          j        ||f| j                  }|  ||dz
  d<   t	          |dz
  dd          D ]S}t	          |          D ]A}|||f         |||f         ||||z
  dz
  f         z  z
  d|||f         dz  z
  z  ||dz
  |f<   BT|                                }|d|dz  z
  dz  z  }|S )a  
    Transform constrained parameters used in likelihood evaluation
    to unconstrained parameters used by the optimizer

    Parameters
    ----------
    constrained : ndarray
        Constrained parameters of, e.g., an autoregressive or moving average
        component, to be transformed to arbitrary parameters used by the
        optimizer.

    Returns
    -------
    unconstrained : ndarray
        Unconstrained parameters used by the optimizer, to be transformed to
        stationary coefficients of, e.g., an autoregressive or moving average
        component.

    References
    ----------
    .. [*] Monahan, John F. 1984.
       "A Note on Enforcing Stationarity in
       Autoregressive-moving Average Models."
       Biometrika 71 (2) (August 1): 403-404.
    r   r   r   NrK   rs   )rh   r   r(   r   r*   diagonal)constrainedr1   ru   rw   r5   rv   xs          r   !unconstrain_stationary_univariater~     s    4 	!A
!Q{0111AlAacddG1Q32 K Kq 	K 	KA1a41QT71Q!AX;#661qAwz>JAac1fII	K	

A	a!Q$h_AHr   c                 ~   ddl m} g }|t          |           }|| d         j        d         }t	          j        |          }t          |          D ]j}| |         }|                    |t	          j        ||j	                  z   d          \  }}	|
                    |                    |||	                     k|S )a-  
    Transform arbitrary matrices to matrices with singular values less than
    one.

    Parameters
    ----------
    unconstrained : list
        Arbitrary matrices. Should be a list of length `order`, where each
        element is an array sized `k_endog` x `k_endog`.
    order : int, optional
        The order of the autoregression.
    k_endog : int, optional
        The dimension of the data vector.

    Returns
    -------
    constrained : list
        Partial autocorrelation matrices. Should be a list of length
        `order`, where each element is an array sized `k_endog` x `k_endog`.

    See Also
    --------
    constrain_stationary_multivariate

    Notes
    -----
    Corresponds to Lemma 2.2 in Ansley and Kohn (1986). See
    `constrain_stationary_multivariate` for more details.
    r   r,   NTlowerscipyr,   r!   rh   r   r'   r*   
cho_factorr.   r+   appendsolve_triangular)
rt   orderk_endogr,   r|   r'   r5   ABr   s
             r   "_constrain_sv_less_than_one_pythonr   $  s    @ K}M"""(+
&//C5\\ G G!$$S26!QS>>%9$FF56221au2EEFFFFr   c                    ddl m} |t          |           }|| d         j        d         }|s|}t	          j        |          ||z   dz  z  }|g}|g}|g}	g }
g }|                    |d          }|g}|g}t          |          D ]}|
}|}g }
g }|
                    |	                    ||         | |         j
        dd                     t	          j        ||         |
d         j
                  |
d<   |                    |	                    ||         | |         dd                     t	          j        ||         |d         j
                  |d<   t	          j        |
d         ||                   }|	                    |                                j
                   t          |          D ]}|
                    |||         t	          j        |
d	         |||d
z   z
                     z
             |                    |||         t	          j        |d	         |||d
z   z
                     z
             |	|d
z   xx         t	          j        |	|d
z            |||d
z   z
           j
                  z  cc<   |                    ||         t	          j        ||
|         j
                  z
             |                    ||         t	          j        t	          j        ||         ||                   ||         j
                  z
             |                    |                    ||d
z            d                     |                    |                    ||d
z            d                     |d	         }|st          j                            |          }t          j                            |          }t	          j        |t          j                            |                    }t          j                            |          }t          |          D ]3}t	          j        t	          j        ||
|                   |          |
|<   4|
|fS )a  
    Transform matrices with singular values less than one to matrices
    corresponding to a stationary (or invertible) process.

    Parameters
    ----------
    partial_autocorrelations : list
        Partial autocorrelation matrices. Should be a list of length `order`,
        where each element is an array sized `k_endog` x `k_endog`.
    error_variance : ndarray
        The variance / covariance matrix of the error term. Should be sized
        `k_endog` x `k_endog`. This is used as input in the algorithm even if
        is not transformed by it (when `transform_variance` is False). The
        error term variance is required input when transformation is used
        either to force an autoregressive component to be stationary or to
        force a moving average component to be invertible.
    transform_variance : bool, optional
        Whether or not to transform the error variance term. This option is
        not typically used, and the default is False.
    order : int, optional
        The order of the autoregression.
    k_endog : int, optional
        The dimension of the data vector.

    Returns
    -------
    coefficient_matrices : list
        Transformed coefficient matrices leading to a stationary VAR
        representation.

    See Also
    --------
    constrain_stationary_multivariate

    Notes
    -----
    Corresponds to Lemma 2.1 in Ansley and Kohn (1986). See
    `constrain_stationary_multivariate` for more details.
    r   r   N
   Tr   r+   )r   transrz   r   )r   r,   r!   rh   r   r'   choleskyr*   r   r   r+   r.   copyinsertr-   )partial_autocorrelationserror_variancetransform_variancer   r   r,   initial_varianceforward_variancesbackward_variancesautocovariancesforwards	backwardserror_variance_factorforward_factorsbackward_factorsr   prev_forwardsprev_backwardstmprw   varianceinitial_variance_factortransformed_variance_factor	transforminv_transformr5   s                             r   3_compute_coefficients_from_multivariate_pacf_pythonr   T  s   T },--*1-3A6
  A) EGOb+@@'(()%&O HI"OON$OGG,-O-. 5\\ @
 @
 "	 	## #%=a%@%B# $ ' '	( 	( 	( f_Q/!??
 	##"$<Q$?# $ ' '	( 	( 	( v.q19Q<>BB	! fXa["4Q"788sxxzz|,,, q 	E 	EAOOA}Q/"&nQ!W537 37  7 8 8 8 Qq 1BF"}Q!W557 57 !7 8 8 8 AaC   BF?1Q3+?+8AaC+A+C%E %E E     	  a 26#x{}#=#==	
 	
 	
 	!!q!Fy|%6q%9::! 	
 	
 	
 	OO-ac2$O??	
 	
 	
 	OO.qs34O@@	
 	
 	
 	
 !$H  #%)"4"45E"F"F&(i&8&8&B&B#F29==)DEEG G		i00u 	 	Arvi!55}EE QKK Xr   c                    	 t                     t          u }|s+ j        \  	}|	z  }	 fdt          |          D              t	                     } d         j        d         	t           |	          }t          ||||	          \  }}|s-t          j        |d          	                    		|z            }||fS )a  
    Transform unconstrained parameters used by the optimizer to constrained
    parameters used in likelihood evaluation for a vector autoregression.

    Parameters
    ----------
    unconstrained : array or list
        Arbitrary matrices to be transformed to stationary coefficient matrices
        of the VAR. If a list, should be a list of length `order`, where each
        element is an array sized `k_endog` x `k_endog`. If an array, should be
        the matrices horizontally concatenated and sized
        `k_endog` x `k_endog * order`.
    error_variance : ndarray
        The variance / covariance matrix of the error term. Should be sized
        `k_endog` x `k_endog`. This is used as input in the algorithm even if
        is not transformed by it (when `transform_variance` is False). The
        error term variance is required input when transformation is used
        either to force an autoregressive component to be stationary or to
        force a moving average component to be invertible.
    transform_variance : bool, optional
        Whether or not to transform the error variance term. This option is
        not typically used, and the default is False.
    prefix : {'s','d','c','z'}, optional
        The appropriate BLAS prefix to use for the passed datatypes. Only
        use if absolutely sure that the prefix is correct or an error will
        result.

    Returns
    -------
    constrained : array or list
        Transformed coefficient matrices leading to a stationary VAR
        representation. Will match the type of the passed `unconstrained`
        variable (so if a list was passed, a list will be returned).

    Notes
    -----
    In the notation of [1]_, the arguments `(variance, unconstrained)` are
    written as :math:`(\Sigma, A_1, \dots, A_p)`, where :math:`p` is the order
    of the vector autoregression, and is here determined by the length of
    the `unconstrained` argument.

    There are two steps in the constraining algorithm.

    First, :math:`(A_1, \dots, A_p)` are transformed into
    :math:`(P_1, \dots, P_p)` via Lemma 2.2 of [1]_.

    Second, :math:`(\Sigma, P_1, \dots, P_p)` are transformed into
    :math:`(\Sigma, \phi_1, \dots, \phi_p)` via Lemmas 2.1 and 2.3 of [1]_.

    If `transform_variance=True`, then only Lemma 2.1 is applied in the second
    step.

    While this function can be used even in the univariate case, it is much
    slower, so in that case `constrain_stationary_univariate` is preferred.

    References
    ----------
    .. [1] Ansley, Craig F., and Robert Kohn. 1986.
       "A Note on Reparameterizing a Vector Autoregressive Moving Average Model
       to Enforce Stationarity."
       Journal of Statistical Computation and Simulation 24 (2): 99-106.
    .. [*] Ansley, Craig F, and Paul Newbold. 1979.
       "Multivariate Partial Autocorrelations."
       In Proceedings of the Business and Economic Statistics Section, 349-53.
       American Statistical Association
    c                 >    g | ]}d |z  |dz   z  f         S Nr   rI   )rF   r5   r   rt   s     r   rG   z<constrain_stationary_multivariate_python.<locals>.<listcomp>L  sH     
 
 
 (7(AgIqsGm$;;<
 
 
r   r   r   r8   )
typer#   rh   r*   r!   r   r   r   rZ   reshape)
rt   r   r   prefixuse_listr   sv_constrainedr|   varr   s
   `        @r   (constrain_stationary_multivariate_pythonr     s   L M""d*H 
&,'
 
 
 
 
5\\
 
 

 EA$Q'G 8ug' 'N K(:E7L LK  &n[q999AAWu_& & r   c                 v  	
 t          |           t          u }|rt          j        | d          } | j        \  
}|
z  }|dk     rt          d          
dk     rt          d          |t          | |g          \  }}}t          |         }t          j        | |          } t          j        ||          }t          |         | |
          }t          |         ||||
          \  	}t          j        	|          	t          j        ||          }|r	
fdt          |          D             		|fS )Nr   r8   zMust have order at least 1z(Must have at least 1 endogenous variabler   c                 >    g | ]}d |z  |dz   z  f         S r   rI   rF   r5   r|   r   s     r   rG   z5constrain_stationary_multivariate.<locals>.<listcomp>  H     
 
 
 !G)QqS'M"99:
 
 
r   )r   r#   r   rZ   rh   r"   r   prefix_dtype_mapasfortranarrayprefix_sv_mapprefix_pacf_maparrayr*   )rt   r   r   r   r   r   r   _r   r|   r   s            @@r   !constrain_stationary_multivariater   f  s   
 M""d*H >}1==="(NGU	gEqyy5666{{CDDD~.H%' 'qV$E%m5AAAM 777H #6*=%IIN
 ,F3"4eWF FK (;e444Kx...H 

 
 
 
 
5\\
 
 

   r   c                 ~   ddl m} g }|t          |           }|| d         j        d         }t	          j        |          }t          |          D ]j}| |         }|                    |t	          j        ||j	                  z
  d          \  }}	|
                    |                    |||	                     k|S )a>  
    Transform matrices with singular values less than one to arbitrary
    matrices.

    Parameters
    ----------
    constrained : list
        The partial autocorrelation matrices. Should be a list of length
        `order`, where each element is an array sized `k_endog` x `k_endog`.
    order : int, optional
        The order of the autoregression.
    k_endog : int, optional
        The dimension of the data vector.

    Returns
    -------
    unconstrained : list
        Unconstrained matrices. A list of length `order`, where each element is
        an array sized `k_endog` x `k_endog`.

    See Also
    --------
    unconstrain_stationary_multivariate

    Notes
    -----
    Corresponds to the inverse of Lemma 2.2 in Ansley and Kohn (1986). See
    `unconstrain_stationary_multivariate` for more details.
    r   r   NTr   r   )
r|   r   r   r,   rt   r'   r5   PB_invr   s
             r   _unconstrain_sv_less_than_oner     s    < M}K  a.&q)
&//C5\\ M MN((rva~~)=T(JJu 	V44UAU4KKLLLLr   c                    t          j        |           } | j        dk    r| ddt           j        f         } | t          j        | d          z  } | j        \  }}g }t          |dz             D ]}|                    t          j        ||f                     t          ||z
            D ]4}||xx         t          j	        | |         | ||z                      z  cc<   5||xx         |z  cc<   |S )a  
    Computer multivariate sample autocovariances

    Parameters
    ----------
    endog : array_like
        Sample data on which to compute sample autocovariances. Shaped
        `nobs` x `k_endog`.
    maxlag : int
        Maximum lag to use when computing the sample autocovariances.

    Returns
    -------
    sample_autocovariances : list
        A list of the first `maxlag` sample autocovariance matrices. Each
        matrix is shaped `k_endog` x `k_endog`.

    Notes
    -----
    This function computes the forward sample autocovariances:

    .. math::

        \hat \Gamma(s) = \frac{1}{n} \sum_{t=1}^{n-s}
        (Z_t - \bar Z) (Z_{t+s} - \bar Z)'

    See page 353 of Wei (1990). This function is primarily implemented for
    checking the partial autocorrelation functions below, and so is quite slow.

    References
    ----------
    .. [*] Wei, William. 1990.
       Time Series Analysis : Univariate and Multivariate Methods. Boston:
       Pearson.
    r   Nr   r8   )
r   r   rJ   newaxismeanrh   r*   r   r(   outer)endogmaxlagnobsr   sample_autocovariancesr   ts          r   "_compute_multivariate_sample_acovfr     s   J HUOOEzQaaam$	RWU####E KMD'6A: * *%%bh/A&B&BCCCtax 	H 	HA"1%%%%(E!A#J)G)GG%%%%q!!!T)!!!!!!r   c                     
 ddl m} t                     t          u r#t	                     } d         j        d         
n+ j        \  
}|
z  } 
fdt          |          D              ||dz
  }t          dg fdt          |          D             z             j        }t          j
        |j                  }||d
d
f<   |                    ||          
fdt          t          ||dz                       D             }t          ||dz
  z
            D ]*}	t          j        |          |d

 df         gz  }+|r/t          t	          |                    D ]}	||	         j        ||	<   |S )a  
    Compute multivariate autocovariances from vector autoregression coefficient
    matrices

    Parameters
    ----------
    coefficients : array or list
        The coefficients matrices. If a list, should be a list of length
        `order`, where each element is an array sized `k_endog` x `k_endog`. If
        an array, should be the coefficient matrices horizontally concatenated
        and sized `k_endog` x `k_endog * order`.
    error_variance : ndarray
        The variance / covariance matrix of the error term. Should be sized
        `k_endog` x `k_endog`.
    maxlag : int, optional
        The maximum autocovariance to compute. Default is `order`-1. Can be
        zero, in which case it returns the variance.
    forward_autocovariances : bool, optional
        Whether or not to compute forward autocovariances
        :math:`E(y_t y_{t+j}')`. Default is False, so that backward
        autocovariances :math:`E(y_t y_{t-j}')` are returned.

    Returns
    -------
    autocovariances : list
        A list of the first `maxlag` autocovariance matrices. Each matrix is
        shaped `k_endog` x `k_endog`.

    Notes
    -----
    Computes

    .. math::

        \Gamma(j) = E(y_t y_{t-j}')

    for j = 1, ..., `maxlag`, unless `forward_autocovariances` is specified,
    in which case it computes:

    .. math::

        E(y_t y_{t+j}') = \Gamma(j)'

    Coefficients are assumed to be provided from the VAR model:

    .. math::
        y_t = A_1 y_{t-1} + \dots + A_p y_{t-p} + \varepsilon_t

    Autocovariances are calculated by solving the associated discrete Lyapunov
    equation of the state space representation of the VAR process.
    r   r   c                 >    g | ]}d |z  |dz   z  f         S r   rI   )rF   r5   coefficientsr   s     r   rG   zA_compute_multivariate_acovf_from_coefficients.<locals>.<listcomp>@  sH     
 
 
 '1W9ac7]#::;
 
 
r   Nr   c                 F    g | ]}t          j        |                    S rI   )r   squeeze)rF   r5   r   s     r   rG   zA_compute_multivariate_acovf_from_coefficients.<locals>.<listcomp>L  s*    BBB
<?+++BBBr   c                 >    g | ]}d |z  |dz   z  f         S r   rI   )rF   r5   r   stacked_covs     r   rG   zA_compute_multivariate_acovf_from_coefficients.<locals>.<listcomp>Y  sH        	HWHai1g556  r   )r   r,   r   r#   r!   rh   r*   r6   r+   r   r(   rq   minr.   )r   r   r   forward_autocovariancesr,   r   	companionselected_variancer   r5   r   r   s   `         @@r   -_compute_multivariate_acovf_from_coefficientsr     s
   l  LT!!L!!q/'*%+'
 
 
 
 
5\\
 
 

 ~q
 !	
BBBBU5\\BBBB  
 11,:hwh() 00<MNNK
    s5&(++,,  O
 6U1W%&& 
 
fY447())+,
 	
  6s?++,, 	6 	6A!0!3!5OAr   c                 @    t          | |          }t          |          S )a  
    Computer multivariate sample partial autocorrelations

    Parameters
    ----------
    endog : array_like
        Sample data on which to compute sample autocovariances. Shaped
        `nobs` x `k_endog`.
    maxlag : int
        Maximum lag for which to calculate sample partial autocorrelations.

    Returns
    -------
    sample_pacf : list
        A list of the first `maxlag` sample partial autocorrelation matrices.
        Each matrix is shaped `k_endog` x `k_endog`.
    )r   /_compute_multivariate_pacf_from_autocovariances)r   r   r   s      r   !_compute_multivariate_sample_pacfr   k  s*    $ @vNN:     r   c                    ddl m} |t          |           dz
  }|| d         j        d         }g }g }g }g }g }g }	g }
t	          |          D ]}t          |          }t          |          }g }g }| d                                         }| d         j                                        }t	          |          D ]U}|t          j	        ||         | |dz                      z  }|t          j	        ||         | |dz            j                  z  }V|
                    |           |
                    |           |
                    |                    ||         d                     |	
                    |                    ||         d                     |dk    r~|
                    |                    |d         df| d                   j                   |
                    |                    |	d         df| d         j                  j                   n| |dz            j                                        }t	          |          D ].}|t          j	        ||         | ||z
           j                  z  }/|
                    |                    |	|         df|j                  j                   |
                    |                    ||         df|          j                   t	          |          D ]}|                    |||         t          j	        |d         |||dz   z
                     z
             |                    |||         t          j	        |d         |||dz   z
                     z
             |

                    |                    ||         t          j	        ||         |	|                   d                     |
S )a  
    Compute multivariate partial autocorrelations from autocovariances.

    Parameters
    ----------
    autocovariances : list
        Autocorrelations matrices. Should be a list of length `order` + 1,
        where each element is an array sized `k_endog` x `k_endog`.
    order : int, optional
        The order of the autoregression.
    k_endog : int, optional
        The dimension of the data vector.

    Returns
    -------
    pacf : list
        List of first `order` multivariate partial autocorrelations.

    See Also
    --------
    unconstrain_stationary_multivariate

    Notes
    -----
    Note that this computes multivariate partial autocorrelations.

    Corresponds to the inverse of Lemma 2.1 in Ansley and Kohn (1986). See
    `unconstrain_stationary_multivariate` for more details.

    Computes sample partial autocorrelations if sample autocovariances are
    given.
    r   r   Nr   Tr   rz   )r   r,   r!   rh   r*   r#   r   r+   r   r.   r   r   	cho_solver   r   )r   r   r   r,   r   r   r   r   r   r   r   r   r   r   forward_variancebackward_variancerw   tmp_sums                     r   r   r     su   D }O$$Q&!!$*1-  HIO
  " 5\\ P PXi	 +1-2244+A.05577q 	@ 	@A}Q'7'6qs';!= != =q(9(7!(<(>"@ "@ @ 	  !1222!!"3444 	OO-a0O==	
 	
 	
 	OO.q1O>>	
 	
 	

 66 OOF,, #T*OA,>@ @@AC C C V--!!$d+_Q-?-AC CCDF F F F
 &ac*,1133G1XX L L26-"2OAaC4H4JKKK OOF,,!!$d+WY8 889; ; ; V-- #T*G5 5568 8 8
 q 	8 	8AOOA}Q/"&nQ!W537 37  7 8 8 8Qq 1BF"}Q!W557 57 !7 8 8 8 8 	!''(?(?Ax{4DQ4G H H )@ ) ) 	 	 	 	 $#r   c                     t          |           t          u r#t          |           }| d         j        d         }n| j        \  }}||z  }t          }d  || ||          D             }t          |          S )a$  
    Transform matrices corresponding to a stationary (or invertible) process
    to matrices with singular values less than one.

    Parameters
    ----------
    constrained : array or list
        The coefficients matrices. If a list, should be a list of length
        `order`, where each element is an array sized `k_endog` x `k_endog`. If
        an array, should be the coefficient matrices horizontally concatenated
        and sized `k_endog` x `k_endog * order`.
    error_variance : ndarray
        The variance / covariance matrix of the error term. Should be sized
        `k_endog` x `k_endog`.
    order : int, optional
        The order of the autoregression.
    k_endog : int, optional
        The dimension of the data vector.

    Returns
    -------
    pacf : list
        List of first `order` multivariate partial autocorrelations.

    See Also
    --------
    unconstrain_stationary_multivariate

    Notes
    -----
    Note that this computes multivariate partial autocorrelations.

    Corresponds to the inverse of Lemma 2.1 in Ansley and Kohn (1986). See
    `unconstrain_stationary_multivariate` for more details.

    Notes
    -----
    Coefficients are assumed to be provided from the VAR model:

    .. math::
        y_t = A_1 y_{t-1} + \dots + A_p y_{t-p} + \varepsilon_t
    r   c                     g | ]	}|j         
S rI   )r+   )rF   autocovariances     r   rG   z@_compute_multivariate_pacf_from_coefficients.<locals>.<listcomp>\  s(     ; ; ;+; ; ;r   )r   )r   r#   r!   rh   r   r   )r|   r   r   r   _acovfr   s         r   ,_compute_multivariate_pacf_from_coefficientsr   #  s    Z KD  K  a.&q)$*'
 ;F; ;{N5999; ; ;O ;?KKKr   c                 P    t                     t          u }|s, j        \  }|z  } fdt          |          D              n"t	                     } d         j        d         t           ||          }t          ||          }|st          j        |d          }||fS )a  
    Transform constrained parameters used in likelihood evaluation
    to unconstrained parameters used by the optimizer

    Parameters
    ----------
    constrained : array or list
        Constrained parameters of, e.g., an autoregressive or moving average
        component, to be transformed to arbitrary parameters used by the
        optimizer. If a list, should be a list of length `order`, where each
        element is an array sized `k_endog` x `k_endog`. If an array, should be
        the coefficient matrices horizontally concatenated and sized
        `k_endog` x `k_endog * order`.
    error_variance : ndarray
        The variance / covariance matrix of the error term. Should be sized
        `k_endog` x `k_endog`. This is used as input in the algorithm even if
        is not transformed by it (when `transform_variance` is False).

    Returns
    -------
    unconstrained : ndarray
        Unconstrained parameters used by the optimizer, to be transformed to
        stationary coefficients of, e.g., an autoregressive or moving average
        component. Will match the type of the passed `constrained`
        variable (so if a list was passed, a list will be returned).

    Notes
    -----
    Uses the list representation internally, even if an array is passed.

    References
    ----------
    .. [*] Ansley, Craig F., and Robert Kohn. 1986.
       "A Note on Reparameterizing a Vector Autoregressive Moving Average Model
       to Enforce Stationarity."
       Journal of Statistical Computation and Simulation 24 (2): 99-106.
    c                 >    g | ]}d |z  |dz   z  f         S r   rI   r   s     r   rG   z7unconstrain_stationary_multivariate.<locals>.<listcomp>  r   r   r   r   r8   )	r   r#   rh   r*   r!   r   r   r   rZ   )r|   r   r   r   r   rt   r   s   `     @r   #unconstrain_stationary_multivariater   c  s    L K  D(H 
*$*'
 
 
 
 
5\\
 
 

 K  a.&q)
  L^UG 5  5
 2 %2 2M  >}1===.((r   c                    t          |          }|dvrt          d| |fz            |d         |k    st          d| ||d         fz            |d         |k    st          d| ||d         fz            |$|dk    s|d	         dk    st          d
| z            |dk    r0|0|d	         d|fvr&t          d| |t          |          fz            dS dS dS )a  
    Validate the shape of a possibly time-varying matrix, or raise an exception

    Parameters
    ----------
    name : str
        The name of the matrix being validated (used in exception messages)
    shape : array_like
        The shape of the matrix to be validated. May be of size 2 or (if
        the matrix is time-varying) 3.
    nrows : int
        The expected number of rows.
    ncols : int
        The expected number of columns.
    nobs : int
        The number of observations (used to validate the last dimension of a
        time-varying matrix)

    Raises
    ------
    ValueError
        If the matrix is not of the desired shape.
    )rK      zTInvalid value for %s matrix. Requires a 2- or 3-dimensional array, got %d dimensionsr   z:Invalid dimensions for %s matrix: requires %d rows, got %dr   z=Invalid dimensions for %s matrix: requires %d columns, got %dNrK   rz   zInvalid dimensions for %s matrix: time-varying matrices cannot be given unless `nobs` is specified (implicitly when a dataset is bound or else set explicity)r   zNInvalid dimensions for time-varying %s matrix. Requires shape (*,*,%d), got %sr!   r"   str)rP   rh   nrowsncolsr   rJ   s         r   validate_matrix_shaper     sZ   0 u::D 6 I& ' ' 	' 8u ),0%q+BC D D 	D8u ,/3UE!H.EF G G 	G |TQYY%)q.. ' *.. / / 	/ qyyT%%)At9*D*D Dc%jj12 3 3 	3 y%%*D*Dr   c                 Z   t          |          }|dvrt          d| |fz            |d         |k    st          d| ||d         fz            |$|dk    s|d         dk    st          d| z            |d	k    r.|d         d|fvr$t          d
| |t          |          fz            dS dS )av  
    Validate the shape of a possibly time-varying vector, or raise an exception

    Parameters
    ----------
    name : str
        The name of the vector being validated (used in exception messages)
    shape : array_like
        The shape of the vector to be validated. May be of size 1 or (if
        the vector is time-varying) 2.
    nrows : int
        The expected number of rows (elements of the vector).
    nobs : int
        The number of observations (used to validate the last dimension of a
        time-varying vector)

    Raises
    ------
    ValueError
        If the vector is not of the desired shape.
    )r   rK   zTInvalid value for %s vector. Requires a 1- or 2-dimensional array, got %d dimensionsr   z:Invalid dimensions for %s vector: requires %d rows, got %dNr   rz   zInvalid dimensions for %s vector: time-varying vectors cannot be given unless `nobs` is specified (implicitly when a dataset is bound or else set explicity)rK   zLInvalid dimensions for time-varying %s vector. Requires shape (*,%d), got %sr   )rP   rh   r   r   rJ   s        r   validate_vector_shaper     s   , u::D6 I& ' ' 	' 8u ),0%q+BC D D 	D |TQYY%)q.. ' *.. / / 	/ qyyU1XaY.. Bc%jj12 3 3 	3 y..r   c                     |t          | f          d         }t          |         }|st          j        | d          }  || t          j        |          |||           | S )a  
    Reorder the rows or columns of a time-varying matrix where all non-missing
    values are in the upper left corner of the matrix.

    Parameters
    ----------
    matrix : array_like
        The matrix to be reordered. Must have shape (n, m, nobs).
    missing : array_like of bool
        The vector of missing indices. Must have shape (k, nobs) where `k = n`
        if `reorder_rows is True` and `k = m` if `reorder_cols is True`.
    reorder_rows : bool, optional
        Whether or not the rows of the matrix should be re-ordered. Default
        is False.
    reorder_cols : bool, optional
        Whether or not the columns of the matrix should be re-ordered. Default
        is False.
    is_diagonal : bool, optional
        Whether or not the matrix is diagonal. If this is True, must also have
        `n = m`. Default is False.
    inplace : bool, optional
        Whether or not to reorder the matrix in-place.
    prefix : {'s', 'd', 'c', 'z'}, optional
        The Fortran prefix of the vector. Default is to automatically detect
        the dtype. This parameter should only be used with caution.

    Returns
    -------
    reordered_matrix : array_like
        The reordered matrix.
    Nr   Fr   )r   !prefix_reorder_missing_matrix_mapr   r   r   )r3   missingreorder_rowsreorder_colsis_diagonalinplacer   reorders           r   reorder_missing_matrixr     su    D ~$fY//2/7G ,s+++GFB%g..l   Mr   c                     |t          | f          d         }t          |         }|st          j        | d          }  || t          j        |                     | S )a  
    Reorder the elements of a time-varying vector where all non-missing
    values are in the first elements of the vector.

    Parameters
    ----------
    vector : array_like
        The vector to be reordered. Must have shape (n, nobs).
    missing : array_like of bool
        The vector of missing indices. Must have shape (n, nobs).
    inplace : bool, optional
        Whether or not to reorder the matrix in-place. Default is False.
    prefix : {'s', 'd', 'c', 'z'}, optional
        The Fortran prefix of the vector. Default is to automatically detect
        the dtype. This parameter should only be used with caution.

    Returns
    -------
    reordered_vector : array_like
        The reordered vector.
    Nr   r   r   )r   !prefix_reorder_missing_vector_mapr   r   r   )vectorr   r   r   r   s        r   reorder_missing_vectorr   :  se    , ~$fY//2/7G ,s+++GFB%g..///Mr   c                 d   |t          | |f          d         }t          |         }|st          j        |d          }	 |                                 st                      n+# t          t
          f$ r t          j        |           } Y nw xY w || |t          j        |          |||           |S )aT  
    Copy the rows or columns of a time-varying matrix where all non-missing
    values are in the upper left corner of the matrix.

    Parameters
    ----------
    A : array_like
        The matrix from which to copy. Must have shape (n, m, nobs) or
        (n, m, 1).
    B : array_like
        The matrix to copy to. Must have shape (n, m, nobs).
    missing : array_like of bool
        The vector of missing indices. Must have shape (k, nobs) where `k = n`
        if `reorder_rows is True` and `k = m` if `reorder_cols is True`.
    missing_rows : bool, optional
        Whether or not the rows of the matrix are a missing dimension. Default
        is False.
    missing_cols : bool, optional
        Whether or not the columns of the matrix are a missing dimension.
        Default is False.
    is_diagonal : bool, optional
        Whether or not the matrix is diagonal. If this is True, must also have
        `n = m`. Default is False.
    inplace : bool, optional
        Whether or not to copy to B in-place. Default is False.
    prefix : {'s', 'd', 'c', 'z'}, optional
        The Fortran prefix of the vector. Default is to automatically detect
        the dtype. This parameter should only be used with caution.

    Returns
    -------
    copied_matrix : array_like
        The matrix B with the non-missing submatrix of A copied onto it.
    Nr   r   r   )r   prefix_copy_missing_matrix_mapr   r   is_f_contigr"   AttributeErrorr   )	r   r   r   missing_rowsmissing_colsr   r   r   r   s	            r   copy_missing_matrixr  \  s    H ~$aV,,Q/)&1D "GAS!!!!}} 	,,	J' ! ! !a  ! 	DAr ))<	   H    "A# #%B
Bc                 ^   |t          | |f          d         }t          |         }|st          j        |d          }	 |                                 st                      n+# t          t
          f$ r t          j        |           } Y nw xY w || |t          j        |                     |S )aJ  
    Reorder the elements of a time-varying vector where all non-missing
    values are in the first elements of the vector.

    Parameters
    ----------
    a : array_like
        The vector from which to copy. Must have shape (n, nobs) or (n, 1).
    b : array_like
        The vector to copy to. Must have shape (n, nobs).
    missing : array_like of bool
        The vector of missing indices. Must have shape (n, nobs).
    inplace : bool, optional
        Whether or not to copy to b in-place. Default is False.
    prefix : {'s', 'd', 'c', 'z'}, optional
        The Fortran prefix of the vector. Default is to automatically detect
        the dtype. This parameter should only be used with caution.

    Returns
    -------
    copied_vector : array_like
        The vector b with the non-missing subvector of b copied onto it.
    Nr   r   r   )r   prefix_copy_missing_vector_mapr   r   r  r"   r  r   )rk   rp   r   r   r   r   s         r   copy_missing_vectorr	    s    0 ~$aV,,Q/)&1D "GAS!!!!}} 	,,	J' ! ! !a  ! 	DAr ))***Hr  c                 d   |t          | |f          d         }t          |         }|st          j        |d          }	 |                                 st                      n+# t          t
          f$ r t          j        |           } Y nw xY w || |t          j        |          |||           |S )aD  
    Copy the rows or columns of a time-varying matrix where all non-index
    values are in the upper left corner of the matrix.

    Parameters
    ----------
    A : array_like
        The matrix from which to copy. Must have shape (n, m, nobs) or
        (n, m, 1).
    B : array_like
        The matrix to copy to. Must have shape (n, m, nobs).
    index : array_like of bool
        The vector of index indices. Must have shape (k, nobs) where `k = n`
        if `reorder_rows is True` and `k = m` if `reorder_cols is True`.
    index_rows : bool, optional
        Whether or not the rows of the matrix are a index dimension. Default
        is False.
    index_cols : bool, optional
        Whether or not the columns of the matrix are a index dimension.
        Default is False.
    is_diagonal : bool, optional
        Whether or not the matrix is diagonal. If this is True, must also have
        `n = m`. Default is False.
    inplace : bool, optional
        Whether or not to copy to B in-place. Default is False.
    prefix : {'s', 'd', 'c', 'z'}, optional
        The Fortran prefix of the vector. Default is to automatically detect
        the dtype. This parameter should only be used with caution.

    Returns
    -------
    copied_matrix : array_like
        The matrix B with the non-index submatrix of A copied onto it.
    Nr   r   r   )r   prefix_copy_index_matrix_mapr   r   r  r"   r  r   )	r   r   rX   
index_rows
index_colsr   r   r   r   s	            r   copy_index_matrixr    s    H ~$aV,,Q/'/D "GAS!!!!}} 	,,	J' ! ! !a  ! 	DAr ''Z	   Hr  c                 ^   |t          | |f          d         }t          |         }|st          j        |d          }	 |                                 st                      n+# t          t
          f$ r t          j        |           } Y nw xY w || |t          j        |                     |S )aB  
    Reorder the elements of a time-varying vector where all non-index
    values are in the first elements of the vector.

    Parameters
    ----------
    a : array_like
        The vector from which to copy. Must have shape (n, nobs) or (n, 1).
    b : array_like
        The vector to copy to. Must have shape (n, nobs).
    index : array_like of bool
        The vector of index indices. Must have shape (n, nobs).
    inplace : bool, optional
        Whether or not to copy to b in-place. Default is False.
    prefix : {'s', 'd', 'c', 'z'}, optional
        The Fortran prefix of the vector. Default is to automatically detect
        the dtype. This parameter should only be used with caution.

    Returns
    -------
    copied_vector : array_like
        The vector b with the non-index subvector of b copied onto it.
    Nr   r   r   )r   prefix_copy_index_vector_mapr   r   r  r"   r  r   )rk   rp   rX   r   r   r   s         r   copy_index_vectorr    s    0 ~$aV,,Q/'/D "GAS!!!!}} 	,,	J' ! ! !a  ! 	DAr ''(((Hr  c                     d}| at          | d           }|st          j        |           } | j        dk    r#|s| d d d f         } nt	          j        |           } | j        d         }|| fS Nr   r   )r   r   asarrayrJ   rT   rU   rh   )exogk_exogexog_is_using_pandass      r   prepare_exogr  &  s    F/d;;# 	$:d##D 9>>' *AAAtG}|D))AD>r   c                    | | dk    rt          j        d          }n| dk    rt           j        d         }n| dk    rt           j        d         }n| dk    rt           j        d         }ni| d	k    rt           j        d
         }nPt          j        |           } | j        dk    r| dk                        t                    }nt          d|            t          t          j        |                    }||fS )Nr1   r   r   r   r   )r   r   ct)r   r   ctt)r   r   r   zValid trend inputs are 'c' (constant), 't' (linear trend in time), 'ct' (both), 'ctt' (both with trend squared) or an interable defining a polynomial, e.g., [1, 1, 0, 1] is `a + b*t + ct**3`. Received )	r   onesrL   r   rJ   astyper   r"   sum)trendpolynomial_trendk_trends      r   prepare_trend_specr"  8  s    }71::	#58	#5;	$5;	%5>:>> %	11#662 +02 2   "&)**++GW$$r   c                    t          j        |||z             }t          j        ||f          }d}|                                 d         D ]5}|dk    rt          j        |          |d d |f<   n||z  |d d |f<   |dz  }6|S r  )r   aranger(   nonzeror  )r   r!  r   offset
time_trend
trend_datar5   rw   s           r   prepare_trend_datar)  Y  s     64&=11J4/**J	A%%''*  66!wt~~Jqqq!t)1}Jqqq!t	Qr   c                     	 t           j                            |           S # t           j        j        $ rC t          j        t          j        |                     rt           j        cY S t           j        cY S w xY w)z3Compute condition while protecting from LinAlgError)r   r,   condLinAlgErroranyisnannaninf)rk   s    r   
_safe_condr1  i  sk    y~~a   9    6"(1++ 	6MMM6MMM	s   ! AA8)A87A8      ?c                 B   | j         }| j        }| j        }t          | j                 }|t          j        | j                  }|t          j        | j                  }t          j        t          j	        |          
                    t
          j                            }|                                 t          j        t          j	        |          
                    t
          j                            }|                                 ||d         dk    }|r|d         dk    rt          d           |||||||t          |                    \  }	}
}}t          |d         |d                   }t          j        | j        d d |d f                   }t          j        |          r|	j        }t          j        |	                    dddd                              |d         |d         z  |d         |d         d                    }	t          j        |
                    t
          j                            }t/          |	|dd	           |	                    |d         |d         |d         |d                                       dddd          }	n|	                    dddd          }	|
                    dddd          }
|                    ddd          }t          j        ||z
  ||z
            }|	|         }	|
|         }
|r|||z
           }|	|
|fS )
Nr   z[If `compute_prior_weights` is set to True, then `compute_j` must include the time period 0.rK   r   r   Cr   T)r   r   )_statespacer   r   )prefix_compute_smoothed_state_weights_mapr   r   r$  r   uniquerN   r  int32sortr"   boolr   r.  r   r-  rh   r   rj   r   r   ix_)ssm	compute_t	compute_jcompute_prior_weightsscale_model_kfilter	_smootherfuncweightsstate_intercept_weightsprior_weightsr   t0r   rh   ix_tjs                    r   _compute_smoothed_state_weightsrJ  t  s     _F!H$I 5SZ@D Ich''	Ich''		"-	2299"(CCDDINN	"-	2299"(CCDDINN $ )! 1 I1!2!2 H I I 	I :>8VY	5"##:% :%6G$mQ 
Yq\9Q<	(	(BhsyBCC())G	vg 0 #G$5$5aAq$A$A$I$I!HuQxq583 %J %@ %@ A A#GNN28$<$<==wd'+	- 	- 	- 	- ??58U1XuQxqJJ$9Q1a00 	 ##Aq!Q// 6??1aKK "++Aq!44M F9r>9r>22EenG5e< 6%i"n5+]::r   c                 Z   | j         }|                    | j                   |,t          j        | j        |j        j        j        k              }|r|j                            dddd           n|j        	                                 t          |j        |||| j        j                  S )a  
    Construct the weights of observations and the prior on the smoothed state

    Parameters
    ----------
    results : MLEResults object
        Results object from fitting a state space model.
    compute_t : array_like, optional
        An explicit list of periods `t` of the smoothed state vector to compute
        weights for (see the Returns section for more details about the
        dimension `t`). Default is to compute weights for all periods `t`.
        However, if weights for only a few time points are desired, then
        performance can be improved by specifying this argument.
    compute_j : array_like, optional
        An explicit list of periods `j` of observations to compute
        weights for (see the Returns section for more details about the
        dimension `j`). Default is to compute weights for all periods `j`.
        However, if weights for only a few time points are desired, then
        performance can be improved by specifying this argument.
    compute_prior_weights : bool, optional
        Whether or not to compute the weight matrices associated with the prior
        mean (also called the "initial state"). Note that doing so requires
        that period 0 is in the periods defined in `compute_j`. Default is True
        if 0 is in `compute_j` (or if the `compute_j` argument is not passed)
        and False otherwise.
    resmooth : bool, optional
        Whether or not to re-perform filtering and smoothing prior to
        constructing the weights. Default is to resmooth if the smoothed_state
        vector is different between the given results object and the
        underlying smoother. Caution is adviced when changing this setting.
        See the Notes section below for more details.

    Returns
    -------
    weights : array_like
        Weight matrices that can be used to construct the smoothed state from
        the observations. The returned matrix is always shaped
        `(nobs, nobs, k_states, k_endog)`, and entries that are not computed
        are set to NaNs. (Entries will not be computed if they are not
        included in `compute_t` and `compute_j`, or if they correspond to
        missing observations, or if they are for periods in which the exact
        diffuse Kalman filter is operative). The `(t, j, m, p)`-th element of
        this matrix contains the weight of the `p`-th element of the
        observation vector at time `j` in constructing the `m`-th element of
        the smoothed state vector at time `t`.
    prior_weights : array_like
        Weight matrices that describe the impact of the prior (also called the
        initialization) on the smoothed state vector. The returned matrix is
        always shaped `(nobs, k_states, k_states)`. If prior weights are not
        computed, then all entries will be set to NaNs. The `(t, m, l)`-th
        element of this matrix contains the weight of the `l`-th element of the
        prior mean (also called the "initial state") in constructing the
        `m`-th element of the smoothed state vector at time `t`.

    Notes
    -----
    In [1]_, Chapter 4.8, it is shown how the smoothed state vector can be
    written as a weighted vector sum of observations:

    .. math::

        \hat \alpha_t = \sum_{j=1}^n \omega_{jt}^{\hat \alpha} y_j

    One output of this function is the weights
    :math:`\omega_{jt}^{\hat \alpha}`. Note that the description in [1]_
    assumes that the prior mean (or "initial state") is fixed to be zero. More
    generally, the smoothed state vector will also depend partly on the prior.
    The second output of this function are the weights of the prior mean.

    There are two important technical notes about the computations used here:

    1. In the univariate approach to multivariate filtering (see e.g.
       Chapter 6.4 of [1]_), all observations are introduced one at a time,
       including those from the same time period. As a result, the weight of
       each observation can be different than when all observations from the
       same time point are introduced together, as in the typical multivariate
       filtering approach. Here, we always compute weights as in the
       multivariate filtering approach, and we handle singular forecast error
       covariance matrices by using a pseudo-inverse.
    2. Constructing observation weights for periods in which the exact diffuse
       filter (see e.g. Chapter 5 of [1]_) is operative is not done here, and
       so the corresponding entries in the returned weight matrices will always
       be set equal to zeros. While handling these periods may be implemented
       in the future, one option for constructing these weights is to use an
       approximate (instead of exact) diffuse initialization for this purpose.

    Finally, one note about implementation: to compute the weights, we use
    attributes of the underlying filtering and smoothing Cython objects
    directly. However, these objects are not frozen with the result
    computation, and we cannot guarantee that their attributes have not
    changed since `res` was created. As a result, by default we re-run the
    filter and smoother to ensure that the attributes there actually correspond
    to the `res` object. This can be overridden by the user for a small
    performance boost if they are sure that the attributes have not changed;
    see the `resmooth` argument.

    References
    ----------
    .. [1] Durbin, James, and Siem Jan Koopman. 2012.
            Time Series Analysis by State Space Methods: Second Edition.
            Oxford University Press.
    Nr   F)conserve_memoryupdate_representationupdate_filterupdate_smoother)r=  r>  r?  r@  )modelupdateparamsr   r-  smoothed_stater<  r   smooth_initialize_representationrJ  filter_resultsr@  )resultsr=  r>  r?  resmoothmods         r   compute_smoothed_state_weightsrZ    s    R -CJJw~ 6'0'2AB C C  -q%*E 	 	C 	C 	C 	C 	**,,,*9	3$*, , , ,r   c                    ||||t          d          |}d}|||| j        dz
  }| j        dz
  }t          |du           t          |du           z   t          |du           z   dk    rt          d          |&|$|                    ||          \  }}}}||dz
  z   }n-|&|$|                    ||          \  }}}}||dz
  z
  }n||	 |                    ||          \  }}}}||z   }|||fS )a{	  
    Compute start/end periods and an index, often for impacts of data updates

    Parameters
    ----------
    previous_model : MLEModel
        Model used to compute default start/end periods if None are given.
        In the case of computing impacts of data updates, this would be the
        model estimated with the previous dataset. Otherwise, can be the same
        as `updated_model`.
    updated_model : MLEModel
        Model used to compute the index. In the case of computing impacts of
        data updates, this would be the model estimated with the updated
        dataset. Otherwise, can be the same as `previous_model`.
    impact_date : {int, str, datetime}, optional
        Specific individual impact date. Cannot be used in combination with
        `start`, `end`, or `periods`.
    start : {int, str, datetime}, optional
        Starting point of the impact dates. If given, one of `end` or `periods`
        must also be given. If a negative integer, will be computed relative to
        the dates in the `updated_model` index. Cannot be used in combination
        with `impact_date`.
    end : {int, str, datetime}, optional
        Ending point of the impact dates. If given, one of `start` or `periods`
        must also be given. If a negative integer, will be computed relative to
        the dates in the `updated_model` index. Cannot be used in combination
        with `impact_date`.
    periods : int, optional
        Number of impact date periods. If given, one of `start` or `end`
        must also be given. Cannot be used in combination with `impact_date`.

    Returns
    -------
    start : int
        Integer location of the first included impact dates.
    end : int
        Integer location of the last included impact dates (i.e. this integer
        location is included in the returned `index`).
    index : pd.Index
        Index associated with `start` and `end`, as computed from the
        `updated_model`'s index.

    Notes
    -----
    This function is typically used as a helper for standardizing start and
    end periods for a date range where the most sensible default values are
    based on some initial dataset (here contained in the `previous_model`),
    while index-related operations (especially relative start/end dates given
    via negative integers) are most sensibly computed from an updated dataset
    (here contained in the `updated_model`).

    NzWCannot use the `impact_date` argument in combination with `start`, `end`, or `periods`.r   zOOf the three parameters: start, end, and periods, exactly two must be specified)r"   r   r   _get_prediction_index)	previous_modelupdated_modelimpact_datestartendperiodsr   out_of_sampleprediction_indexs	            r   get_impact_datesre  7  so   t #+'/ + , , , }#a'!A%
5D=Ct,,,s7d?/C/CCqHH C D D 	D
 
	w2&<<UEJJq!Qw{#	W0$::3DD31w{#		s 	++E377 0E3/

C#'''r   c                      g }| D ]S}|d}n7t          j        |          }|j        dk    r|                    d          }n|}|                    |           Tt          |          dk    r|d         S |S )z
    Version of `np.atleast_1d`, copied from
    https://github.com/numpy/numpy/blob/master/numpy/core/shape_base.py,
    with the following modifications:

    1. It allows for `None` arguments, and passes them directly through
    Nr   r   )r   r&   rJ   r   r   r!   arysresaryresults       r   _atleast_1drl    s     C 	 	;FF-$$Cx1}}Q

6
3xx1}}1v
r   c                  2   g }| D ]v}|d}nZt          j        |          }|j        dk    r|                    dd          }n$|j        dk    r|ddt           j        f         }n|}|                    |           wt          |          dk    r|d         S |S )a8  
    Version of `np.atleast_2d`, copied from
    https://github.com/numpy/numpy/blob/master/numpy/core/shape_base.py,
    with the following modifications:

    1. It allows for `None` arguments, and passes them directly through
    2. Instead of creating new axis at the beginning, it creates it at the end
    Nr   r   )r   r&   rJ   r   r   r   r!   rg  s       r   _atleast_2drn    s     C  ;FF-$$Cx1}}Q**QQQQ
]+

6
3xx1}}1v
r   rD   )r   Nr   )r   F)ra   )F)NN)FNN)FN)NF)FFFFN)r   )NNNr2  )NNNN)__doc__numpyr   scipy.linalgr   r?   rT   statsmodels.compat.pandasr   statsmodels.tools.datar   scipy.linalg.blasr    r	   r
   r   r   r   r   r   compatibility_modehas_trmmfloat32float64	complex64
complex128r   sInitializationdInitializationcInitializationzInitializationprefix_initialization_mapsStatespacedStatespacecStatespacezStatespaceprefix_statespace_mapsKalmanFilterdKalmanFiltercKalmanFilterzKalmanFilterprefix_kalman_filter_mapsKalmanSmootherdKalmanSmoothercKalmanSmootherzKalmanSmootherprefix_kalman_smoother_mapsSimulationSmootherdSimulationSmoothercSimulationSmootherzSimulationSmootherprefix_simulation_smoother_mapsCFASimulationSmootherdCFASimulationSmoothercCFASimulationSmootherzCFASimulationSmoother"prefix_cfa_simulation_smoother_map-_scompute_coefficients_from_multivariate_pacf-_dcompute_coefficients_from_multivariate_pacf-_ccompute_coefficients_from_multivariate_pacf-_zcompute_coefficients_from_multivariate_pacfr   _sconstrain_sv_less_than_one_dconstrain_sv_less_than_one_cconstrain_sv_less_than_one_zconstrain_sv_less_than_oner   sreorder_missing_matrixdreorder_missing_matrixcreorder_missing_matrixzreorder_missing_matrixr   sreorder_missing_vectordreorder_missing_vectorcreorder_missing_vectorzreorder_missing_vectorr   scopy_missing_matrixdcopy_missing_matrixccopy_missing_matrixzcopy_missing_matrixr   scopy_missing_vectordcopy_missing_vectorccopy_missing_vectorzcopy_missing_vectorr  scopy_index_matrixdcopy_index_matrixccopy_index_matrixzcopy_index_matrixr  scopy_index_vectordcopy_index_vectorccopy_index_vectorzcopy_index_vectorr   _scompute_smoothed_state_weights _dcompute_smoothed_state_weights _ccompute_smoothed_state_weights _zcompute_smoothed_state_weightsr6  r   r6   r:   rY   rf   rq   rx   r~   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r   r  r	  r  r  r  r"  r)  r1  rJ  rZ  re  rl  rn  rI   r   r   <module>r     s        ( ( ( ( ( (     . . . . . . 3 3 3 3 3 3 1 1 1 1 1 11 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 1
  	"*2<bm   
	(		(		(		(	   
	$?+F		$?+F  
 
	%		%		%		%	   
	)		)		)		)	   
	1		1		1		1	" "  
"	8	!	8	!	8	!	8	& & " 
	=		=		=		=	  
	,		,		,		,	  
	'		'		'		'	% % ! 
	'		'		'		'	% % ! 
	$		$		$		$	" "  
	$		$		$		$	" "  
	"		"		"		"	     
	"		"		"		"	     
	0		0		0		0	- - )9 9 9 9v v vr5 5 5 5pL L L L^D/ D/ D/ D/N5 5 5 56" " "J" " "J =A/3- - - -b FK j j j j\ AF48b b b bJ 

2
:;;9>-1-! -! -! <;-!`. . . .b4" 4" 4"p .2 %i i i iX     2 IM]$ ]$ ]$ ]$B FJ=L =L =L =L@A) A) A)H23 23 23j,3 ,3 ,3^ :?;@15, , , ,^   D INAE6 6 6 6r) ) ) )X AF?C6 6 6 6r) ) ) )X  $% % %B       DHFIB; B; B; B;J GKHL{, {, {, {,| AE37X( X( X( X(v  2    r   