
    M/PhH                         d Z ddlZddlZddlmZmZmZ ddlm	Z	 ddl
mZ  G d d          Z G d	 d
          Z G d d          Z G d d          ZdS )zI
State Space Representation

Author: Chad Fulton
License: Simplified-BSD
    N   )find_best_blas_typevalidate_matrix_shapevalidate_vector_shape)Initialization)toolsc                        e Zd Zd Zd Zd ZdS )OptionWrapperc                 "    || _         || _        d S N)mask_attribute
mask_value)selfr   r   s      i/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/tsa/statespace/representation.py__init__zOptionWrapper.__init__   s    ,$    c                 X    t          t          || j        d          | j        z            S Nr   )boolgetattrr   r   )r   objobjtypes      r   __get__zOptionWrapper.__get__   s&    GC!4a884?JKKKr   c                     t          || j        d          }t          |          r|| j        z  }n|| j         z  }t	          || j        |           d S r   )r   r   r   r   setattr)r   r   valuemask_attribute_values       r   __set__zOptionWrapper.__set__   s]    &sD,?CC;; 	<(4?:EE(DO+;;ET(%00000r   N)__name__
__module____qualname__r   r   r    r   r   r
   r
      sD        % % %L L L1 1 1 1 1r   r
   c                   ,    e Zd Zd Zd Zd Zd Zd ZdS )MatrixWrapperc                 6    || _         || _        d|z   | _        d S )N_)name	attribute
_attribute)r   r'   r(   s      r   r   zMatrixWrapper.__init__&   s    	"	/r   c                 2    t          || j        d           }|S r   )r   r)   )r   r   r   matrixs       r   r   zMatrixWrapper.__get__+   s    dot44 r   c                 .   t          j        |d          }|j        | j                 }t	          |          dk    r|                     |||          }n|                     |||          }t          || j        |           |j	        |j        | j        <   d S )NForder   )
npasarrayshapesr(   len_set_matrix_set_vectorr   r)   shaper   r   r   r7   s       r   r   zMatrixWrapper.__set__2   s    
5,,,
4>*u::??$$S%77EE$$S%77ET_e,,,%*[
4>"""r   c                 2   |j         dk    r/|d         dk    r#|j        d         |d         k    r|d d d f         }t          | j        |j        |d         |d         |j                   |j         dk    r#t          j        |d d d d d f         d          }|S )Nr   r      r-   r.   )ndimr7   r   r'   nobsr1   arrayr8   s       r   r5   zMatrixWrapper._set_matrix>   s    J!OOaAA%(**$'NE 	Iu{E!HeAh	
 	
 	

 :??HU111aaa:.c:::Er   c                     t          | j        |j        |d         |j                   |j        dk    r t          j        |d d d f         d          }|S )Nr   r   r-   r.   )r   r'   r7   r<   r;   r1   r=   r8   s       r   r6   zMatrixWrapper._set_vectorO   sY    Iu{E!Hch	
 	
 	

 :??HU111d7^3777Er   N)r   r    r!   r   r   r   r5   r6   r"   r   r   r$   r$   %   s_        * * *
  
1 
1 
1  "
 
 
 
 
r   r$   c                      e Zd ZdZdZ	  edd          Z	  edd          Z	  edd          Z	  edd          Z		  ed	d
          Z
	  edd          Z	  edd          Z	 dddej        ddddddddfdZd Zd Zd Zd Zd'dZd(dZed             Zed             Zed             Zed             Zed             Zd Z	 	 	 d)dZd Zd*d Z	 	 d+d!Z d" Z!d# Z"d*d$Z#d,d&Z$dS )-Representationa>  
    State space representation of a time series process

    Parameters
    ----------
    k_endog : {array_like, int}
        The observed time-series process :math:`y` if array like or the
        number of variables in the process if an integer.
    k_states : int
        The dimension of the unobserved state process.
    k_posdef : int, optional
        The dimension of a guaranteed positive definite covariance matrix
        describing the shocks in the measurement equation. Must be less than
        or equal to `k_states`. Default is `k_states`.
    initial_variance : float, optional
        Initial variance used when approximate diffuse initialization is
        specified. Default is 1e6.
    initialization : Initialization object or str, optional
        Initialization method for the initial state. If a string, must be one
        of {'diffuse', 'approximate_diffuse', 'stationary', 'known'}.
    initial_state : array_like, optional
        If `initialization='known'` is used, the mean of the initial state's
        distribution.
    initial_state_cov : array_like, optional
        If `initialization='known'` is used, the covariance matrix of the
        initial state's distribution.
    nobs : int, optional
        If an endogenous vector is not given (i.e. `k_endog` is an integer),
        the number of observations can optionally be specified. If not
        specified, they will be set to zero until data is bound to the model.
    dtype : np.dtype, optional
        If an endogenous vector is not given (i.e. `k_endog` is an integer),
        the default datatype of the state space matrices can optionally be
        specified. Default is `np.float64`.
    design : array_like, optional
        The design matrix, :math:`Z`. Default is set to zeros.
    obs_intercept : array_like, optional
        The intercept for the observation equation, :math:`d`. Default is set
        to zeros.
    obs_cov : array_like, optional
        The covariance matrix for the observation equation :math:`H`. Default
        is set to zeros.
    transition : array_like, optional
        The transition matrix, :math:`T`. Default is set to zeros.
    state_intercept : array_like, optional
        The intercept for the transition equation, :math:`c`. Default is set to
        zeros.
    selection : array_like, optional
        The selection matrix, :math:`R`. Default is set to zeros.
    state_cov : array_like, optional
        The covariance matrix for the state equation :math:`Q`. Default is set
        to zeros.
    **kwargs
        Additional keyword arguments. Not used directly. It is present to
        improve compatibility with subclasses, so that they can use `**kwargs`
        to specify any default state space matrices (e.g. `design`) without
        having to clean out any other keyword arguments they might have been
        passed.

    Attributes
    ----------
    nobs : int
        The number of observations.
    k_endog : int
        The dimension of the observation series.
    k_states : int
        The dimension of the unobserved state process.
    k_posdef : int
        The dimension of a guaranteed positive
        definite covariance matrix describing
        the shocks in the measurement equation.
    shapes : dictionary of name:tuple
        A dictionary recording the initial shapes
        of each of the representation matrices as
        tuples.
    initialization : str
        Kalman filter initialization method. Default is unset.
    initial_variance : float
        Initial variance for approximate diffuse
        initialization. Default is 1e6.

    Notes
    -----
    A general state space model is of the form

    .. math::

        y_t & = Z_t \alpha_t + d_t + \varepsilon_t \\
        \alpha_t & = T_t \alpha_{t-1} + c_t + R_t \eta_t \\

    where :math:`y_t` refers to the observation vector at time :math:`t`,
    :math:`\alpha_t` refers to the (unobserved) state vector at time
    :math:`t`, and where the irregular components are defined as

    .. math::

        \varepsilon_t \sim N(0, H_t) \\
        \eta_t \sim N(0, Q_t) \\

    The remaining variables (:math:`Z_t, d_t, H_t, T_t, c_t, R_t, Q_t`) in the
    equations are matrices describing the process. Their variable names and
    dimensions are as follows

    Z : `design`          :math:`(k\_endog \times k\_states \times nobs)`

    d : `obs_intercept`   :math:`(k\_endog \times nobs)`

    H : `obs_cov`         :math:`(k\_endog \times k\_endog \times nobs)`

    T : `transition`      :math:`(k\_states \times k\_states \times nobs)`

    c : `state_intercept` :math:`(k\_states \times nobs)`

    R : `selection`       :math:`(k\_states \times k\_posdef \times nobs)`

    Q : `state_cov`       :math:`(k\_posdef \times k\_posdef \times nobs)`

    In the case that one of the matrices is time-invariant (so that, for
    example, :math:`Z_t = Z_{t+1} ~ \forall ~ t`), its last dimension may
    be of size :math:`1` rather than size `nobs`.

    References
    ----------
    .. [*] Durbin, James, and Siem Jan Koopman. 2012.
       Time Series Analysis by State Space Methods: Second Edition.
       Oxford University Press.
    Ndesignzobservation interceptobs_interceptzobservation covariance matrixobs_cov
transitionzstate interceptstate_intercept	selectionzstate covariance matrix	state_covg    .Ar   c           
         i | _         d }t          |t          j                  r:|}|j        d         r|j        d         dk    s|dk    r|j        }|j        d         }|| _        |dk     rt          d          || _	        |dk     rt          d          || _
        ||n|| _        | j        | j
        k    rt          d          ||                     |           | j        | j	        f| j        | j
        df| j        df| j        | j        df| j
        | j
        df| j
        df| j
        | j        df| j        | j        dfd| _         t                      }| j                                         D ]T\  }}|dk    rt          | d	|z   t          j        ||d
                     ||         t          | |||                    U|| _        ||nt$          j                                        | _        |                    dd           | _        g d}| j        |v r|                     | j                   n| j        dk    rd|v r|                    d          }n)d|v r|                    d          }nt          d          d|v r|                    d          }n)d|v r|                    d          }nt          d          |                     d||           n0t          | j        t0                    s| j        t          d          t3          |          r2d|                                 d}t7          j        |t:                     i | _        i | _        d | _         d S )NC_CONTIGUOUSr   r   zMNumber of endogenous variables in statespace model must be a positive number.z?Number of states in statespace model must be a positive number.zZDimension of state innovation `k_posdef` cannot be larger than the dimension of the state.)obsrA   rB   rC   rD   rE   rF   rG   rJ   r&   r-   )dtyper/   initialization)diffuseapproximate_diffuse
stationaryknownconstantinitial_statezSInitial state must be provided when "known" is the specified initialization method.stationary_covinitial_state_covzeInitial state covariance matrix must be provided when "known" is the specified initialization method.rQ   rS   *Invalid state space initialization method.zUnknown keyword arguments: zT.Passing unknown keyword arguments will raise a TypeError beginning in version 0.15.)!r3   
isinstancer1   ndarrayflagsr7   Tk_endog
ValueErrorr<   k_statesk_posdefbindlocalsitemsr   zerosinitial_variancer   prefix_statespace_mapcopypoprL   
initializer   r4   keyswarningswarnFutureWarning_representations_statespaces_time_invariant)r   r[   r]   r^   rc   r<   rK   rA   rB   rC   rD   rE   rF   rG   statespace_classeskwargsendogscoper'   r7   basic_initsrQ   rS   msgs                           r   r   zRepresentation.__init__  s   
  grz** 	%E N+  [^a''4199k!nG Q;; A B B B	 a<< 1 2 2 2 $,$8h
 =4=(( K L L L IIe L$),|T]A6"lA.dlA6=$-; $q1-:-:	
 	
 ;,,.. 		1 		1KD%u}}D#*bhuE&M&M&MNNN T{&dE$K000 !1);)G '9&8+0+F+K+K+M+M 	"
 %jj)94@@FFF+--OOD/0000 G++V##!::j11 F**!::o66  "L M M M6))!',<!=!=$..!',?!@!@  "; < < < OOGh+9  ; ; ; ;T0.AA 	K#/IJJJ v;; 	.1 1 1 1C M#}--- !#   $r   c                    t          |          }|t          u re|| j        vrt          d|z            t	          | d|z             }|j        d         dk    r$|t          d           f|j        dz
  z  dz            S |S |t          u ry|d         |dd          }}|| j        vrt          d|z            t	          | d|z             }|j        d         dk    r t          |          |j        dz
  k    r|dz   }||         S t          d          )N*"%s" is an invalid state space matrix namer&   r   r   r   8First index must the name of a valid state space matrix.)
typestrr3   
IndexErrorr   r7   slicer;   tupler4   )r   key_typer+   r'   slice_s         r   __getitem__zRepresentation.__getitem__  sB   S		C<<$+%% !M#&"' ( ( (T39--F |B1$$uT{{nfk!m<tCDDe^^q63qrr7&D4;&& !M#'"( ) ) ) T3:..F |B1$$VA)E)E$&>!  ( ) ) )r   c                    t          |          }|t          u r.|| j        vrt          d|z            t	          | ||           d S |t
          u r|d         |dd          }}|| j        vrt          d|d         z            t          j        |          j        }t          | d|z             }g d}|j        |k    s4|j
        |v r+t          | d|z             j                            |          }|j        d         dk    r t          |          |j        dz
  k    r|dz   }|||<   t	          | ||           d S t          d          )	Nrv   r   r   r&   )fdr-   Drw   rx   ry   )rz   r{   r3   r|   r   r~   r1   r=   rK   r   charrealastyper7   r4   r;   )	r   r   r   r   r'   r   rK   r+   valid_typess	            r   __setitem__zRepresentation.__setitem__  s   S		C<<$+%% !M#&"' ( ( (D#u%%%%% e^^q63qrr7&D4;&& !M#&q6"* + + + HUOO)ET3:..F...K<5((UZ;-F-F sTz227>>uEE |B1$$VA)E)E$ #F6ND$'''''  ( ) ) )r   c                    t          |          |d<   | j        |d<   dD ]A}t          | |          }||vs||         |||<   ||         |k    rt          d|z            B| j                                        D ]E}|dk    r	||vr8t          | |          }|j        d         dk    rt          d	|z            |||<   F|                    d
| j                   |S )a  
        Construct keyword arguments for cloning a state space model

        Parameters
        ----------
        endog : array_like
            An observed time-series process :math:`y`.
        **kwargs
            Keyword arguments to pass to the new state space representation
            model constructor. Those that are not specified are copied from
            the specification of the current state space model.
        r<   r[   )r]   r^   Nz/Cannot change the dimension of %s when cloning.rJ   rw   r   zZThe `%s` matrix is time-varying. Cloning this model requires specifying an updated matrix.rL   )	r4   r[   r   r\   r3   rh   r7   
setdefaultrL   )r   rq   rp   r   valr'   mats          r   _clone_kwargszRepresentation._clone_kwargs  s2   " Uv Ly+ 	4 	4C$$$C&  F3K$7!sc{c!!  "-/2"3 4 4 4 " K$$&& 
	# 
	#Du}}6!!dD))9R=A%%$ &8:>&? @ @ @  #t 	*D,?@@@r   c                 f     | j         |fi |} | j        di |}|                    |           |S )aw  
        Clone a state space representation while overriding some elements

        Parameters
        ----------
        endog : array_like
            An observed time-series process :math:`y`.
        **kwargs
            Keyword arguments to pass to the new state space representation
            model constructor. Those that are not specified are copied from
            the specification of the current state space model.

        Returns
        -------
        Representation

        Notes
        -----
        If some system matrices are time-varying, then new time-varying
        matrices *must* be provided.
        r"   )r   	__class__r_   )r   rq   rp   mods       r   clonezRepresentation.clone  sI    , $#E44V44dn&&v&&
r   c           	      "   t          j        |          }|j        dk    r|ddt           j        f         }t	          |          }|d}|| j        }|dk     r
| j        |z   }|dk     r
| j        |z   }|| j        k    rt          d          || j        k    rt          d          ||k    rt          d          t          j        | j	        dd||f         j
        |g          }d}d}| j                                        D ]}\  }}	|d	k    rt          | |          }
||vrD|
j        d
         dk    r2||z   | j        k    rt          ||z            |
d|||z   f         ||<   e|dk    rt          d          |
j        d
         dk    r| j        dk    rt          ||z            t          j        ||                   }t	          |	          dk    r)t!          ||j        |	d         |j        d
                    n/t#          ||j        |	d         |	d         |j        d
                    |j        d
         |k     rt          ||z            |dd|f         }t           j        |
d||f         |f         ||<    | j        |fi |S )a~  
        Extend the current state space model, or a specific (time) subset

        Parameters
        ----------
        endog : array_like
            An observed time-series process :math:`y`.
        start : int, optional
            The first period of a time-varying state space model to include in
            the new model. Has no effect if the state space model is
            time-invariant. Default is the initial period.
        end : int, optional
            The last period of a time-varying state space model to include in
            the new model. Has no effect if the state space model is
            time-invariant. Default is the final period.
        **kwargs
            Keyword arguments to pass to the new state space representation
            model constructor. Those that are not specified are copied from
            the specification of the current state space model.

        Returns
        -------
        Representation

        Notes
        -----
        This method does not allow replacing a time-varying system matrix with
        a time-invariant one (or vice-versa). If that is required, use `clone`.
        r   Nr   zfThe `start` argument of the extension within the base model cannot be after the end of the base model.zdThe `end` argument of the extension within the base model cannot be after the end of the base model.z_The `start` argument of the extension within the base model cannot be after the `end` argument.zIModel has time-invariant %s matrix, so cannot provide an extended matrix.ziModel has time-varying %s matrix, so an updated time-varying matrix for the extension period is required.rJ   rw   .zOExtension is being performed within-sample so cannot provide an extended matrixr:   )r1   
atleast_1dr;   newaxisr4   r<   r\   r   concatrq   rZ   r3   ra   r   r7   r2   r   r   c_r   )r   rq   startendrp   r<   error_tierror_tvr'   r7   r   updated_mats               r   extendzRepresentation.extend  s   < e$$:??!!!RZ-(E5zz=E;)C199I%E77)c/C49 , - - - ?? , - - - 3;; O P P P
 djE#I68%@AA+$  ;,,.. 8	G 8	GKD%u}}$%%C 6!!9R=1$$ TzDI--(D999 (+3cDj0@+@'At  "I J J J 9R=A%%$)a--$X_555 !j66u::??)$0A58*5*;B*?A A A A *$0A58*/(K4Eb4IK K K $R(4//$X_555"-c5D5j"9K  "uSeCi%8+%EFttz%**6***r   绽|=c                 "   | j         j        }t          |          t          |          k     r.t          dt          |          t          |          fz            t          |          t          |          k    rXt          |          t          |          z
  }t          j        |j        || d          j        t          j        z  f         j        }t	          j        |          }t	          j        |          }t	          j        ||z
            }t          j	        |||z  <   d|||z  <   ||k    }|| z  }	d||	<   t          t          t	          j        |                     }
t          t          t	          j        |	                     }|
|fS )NzKGiven data (length %d) is too short to diff against model data (length %d).g        F)rq   rZ   r4   r\   r1   r   nanisnanabsinflistzipwhere)r   	new_endog	tolerancerq   nobs_appendnew_nanexisting_nandiffis_revisionis_newrevision_ixnew_ixs               r   
diff_endogzRepresentation.diff_endog  s`   
y>>CJJ&& @ #IE

;< = = = y>>CJJ&&i..3u::5KE%'9k\]]#;#=#FFGIE(9%%xvi%'((')vW|#$')W|#$i'(#F3 5 5677c28F++,--F""r   c                     | j         | j        | j        | j        | j        | j        | j        f}| j        | j        f|z   }t          |          d         S )zO
        (str) BLAS prefix of currently active representation matrices
        Nr   )	_design_obs_intercept_obs_cov_transition_state_intercept
_selection
_state_covrq   r   )r   arrayss     r   prefixzRepresentation.prefix  sX     L$-t}d3T_O

 :!j]V+F"6**1--r   c                 0    t           j        | j                 S )zN
        (dtype) Datatype of currently active representation matrices
        )r   prefix_dtype_mapr   r   s    r   rK   zRepresentation.dtype  s    
 %dk22r   c                 V   | j         | j        j        d         | j        j        d         cxk    oq| j        j        d         cxk    oZ| j        j        d         cxk    oC| j        j        d         cxk    o,| j        j        d         cxk    o| j        j        d         k    nc S | j         S )zk
        (bool) Whether or not currently active representation matrices are
        time-invariant
        Nr:   r   )	rn   r   r7   r   r   r   r   r   r   r   s    r   time_invariantzRepresentation.time_invariant  s     '"1%)<)B1)E ) ) ) )#A&) ) ) )*.*:*@*C) ) ) )%+A.) ) ) )26/2G2J) ) ) ) %a() ) ) ) ''r   c                 @    | j         }|| j        v r| j        |         S d S r   )r   rm   )r   r   s     r   _statespacezRepresentation._statespace  s*    T&&&$V,,tr   c                     | j         S )zN
        (array) Observation vector: :math:`y~(k\_endog \times nobs)`
        )rq   r   s    r   rJ   zRepresentation.obs  s    
 zr   c                 2   t          |t          j                  st          d          |j        dk    r4| j        dk    r|j        d         df|_        nd|j        d         f|_        |j        dk    st          d          |j        d         r|j        d         | j        k    rnr|j        d         r|j        d         | j        k    r|j        }nG|j        d         rt          d          |j        d         rt          d	          t          d
          |j        d         st          j	        |          }t          j
        |          | _        || _        | j        j        d         | _        t          | d          r| j        j        | j        d<   dS dS )a(  
        Bind data to the statespace representation

        Parameters
        ----------
        endog : ndarray
            Endogenous data to bind to the model. Must be column-ordered
            ndarray with shape (`k_endog`, `nobs`) or row-ordered ndarray with
            shape (`nobs`, `k_endog`).

        Notes
        -----
        The strict requirements arise because the underlying statespace and
        Kalman filtering classes require Fortran-ordered arrays in the wide
        format (shaped (`k_endog`, `nobs`)), and this structure is setup to
        prevent copying arrays in memory.

        By default, numpy arrays are row (C)-ordered and most time series are
        represented in the long format (with time on the 0-th axis). In this
        case, no copying or re-ordering needs to be performed, instead the
        array can simply be transposed to get it in the right order and shape.

        Although this class (Representation) has stringent `bind` requirements,
        it is assumed that it will rarely be used directly.
        z-Invalid endogenous array; must be an ndarray.r   r   r:   z9Invalid endogenous array provided; must be 2-dimensional.F_CONTIGUOUSrI   zXInvalid endogenous array; column-ordered arrays must have first axis shape of `k_endog`.zTInvalid endogenous array; row-ordered arrays must have last axis shape of `k_endog`.z?Invalid endogenous array; must be ordered in contiguous memory.r3   rJ   N)rW   r1   rX   r\   r;   r[   r7   rY   rZ   asfortranarrayiscomplexobj_complex_endogrq   r<   hasattrr3   )r   rq   s     r   r_   zRepresentation.bind  s   4 %,, 	NLMMM :??|q  ${1~q1  !%+a.1zQ / 0 0 0 ;~& 	45;q>T\+I+I [( 	4U[^t|-K-KGEE[( 	4 + , , , [( 	4 + , , ,
  3 4 4 4 {>* 	-%e,,E !oe44 
J$Q'	 4"" 	2!%!1DK	2 	2r   c                    |dk    rt          | j        d||          }n|dk    rt          j        |||||	|
          }n^|dk    r!|| j        }t          | j        d|          }n7|dk    rt          | j        d          }n|d	k    rt          | j        d	          }t	          |t                     st          d
          || _        dS )z,Create an Initialization object if necessaryrP   rU   
componentsaPstarPinfAR0Q0rN   Napproximate_diffuse_variancerO   rM   rV   )r   r]   from_componentsrc   rW   r\   rL   )r   rL   r   rQ   rS   r   r   r   r   r   r   s              r   rg   zRepresentation.initialize6  s    W$$+DM75=;IK K KNN |+++;5tqRB@ @ @NN444+3/3/D,+4-IK K KNN |+++DM<HHNNy((+DM9EEN ..99 	KIJJJ,r   c                    t          j        |d          }t          j        |d          }|j        | j        fk    s+t	          d| j        t          |j                  fz            |j        | j        | j        fk    s1t	          d| j        | j        t          |j                  fz            |                     d||           dS )a  
        Initialize the statespace model with known distribution for initial
        state.

        These values are assumed to be known with certainty or else
        filled with parameters during, for example, maximum likelihood
        estimation.

        Parameters
        ----------
        constant : array_like
            Known mean of the initial state vector.
        stationary_cov : array_like
            Known covariance matrix of the initial state vector.
        r-   r.   zJInvalid dimensions for constant state vector. Requires shape (%d,), got %szSInvalid dimensions for stationary covariance matrix. Requires shape (%d,%d), got %srP   rU   N)r1   r2   r7   r]   r\   r{   rg   )r   rQ   rS   s      r   initialize_knownzRepresentation.initialize_knownR  s      :hc222N#>>>~$-!111 ="mS-@-@AB C C C #t}'EEE G"mT]!."67799 : : :
 	('5 	 	7 	7 	7 	7 	7r   c                 F    || j         }|                     d|           dS )a  
        Initialize the statespace model with approximate diffuse values.

        Rather than following the exact diffuse treatment (which is developed
        for the case that the variance becomes infinitely large), this assigns
        an arbitrary large number for the variance.

        Parameters
        ----------
        variance : float, optional
            The variance for approximating diffuse initial conditions. Default
            is 1e6.
        NrN   r   )rc   rg   )r   variances     r   initialize_approximate_diffusez-Representation.initialize_approximate_diffuser  s=     ,H-5= 	 	? 	? 	? 	? 	?r   c           	      >    |                      d||||||           dS )aa  
        Initialize the statespace model with component matrices

        Parameters
        ----------
        a : array_like, optional
            Vector of constant values describing the mean of the stationary
            component of the initial state.
        Pstar : array_like, optional
            Stationary component of the initial state covariance matrix. If
            given, should be a matrix shaped `k_states x k_states`. The
            submatrix associated with the diffuse states should contain zeros.
            Note that by definition, `Pstar = R0 @ Q0 @ R0.T`, so either
            `R0,Q0` or `Pstar` may be given, but not both.
        Pinf : array_like, optional
            Diffuse component of the initial state covariance matrix. If given,
            should be a matrix shaped `k_states x k_states` with ones in the
            diagonal positions corresponding to states with diffuse
            initialization and zeros otherwise. Note that by definition,
            `Pinf = A @ A.T`, so either `A` or `Pinf` may be given, but not
            both.
        A : array_like, optional
            Diffuse selection matrix, used in the definition of the diffuse
            initial state covariance matrix. If given, should be a
            `k_states x k_diffuse_states` matrix that contains the subset of
            the columns of the identity matrix that correspond to states with
            diffuse initialization. Note that by definition, `Pinf = A @ A.T`,
            so either `A` or `Pinf` may be given, but not both.
        R0 : array_like, optional
            Stationary selection matrix, used in the definition of the
            stationary initial state covariance matrix. If given, should be a
            `k_states x k_nondiffuse_states` matrix that contains the subset of
            the columns of the identity matrix that correspond to states with a
            non-diffuse initialization. Note that by definition,
            `Pstar = R0 @ Q0 @ R0.T`, so either `R0,Q0` or `Pstar` may be
            given, but not both.
        Q0 : array_like, optional
            Covariance matrix associated with stationary initial states. If
            given, should be a matrix shaped
            `k_nondiffuse_states x k_nondiffuse_states`.
            Note that by definition, `Pstar = R0 @ Q0 @ R0.T`, so either
            `R0,Q0` or `Pstar` may be given, but not both.

        Notes
        -----
        The matrices `a, Pstar, Pinf, A, R0, Q0` and the process for
        initializing the state space model is as given in Chapter 5 of [1]_.
        For the definitions of these matrices, see equation (5.2) and the
        subsequent discussion there.

        References
        ----------
        .. [1] Durbin, James, and Siem Jan Koopman. 2012.
           Time Series Analysis by State Space Methods: Second Edition.
           Oxford University Press.
        r   r   Nrg   )r   r   r   r   r   r   r   s          r   initialize_componentsz$Representation.initialize_components  s9    t 	TQ2 	 	 	 	 	 	r   c                 0    |                      d           dS )z@
        Initialize the statespace model as stationary.
        rO   Nr   r   s    r   initialize_stationaryz$Representation.initialize_stationary  s     	%%%%%r   c                 0    |                      d           dS )z=
        Initialize the statespace model as diffuse.
        rM   Nr   r   s    r   initialize_diffusez!Representation.initialize_diffuse  s     		"""""r   c                    || j         }t          j        |         }|| j        vri | j        |<   | j                                        D ]e}|dk    r)| j                            |          | j        |         |<   1t          | d|z                                 |          | j        |         |<   fn| j                                        D ]r}| j        |         |         }|dk    rt          | d|z                                 |          }|j	        |j	        k    r|d d          |d d <   b|| j        |         |<   s|| j
        v rG| j
        |         }|j        j	        d         | j        j	        d         k     p|j        j	        d         | j        j	        d         k     p|j        j	        d         | j        j	        d         k     p|j        j	        d         | j        j	        d         k     p|j        j	        d         | j        j	        d         k     pt|j        j	        d         | j        j	        d         k     pM|j        j	        d         | j        j	        d         k     p&|j        j	        d         | j        j	        d         k     }nd}|r|| j
        v r| j
        |= | j        |         } || j        |         d         | j        |         d         | j        |         d         | j        |         d         | j        |         d	         | j        |         d
         | j        |         d         | j        |         d                   | j
        |<   |||fS )NrJ   r&   r   r:   TrA   rB   rC   rD   rE   rF   rG   )r   r   r   rl   r3   rh   rJ   r   r   r7   rm   rq   rA   rB   rC   rD   rE   rF   rG   rd   )	r   r   rK   r+   existingnewsscreateclss	            r   _initialize_representationz)Representation._initialize_representation  s   >[F&v. ...,.D!&)+**,, 	 	U??.. )&1&99  cFl33::5AA )&1&99	 +**,, 
D 
D08@U??!$f55<<UCCC~22&)!!!f@C-f5f== T&&&"6*BFLOtz'7'::: EIOA&$+*;A*>>>E$*1-1C1I!1LLLE J$Q'4<+=a+@@@E M'*do.CA.FFF	E
 '-a0)/23 4E L&q)T^-A!-DDDE L&q)T^-A!-DDD F F  	***%f- ,V4C(+%f-e4%f-h7%f-o>%f-i8%f-l;%f-.?@%f-k:%f-k:	) 	)Df% uf$$r   Fc                     || j         }t          | j        t                    rD| j        j        st          d          | j        |                             | j        |           d S t          d          )NzInitialization is incomplete.)complex_stepz!Statespace model not initialized.)r   rW   rL   r   initializedRuntimeErrorrm   rg   )r   r   r   s      r   _initialize_statez Representation._initialize_state  s     >[F d)>:: 	D&2 D"#BCCCf%001D>J 1 L L L L L BCCCr   )NN)r   )	NNNNNNNNNr   )NNNNNN)NF)%r   r    r!   __doc__rq   r$   rA   rB   rC   rD   rE   rF   rG   r1   float64r   r   r   r   r   r   r   propertyr   rK   r   r   rJ   r_   rg   r   r   r   r   r   r   r   r"   r   r   r@   r@   \   s       ~ ~@ E ]8X..F "M"9?KKM m;YGGG |\::J $m$57HIIO k;77I 7EEI
 48"%ARZD$ $$D	}$ }$ }$ }$~$) $) $)L') ') ')R- - -^  6|+ |+ |+ |+|# # # #4 . . X. 3 3 X3 ( ( X(   X   XO2 O2 O2b GKEI26- - - -87 7 7@? ? ? ?( FJ*.; ; ; ;z& & &# # #F% F% F% F%PD D D D D Dr   r@   c                   *    e Zd ZdZg dZeZd Zd ZdS )FrozenRepresentationa  
    Frozen Statespace Model

    Takes a snapshot of a Statespace model.

    Parameters
    ----------
    model : Representation
        A Statespace representation

    Attributes
    ----------
    nobs : int
        Number of observations.
    k_endog : int
        The dimension of the observation series.
    k_states : int
        The dimension of the unobserved state process.
    k_posdef : int
        The dimension of a guaranteed positive definite
        covariance matrix describing the shocks in the
        measurement equation.
    dtype : dtype
        Datatype of representation matrices
    prefix : str
        BLAS prefix of representation matrices
    shapes : dictionary of name:tuple
        A dictionary recording the shapes of each of
        the representation matrices as tuples.
    endog : ndarray
        The observation vector.
    design : ndarray
        The design matrix, :math:`Z`.
    obs_intercept : ndarray
        The intercept for the observation equation, :math:`d`.
    obs_cov : ndarray
        The covariance matrix for the observation equation :math:`H`.
    transition : ndarray
        The transition matrix, :math:`T`.
    state_intercept : ndarray
        The intercept for the transition equation, :math:`c`.
    selection : ndarray
        The selection matrix, :math:`R`.
    state_cov : ndarray
        The covariance matrix for the state equation :math:`Q`.
    missing : array of bool
        An array of the same size as `endog`, filled
        with boolean values that are True if the
        corresponding entry in `endog` is NaN and False
        otherwise.
    nmissing : array of int
        An array of size `nobs`, where the ith entry
        is the number (between 0 and `k_endog`) of NaNs in
        the ith row of the `endog` array.
    time_invariant : bool
        Whether or not the representation matrices are time-invariant
    initialization : Initialization object
        Kalman filter initialization method.
    initial_state : array_like
        The state vector used to initialize the Kalamn filter.
    initial_state_cov : array_like
        The state covariance matrix used to initialize the Kalamn filter.
    )modelr   rK   r<   r[   r]   r^   r   rq   rA   rB   rC   rD   rE   rF   rG   missingnmissingr3   rL   rR   rT   rc   c                 f    | j         D ]}t          | |d            |                     |           d S r   )_attributesr   update_representationr   r   r'   s      r   r   zFrozenRepresentation.__init__q  sE    $ 	& 	&DD$%%%% 	""5)))))r   c                    || _         |j        | _        |j        | _        |j        | _        |j        | _        |j        | _        |j        | _        |j        | _        |j        | _        |j	        
                                | _        |j        
                                | _        |j        
                                | _        |j        
                                | _        |j        
                                | _        |j        
                                | _        |j        
                                | _        t1          j        |j        | j                 j        d          | _        t1          j        |j        | j                 j        d          | _        t;          |j                  | _        | j                                        D ]&}|dk    r	tA          | |          j!        | j        |<   '| j        j!        | j        d<   |j"        | _"        |j"        |#                                 t1          j        |j        | j                 j$        d          | _$        t1          j        |j        | j                 j%        d          | _%        t1          j        |j        | j                 j&        d          | _&        dS dS )zUpdate model RepresentationT)re   rJ   N)'r   r   rK   r<   r[   r]   r^   r   rq   r   re   rA   r   rB   r   rC   r   rD   r   rE   r   rF   r   rG   r1   r=   rm   r   r   dictr3   rh   r   r7   rL   r   rR   rT   initial_diffuse_state_covr   s      r   r   z*FrozenRepresentation.update_representationy  sp    
 l[
 J	}#2 [
m((**"16688~**,,+0022$5::<<)..00)..00x 24; ? G%)+ + +!3DK!@!I&*, , , 5<((K$$&& 	: 	:Du}} 'd 3 3 9DK!Z-E $2+##%%%!#"4;/=D"J "J "JD%'X"4;/A&N &N &ND"-/X"4;/I. . .D*** ,+r   N)r   r    r!   r   _model_attributesr   r   r   r"   r   r   r   r   (  sV        > >~   $K* * *2 2 2 2 2r   r   )r   ri   numpyr1   r   r   r   r   rL   r    r
   r$   r@   r   r"   r   r   <module>r     sD                  + * * * * *      1 1 1 1 1 1 1 1(4 4 4 4 4 4 4 4nID ID ID ID ID ID ID IDXC C C C C C C C C Cr   