
    M/Ph{E                        d Z ddlZddlmZ ddlmZ ddlmZm	Z	 ddl
mZmZmZ ddlmZmZ dZd	Zd
ZdZdZeez  ez  ez  ez  ZdZd	Zd
ZdZ G d de          Z G d de	          ZdS )ze
State Space Representation and Kalman Filter, Smoother

Author: Chad Fulton
License: Simplified-BSD
    N)SimpleNamespace)OptionWrapper)KalmanFilterFilterResults)reorder_missing_matrixreorder_missing_vectorcopy_index_matrix)toolsinitialization               c                       e Zd ZdZg dZ ede          Z ede          Z	 ede
          Z ede          Z ede          Z ede          Zg dZ ede          Z	  ede          Z	  ede          Z	  ede          Z	 eZdZ	 	 d fd	Z fd	Zed
             Z 	 	 ddZ!ddZ"ddZ#	 	 ddZ$	 	 	 	 ddZ% xZ&S )KalmanSmoothera  
    State space representation of a time series process, with Kalman filter
    and smoother.

    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`.
    results_class : class, optional
        Default results class to use to save filtering output. Default is
        `SmootherResults`. If specified, class must extend from
        `SmootherResults`.
    **kwargs
        Keyword arguments may be used to provide default values for state space
        matrices, for Kalman filtering options, or for Kalman smoothing
        options. See `Representation` for more details.
    )smoother_statesmoother_state_covsmoother_state_autocovsmoother_disturbancesmoother_disturbance_covsmoother_allsmoother_output)smooth_conventionalsmooth_alternativesmooth_classicalsmooth_methodr   Nc                 `   |t           }dgt          j        z   }fd|D             }dgt          j        z   }fd|D             }	 t	                      j        |||fd|i ||nt          j                                        | _        i | _	         | j
        di |  | j        di |	 d S )Nr   c                 D    i | ]}|v |                     |          S  pop.0keykwargss     j/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/tsa/statespace/kalman_smoother.py
<dictcomp>z+KalmanSmoother.__init__.<locals>.<dictcomp>o   s5     "4 "4 "43%(F]] #&vzz#%2]]    r   c                 D    i | ]}|v |                     |          S r    r!   r#   s     r'   r(   z+KalmanSmoother.__init__.<locals>.<dictcomp>r   s5      2  2  2#&&== !$VZZ__#0==r)   results_classr    )SmootherResultsr   smoother_outputssmooth_methodssuper__init__r
   prefix_kalman_smoother_mapcopy_kalman_smoothersset_smoother_outputset_smooth_method)selfk_endogk_statesk_posdefr+   kalman_smoother_classesr&   keyssmoother_output_kwargssmooth_method_kwargs	__class__s         `   r'   r0   zKalmanSmoother.__init__g   s,     +M ""^%DD"4 "4 "4 "4$ "4 "4 "4 >#@@ 2  2  2  2  2  2  2 	Xx	
 	
7D	
HN	
 	
 	
 '2 $#16688 	' "$ 	! ::#9:::66!566666r)   c                      t                      j        |fi |}|                    d| j                   |                    d| j                   |S )Nr   r   )r/   _clone_kwargs
setdefaultr   r   )r6   endogr&   r>   s      r'   r@   zKalmanSmoother._clone_kwargs   s[    &&u7777 	+T-ABBB/4+=>>>r)   c                 @    | j         }|| j        v r| j        |         S d S N)prefixr3   )r6   rE   s     r'   _kalman_smootherzKalmanSmoother._kalman_smoother   s*    T+++)&11tr)   c                    || j         }|| j        } | j        |fi |\  }}}}|p|| j        v}|s!| j        |         }	|	j        | j        |         u}|r:| j        |         }
 |
| j        |         | j        |         ||          | j        |<   nA| j        |                             |d           | j        |         	                    |           |||||fS )NF)
r   r   _initialize_filterr3   kfilter_kalman_filtersr1   _statespacesr4   r5   )r6   r   r   rE   r&   dtypecreate_filtercreate_statespacecreate_smootherkalman_smootherclss              r'   _initialize_smootherz#KalmanSmoother._initialize_smoother   s1   ""2O  .M $D#F55f55 	8}&7 ) @!)?? 	 	="4V<O.6#3F; <O
  	L1&9C-0S!&)4+?+G. .D"6** "6*>>( ( ("6*<<]KKKuo}>OOOr)   c                 l    ||| _         t          j        D ]}||v rt          | |||                    dS )aV
  
        Set the smoother output

        The smoother can produce several types of results. The smoother output
        variable controls which are calculated and returned.

        Parameters
        ----------
        smoother_output : int, optional
            Bitmask value to set the smoother output to. See notes for details.
        **kwargs
            Keyword arguments may be used to influence the smoother output by
            setting individual boolean flags. See notes for details.

        Notes
        -----
        The smoother output is defined by a collection of boolean flags, and
        is internally stored as a bitmask. The methods available are:

        SMOOTHER_STATE = 0x01
            Calculate and return the smoothed states.
        SMOOTHER_STATE_COV = 0x02
            Calculate and return the smoothed state covariance matrices.
        SMOOTHER_STATE_AUTOCOV = 0x10
            Calculate and return the smoothed state lag-one autocovariance
            matrices.
        SMOOTHER_DISTURBANCE = 0x04
            Calculate and return the smoothed state and observation
            disturbances.
        SMOOTHER_DISTURBANCE_COV = 0x08
            Calculate and return the covariance matrices for the smoothed state
            and observation disturbances.
        SMOOTHER_ALL
            Calculate and return all results.

        If the bitmask is set directly via the `smoother_output` argument, then
        the full method must be provided.

        If keyword arguments are used to set individual boolean flags, then
        the lowercase of the method must be used as an argument name, and the
        value is the desired value of the boolean flag (True or False).

        Note that the smoother output may also be specified by directly
        modifying the class attributes which are defined similarly to the
        keyword arguments.

        The default smoother output is SMOOTHER_ALL.

        If performance is a concern, only those results which are needed should
        be specified as any results that are not specified will not be
        calculated. For example, if the smoother output is set to only include
        SMOOTHER_STATE, the smoother operates much more quickly than if all
        output is required.

        Examples
        --------
        >>> import statsmodels.tsa.statespace.kalman_smoother as ks
        >>> mod = ks.KalmanSmoother(1,1)
        >>> mod.smoother_output
        15
        >>> mod.set_smoother_output(smoother_output=0)
        >>> mod.smoother_state = True
        >>> mod.smoother_output
        1
        >>> mod.smoother_state
        True
        N)r   r   r-   setattr)r6   r   r&   names       r'   r4   z"KalmanSmoother.set_smoother_output   sO    H &#2D "3 	2 	2Dv~~dF4L111	2 	2r)   c                 l    ||| _         t          j        D ]}||v rt          | |||                    dS )a  
        Set the smoothing method

        The smoothing method can be used to override the Kalman smoother
        approach used. By default, the Kalman smoother used depends on the
        Kalman filter method.

        Parameters
        ----------
        smooth_method : int, optional
            Bitmask value to set the filter method to. See notes for details.
        **kwargs
            Keyword arguments may be used to influence the filter method by
            setting individual boolean flags. See notes for details.

        Notes
        -----
        The smoothing method is defined by a collection of boolean flags, and
        is internally stored as a bitmask. The methods available are:

        SMOOTH_CONVENTIONAL = 0x01
            Default Kalman smoother, as presented in Durbin and Koopman, 2012
            chapter 4.
        SMOOTH_CLASSICAL = 0x02
            Classical Kalman smoother, as presented in Anderson and Moore, 1979
            or Durbin and Koopman, 2012 chapter 4.6.1.
        SMOOTH_ALTERNATIVE = 0x04
            Modified Bryson-Frazier Kalman smoother method; this is identical
            to the conventional method of Durbin and Koopman, 2012, except that
            an additional intermediate step is included.
        SMOOTH_UNIVARIATE = 0x08
            Univariate Kalman smoother, as presented in Durbin and Koopman,
            2012 chapter 6, except with modified Bryson-Frazier timing.

        Practically speaking, these methods should all produce the same output
        but different computational implications, numerical stability
        implications, or internal timing assumptions.

        Note that only the first method is available if using a Scipy version
        older than 0.16.

        If the bitmask is set directly via the `smooth_method` argument, then
        the full method must be provided.

        If keyword arguments are used to set individual boolean flags, then
        the lowercase of the method must be used as an argument name, and the
        value is the desired value of the boolean flag (True or False).

        Note that the filter method may also be specified by directly modifying
        the class attributes which are defined similarly to the keyword
        arguments.

        The default filtering method is SMOOTH_CONVENTIONAL.

        Examples
        --------
        >>> mod = sm.tsa.statespace.SARIMAX(range(10))
        >>> mod.smooth_method
        1
        >>> mod.filter_conventional
        True
        >>> mod.filter_univariate = True
        >>> mod.smooth_method
        17
        >>> mod.set_smooth_method(filter_univariate=False,
                                  filter_collapsed=True)
        >>> mod.smooth_method
        33
        >>> mod.set_smooth_method(smooth_method=1)
        >>> mod.filter_conventional
        True
        >>> mod.filter_univariate
        False
        >>> mod.filter_collapsed
        False
        >>> mod.filter_univariate = True
        >>> mod.smooth_method
        17
        N)r   r   r.   rT   )r6   r   r&   rU   s       r'   r5   z KalmanSmoother.set_smooth_method	  sO    ` $!.D"1 	2 	2Dv~~dF4L111	2 	2r)   Fc                      | j         ||fd|i|\  }}}}	}
|	s|
rt          d          | j        |         } |             |S )NrE   zgPassed settings forced re-creation of the Kalman filter. Please run `_filter` before running `_smooth`.)rR   
ValueErrorr3   )r6   r   r   rE   complex_stepresultsr&   rL   rO   rM   rN   smoothers               r'   _smoothzKalmanSmoother._smooth_  s     &D% 7=AG  	I7H  	4- 	4 3 4 4 4
 )&1 	


r)   Tc
                      | j         di |
}|                     |           }|r|                    |            |r|                    |           n|j        |_        || j        } | j        |fd|i|
}|	r|                    |           |S )a  
        Apply the Kalman smoother to the statespace model.

        Parameters
        ----------
        smoother_output : int, optional
            Determines which Kalman smoother output calculate. Default is all
            (including state, disturbances, and all covariances).
        results : class or object, optional
            If a class, then that class is instantiated and returned with the
            result of both filtering and smoothing.
            If an object, then that object is updated with the smoothing data.
            If None, then a SmootherResults object is returned with both
            filtering and smoothing results.
        run_filter : bool, optional
            Whether or not to run the Kalman filter prior to smoothing. Default
            is True.
        prefix : str
            The prefix of the datatype. Usually only used internally.

        Returns
        -------
        SmootherResults object
        NrZ   r    )_filterr+   update_representationupdate_filternobs_diffuser   r\   update_smoother)r6   r   r   rZ   
run_filterrE   rY   r_   r`   rb   r&   rI   r[   s                r'   smoothzKalmanSmoother.smoothu  s    < $,(((( $$T**  	0))$/// 	8!!'**** $+#7G  ""2O4<KKKFKK  	.##H---r)   )NNNrD   )NNNFN)	NNNTNFTTT)'__name__
__module____qualname____doc__r-   r   SMOOTHER_STATEr   SMOOTHER_STATE_COVr   SMOOTHER_DISTURBANCEr   SMOOTHER_DISTURBANCE_COVr   SMOOTHER_STATE_AUTOCOVr   SMOOTHER_ALLr   r.   SMOOTH_CONVENTIONALr   SMOOTH_ALTERNATIVEr   SMOOTH_CLASSICALr   SMOOTH_UNIVARIATEsmooth_univariater   r   r0   r@   propertyrF   rR   r4   r5   r\   rd   __classcell__r>   s   @r'   r   r   "   s2        2  
 #]#4nEEN&'8:LMM')=>>  	')ABB  	')?@@  !=!2LAAL  N (-9LMM '8JKK %}_6FGG &o7HII
 #OMGK)-7 7 7 7 7 7@       X HL$(%P %P %P %PNH2 H2 H2 H2TT2 T2 T2 T2l HL,0   , HL:?9=#4 4 4 4 4 4 4 4r)   r   c                        e Zd ZdZg dZej        Zej	        ez   Z
d fd	Zd Z	 ddZ	 	 dd	Z	 	 ddZ	 	 ddZd Zed             Zed             Zed             Z	 	 ddZ xZS )r,   aG  
    Results from applying the Kalman smoother and/or filter to a state space
    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 : str
        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.
    filter_method : int
        Bitmask representing the Kalman filtering method
    inversion_method : int
        Bitmask representing the method used to invert the forecast error
        covariance matrix.
    stability_method : int
        Bitmask representing the methods used to promote numerical stability in
        the Kalman filter recursions.
    conserve_memory : int
        Bitmask representing the selected memory conservation method.
    tolerance : float
        The tolerance at which the Kalman filter determines convergence to
        steady-state.
    loglikelihood_burn : int
        The number of initial periods during which the loglikelihood is not
        recorded.
    converged : bool
        Whether or not the Kalman filter converged.
    period_converged : int
        The time period in which the Kalman filter converged.
    filtered_state : ndarray
        The filtered state vector at each time period.
    filtered_state_cov : ndarray
        The filtered state covariance matrix at each time period.
    predicted_state : ndarray
        The predicted state vector at each time period.
    predicted_state_cov : ndarray
        The predicted state covariance matrix at each time period.
    kalman_gain : ndarray
        The Kalman gain at each time period.
    forecasts : ndarray
        The one-step-ahead forecasts of observations at each time period.
    forecasts_error : ndarray
        The forecast errors at each time period.
    forecasts_error_cov : ndarray
        The forecast error covariance matrices at each time period.
    loglikelihood : ndarray
        The loglikelihood values at each time period.
    collapsed_forecasts : ndarray
        If filtering using collapsed observations, stores the one-step-ahead
        forecasts of collapsed observations at each time period.
    collapsed_forecasts_error : ndarray
        If filtering using collapsed observations, stores the one-step-ahead
        forecast errors of collapsed observations at each time period.
    collapsed_forecasts_error_cov : ndarray
        If filtering using collapsed observations, stores the one-step-ahead
        forecast error covariance matrices of collapsed observations at each
        time period.
    standardized_forecast_error : ndarray
        The standardized forecast errors
    smoother_output : int
        Bitmask representing the generated Kalman smoothing output
    scaled_smoothed_estimator : ndarray
        The scaled smoothed estimator at each time period.
    scaled_smoothed_estimator_cov : ndarray
        The scaled smoothed estimator covariance matrices at each time period.
    smoothing_error : ndarray
        The smoothing error covariance matrices at each time period.
    smoothed_state : ndarray
        The smoothed state at each time period.
    smoothed_state_cov : ndarray
        The smoothed state covariance matrices at each time period.
    smoothed_state_autocov : ndarray
        The smoothed state lago-one autocovariance matrices at each time
        period: :math:`Cov(\alpha_{t+1}, \alpha_t)`.
    smoothed_measurement_disturbance : ndarray
        The smoothed measurement at each time period.
    smoothed_state_disturbance : ndarray
        The smoothed state at each time period.
    smoothed_measurement_disturbance_cov : ndarray
        The smoothed measurement disturbance covariance matrices at each time
        period.
    smoothed_state_disturbance_cov : ndarray
        The smoothed state disturbance covariance matrices at each time period.
    )r   scaled_smoothed_estimatorscaled_smoothed_estimator_covsmoothing_errorsmoothed_statesmoothed_state_covsmoothed_state_autocov smoothed_measurement_disturbancesmoothed_state_disturbance$smoothed_measurement_disturbance_covsmoothed_state_disturbance_covinnovations_transitionFc           
          t                                          ||           | j        D ]"}t          | |t	          ||d                     #d| _        d| _        d| _        dS )a  
        Update the results to match a given model

        Parameters
        ----------
        model : Representation
            The model object from which to take the updated values.
        only_options : bool, optional
            If set to true, only the smoother and filter options are updated,
            and the state space representation is not updated. Default is
            False.

        Notes
        -----
        This method is rarely required except for internal usage.
        N)r/   r_   _smoother_optionsrT   getattr_smoothed_forecasts_smoothed_forecasts_error_smoothed_forecasts_error_cov)r6   modelonly_optionsrU   r>   s       r'   r_   z%SmootherResults.update_representation@  st    " 	%%e\::: * 	< 	<DD$tT : :;;;; $( )-&-1***r)   c                 R   g }| j         s| j        r|                    d           | j        s| j        r|                    d           | j         r|                    d           | j        r|                    d           | j        r|                    d           | j        r|g dz  }| j        r|ddgz  }t          j        | j                  d	k    }| j	        D ]N}|d
k    r
||v r.|dv rlt          ||d          }|1|r/t          j        t          || j        | j                            }nt          j        |d          }t          | ||           |dk    rt          ||d          }|F|rDt!          || j        dd| j                  }t#          | j        || j        ddd| j                   nt          j        |d          }t          | ||           t          | |t          j        t          ||d          d                     =t          | |d           Pt          j        |j        d          | _        d| _        d| _        d| _        | j        d	k    r`t          j        |j        d          | _        t          j        |j        d          | _        t          j        |j        d          | _        d}d}d|v r.| j        ddd	f         | _        | j        dd||f         | _        d|v r4| j        ddddd	f         | _        | j        dddd||f         | _        d| _        d| _        d| _        | j        r| j         j!        | xj"        | j#        z  c_"        | xj$        | j#        z  c_$        | xj%        | j#        z  c_%        | xj&        | j#        z  c_&        | xj        | j#        z  c_        | xj        | j#        z  c_        | xj        | j#        z  c_        | xj        | j#        z  c_        | xj'        | j#        z  c_'        i | _(        dS )a  
        Update the smoother results

        Parameters
        ----------
        smoother : KalmanSmoother
            The model object from which to take the updated values.

        Notes
        -----
        This method is rarely required except for internal usage.
        rx   ry   r{   r|   r}   )rz   r~   r   r   r   r   r   )rz   r~   N)rE   T)r2   )reorder_rowsreorder_colsrE   )
index_rows
index_colsinplacerE   r   ))r   r   appendr   r   r   npsumnmissing_smoother_attributesr   arrayr   missingrE   rT   r   r	   obs_covr   !scaled_smoothed_diffuse_estimator&scaled_smoothed_diffuse1_estimator_cov&scaled_smoothed_diffuse2_estimator_covra   rx   #scaled_smoothed_estimator_presamplery   'scaled_smoothed_estimator_cov_presampler   r   r   filter_concentratedr   _scaler|   scaler}   r   r   rz   /_SmootherResults__smoothed_state_autocovariance)	r6   r[   
attributeshas_missingrU   vectormatrixstartends	            r'   rb   zSmootherResults.update_smoother\  s?    

  	;$"; 	;9:::" 	?d&C 	?=>>> 	0.///" 	42333& 	86777$ 	    J
 ( 	60 J
 fT]++a/-  	*  	*D(((## @ @ @$XtT::F)k)!#*@"DL+F +F +F "G "G "$&t!<!<!<D$////CCC$XtT::F)k)!7"DLt)-dk"C "C "C
 * L&$,'+d#';0 0 0 0 0
 "$&t!<!<!<D$////D$HWXtT%B%BNNNP P P P dD)))) HX44@@@ 	# 26.6:36:3q  57X:6G 6G 6GD2:<(?d;L ;L ;LD7:<(?d;L ;L ;LD7 &*44.qqq!t4 4 .qqq%)|< * +j882111aaa7; 8 2111aaas?C .
 $( )-&-1*
 # 		/
(9(A##tz1##''4:5''//4:=//55C5544
B44**dj8**88DJF88..$*<..  DJ.   02,,,r)   Nc                 
   |i }||z
  }|dk    r| j         |z
  }n| j         |z
  dz   }t          d||z
            }|dk    r| j        }| j        }	| j        }
n| j        }|dk    rMt          j        || j        f          t          j	        z  } | j
        j        |fd| j         i|}|                    | j        d| j         f         | j        d| j         f                    |                                }|dk    rt          d|          }t          j        |d|df         |j        fd          }t          j        |	d|df         |j        dddf         fd          }	t          j        |
d|df         |j        fd          }
||z  }||z  }nt          j        ||j        fd          }|dk    r;t          d|          }|d|||z   dz
  f         j        }|	d|||z   f         j        }	|
d|||z   dz
  f         j        }
t          j        | j                  dddddf         }|	j        d         |z
  }t)          d|dz             D ]}|||z
  ||z   |z
           |z  }t          j        | j                  d         }t          j        || j        | j        f          }t          j	        |d||z
  <   |	d|          |z  ||
|dz
  d         |	|d         z  z
  z  |||z
  d<   n|j        ||         }|S )	a  
        Compute "forward" autocovariances, Cov(t, t+j)

        Parameters
        ----------
        shift : int
            The number of period to shift forwards when computing the
            autocovariance. This has the opposite sign as `lag` from the
            `smoothed_state_autocovariance` method.
        start : int, optional
            The start of the interval (inclusive) of autocovariances to compute
            and return.
        end : int, optional
            The end of the interval (exclusive) autocovariances to compute and
            return. Note that since it is an exclusive endpoint, the returned
            autocovariances do not include the value at this index.
        extend_kwargs : dict, optional
            Keyword arguments containing updated state space system matrices
            for handling out-of-sample autocovariance computations in
            time-varying state space models.

        Nr   r   r   .r   axisN.)nobsmaxr   predicted_state_covry   r|   r   zerosr7   nanr   extendinitialize_knownpredicted_staterd   concatenateTeyer8   shaperange)r6   shiftr   r   extend_kwargsnmax_insamplen_postsampleLPNacovrB   modresstart_insampleLTtmpLTlengthir   s                        r'   _smoothed_state_autocovariancez.SmootherResults._smoothed_state_autocovariance  s   0  M %K A::9u,LL9u,q0L1cL011 A::+A(A2AA*D !HlDL9::RVCE#$*#ELLLmLLC  !5c49n!E!%!9#ty.!IK K K**,,Czz!$QNAc>??&:$;$'$>$@FGI I INAc>??&:$;$'$;CG$D$F()+ + + NAc>??&:$;$'$E$G()+ + + ~%'~tS-D&EANNNA:: E]]N3sU{Q6679B#~cEk1124A#~cEkAo5568A F4=))$111*5EWQZ%'F1eai(( A A519Ve^a%7785@&''	2C 8Qt}=>>D,.FD(.5(()'E6'
U"cAeaijjMAeffI,E&EF %'(()) 6%)$Dr)   r   c                 N   d}|t          |          dk    r||||f}||| j        v r| j        |         S d}|dk     r| }d}|||t          d          ||}|dz   }|d}||r|dk    r|| j        |z
  dz   }n| j        }|i }|dk     s|dk     rt          d          ||k     rt          d          |dk    r| j        t          d	          |dk    rl|| j        dz   k    r^| j        }|| j        dz   k    r8t          j        |d
|df         | j        d
ddf         fd          j	        }n@|j	        ||         }n/|dk    r| j
        |s|| j        dz   k    r|dk    rYt          j        | j        | j        |f          t          j        z  }	t          j        |	| j
        d
d|dz
  f         fd          }n| j
        d
|dz
  |dz
  f         }|                    ddd          }n|dk    r,| j
        %|r#|| j        dz   k     r| j
        j	        ||         }nR|r|                     ||||          }n6|                     |||z
  ||z
  |          }
|
                    ddd          }|	|d         }n|                    ddd          }|
|| j        |<   |S )a  
        Compute state vector autocovariances, conditional on the full dataset

        Computes:

        .. math::

            Cov(\alpha_t - \hat \alpha_t, \alpha_{t - j} - \hat \alpha_{t - j})

        where the `lag` argument gives the value for :math:`j`. Thus when
        the `lag` argument is positive, the autocovariance is between the
        current and previous periods, while if `lag` is negative the
        autocovariance is between the current and future periods.

        Parameters
        ----------
        lag : int, optional
            The number of period to shift when computing the autocovariance.
            Default is 1.
        t : int, optional
            A specific period for which to compute and return the
            autocovariance. Cannot be used in combination with `start` or
            `end`. See the Returns section for details on how this
            parameter affects what is what is returned.
        start : int, optional
            The start of the interval (inclusive) of autocovariances to compute
            and return. Cannot be used in combination with the `t` argument.
            See the Returns section for details on how this parameter affects
            what is what is returned. Default is 0.
        end : int, optional
            The end of the interval (exclusive) autocovariances to compute and
            return. Note that since it is an exclusive endpoint, the returned
            autocovariances do not include the value at this index. Cannot be
            used in combination with the `t` argument. See the Returns section
            for details on how this parameter affects what is what is returned
            and what the default value is.
        extend_kwargs : dict, optional
            Keyword arguments containing updated state space system matrices
            for handling out-of-sample autocovariance computations in
            time-varying state space models.

        Returns
        -------
        acov : ndarray
            Array of autocovariance matrices. If the argument `t` is not
            provided, then it is shaped `(k_states, k_states, n)`, while if `t`
            given then the third axis is dropped and the array is shaped
            `(k_states, k_states)`.

            The output under the default case differs somewhat based on the
            state space model and the sign of the lag. To see how these cases
            differ, denote the output at each time point as Cov(t, t-j). Then:

            - If `lag > 0` (and the model is either time-varying or
              time-invariant), then the returned array is shaped `(*, *, nobs)`
              and each entry [:, :, t] contains Cov(t, t-j). However, the model
              does not have enough information to compute autocovariances in
              the pre-sample period, so that we cannot compute Cov(1, 1-lag),
              Cov(2, 2-lag), ..., Cov(lag, 0). Thus the first `lag` entries
              have all values set to NaN.

            - If the model is time-invariant and `lag < -1` or if `lag` is
              0 or -1, and the model is either time-invariant or time-varying,
              then the returned array is shaped `(*, *, nobs)` and each
              entry [:, :, t] contains Cov(t, t+j). Moreover, all entries are
              available (i.e. there are no NaNs).

            - If the model is time-varying and `lag < -1` and `extend_kwargs`
              is not provided, then the returned array is shaped
              `(*, *, nobs - lag + 1)`.

            - However, if the model is time-varying and `lag < -1`, then
              `extend_kwargs` can be provided with `lag - 1` additional
              matrices so that the returned array is shaped `(*, *, nobs)` as
              usual.

            More generally, the dimension of the last axis will be
            `start - end`.

        Notes
        -----
        This method computes:

        .. math::

            Cov(\alpha_t - \hat \alpha_t, \alpha_{t - j} - \hat \alpha_{t - j})

        where the `lag` argument determines the autocovariance order :math:`j`,
        and `lag` is an integer (positive, zero, or negative). This method
        cannot compute values associated with time points prior to the sample,
        and so it returns a matrix of NaN values for these time points.
        For example, if `start=0` and `lag=2`, then assuming the output is
        assigned to the variable `acov`, we will have `acov[..., 0]` and
        `acov[..., 1]` as matrices filled with NaN values.

        Based only on the "current" results object (i.e. the Kalman smoother
        applied to the sample), there is not enough information to compute
        Cov(t, t+j) for the last `lag - 1` observations of the sample. However,
        the values can be computed for these time points using the transition
        equation of the state space representation, and so for time-invariant
        state space models we do compute these values. For time-varying models,
        this can also be done, but updated state space matrices for the
        out-of-sample time points must be provided via the `extend_kwargs`
        argument.

        See [1]_, Chapter 4.7, for all details about how these autocovariances
        are computed.

        The `t` and `start`/`end` parameters compute and return only the
        requested autocovariances. As a result, using these parameters is
        recommended to reduce the computational burden, particularly if the
        number of observations and/or the dimension of the state vector is
        large.

        References
        ----------
        .. [1] Durbin, James, and Siem Jan Koopman. 2012.
               Time Series Analysis by State Space Methods: Second Edition.
               Oxford University Press.
        Nr   FT-Cannot specify both `t` and `start` or `end`.r   /Negative `t`, `start`, or `end` is not allowed.`end` must be after `start`zdCannot return smoothed state covariances if those values have not been computed by Kalman smoothing..r   r   )r   )lenr   rX   r   r|   RuntimeErrorr   r   r   r   r}   r   r8   r   	transposer   )r6   lagtr   r   r   	cache_keyforward_autocovariancesr   nansouts              r'   smoothed_state_autocovariancez-SmootherResults.smoothed_state_autocovarianceA  s   v 	 C$6$6!$;$;a,I !TAAA7	BB #(77$C&*# =e/3?LMMM=Ea%C =E;&  377}7Li#o)i M 199aNOOO;;:;;;!88/7  4 5 5 5
 !88ty1},,*Ddi!m##~#uvv+&(@bcc(JK    veCi( Qhh46B+ C03ty1}0D0D zzxs CDDrvM~46sHS1WH}EF   23	#'8I3IJ>>!Q**DD Qhh46B' C,/$)a-,?,?.0s;DD ' 	.::= ; B B
 99cCi} : N N}}Q1-- =7DD>>!Q**D  >BD0;r)   Tc           
         |||t          d          ||}|dz   }|
| j        dz
  }|| j        }|dk     s|dk     rt          d          ||k    rt          d          | j        t          d          d}| j        |j        k     rt          |d	z            | j        |j        k    r | j        |j        k    r| j        |j        k    st          |d
z            | j        j                                        D ]{}	|	dk    r	t          | |	          j
        d         dk    }
t          ||	          j
        d         dk    }|
r|st          |d|	 dz            |
s|rt          |d|	 dz            ||?t          j        t          j        t          j        |t                                        }|| j        k    r| j        j        st#          d          i }| j        j                                        D ]_}	|	dk    r	t          | |	          }t          ||	          }|j
        d         |j
        d         k    r|d|j
        d         df         ||	<   `|j                            | j        j                  \  }} |j        d7||d|j        }|                     ||          j        }du rdndu r|j        ndk     r
|j        z   g }g }dk    r>|D ]:\  }}|k     r|                    ||f           #|                    ||f           ;n|}t1          |          dk    rt3          |d         d                   d}d}d}d}d}d}d}d}d}d} d}!t1          |          dk    rt5          | \  }"}#t          j        |"d         |"d         dz             }$| j        ddd|j        f                                         }t          j        ||j                            t@                    <   |j        |$         }|j        j        |$         }||z
  }|j                                        }%t3          ||j                  }&|&|j        z
  }'|'dk    r>t          j!        |%t          j"        |'| j        f          t          j        z  gd          }%i }(| j        j                                        D ]9}	|	dk    r	t          | |	          }|j
        d         dk    r|dd|&f         |(|	<   : |j        j#        |%fi |(})tH          j%        &                    |           }*|)'                    |*           |)(                                } t1          |          dk    rt          j        |"d         dz             }$|"d         z
  }+||+d         }||+d         }||+d         }t          j        ||          },tS          j*        |)|,|$d|j+                  \  }-}.}.|)j,        j        }/|/j
        d         dk    r|/|,         }/||/dd|ddf         }/|-dddd|f         }-t          j-        |-d         |/ddddddddf         z  d          .                    dddd          }t5          fd|D              \  }"}#|"|"d         z
  }0|.                    dddd          dddd|0|#f         }||0|#f         }||z  }||0|#f         }||0|#f         }||d         }|d         }| j        d||f         }1|| j        k    rBt3          || j                  }2 | j        d7|2|d|}3t          j!        |1|3j/        fd          }1|1|z
  j        }!||!d         }!t1          |          dk    r5t5          | \  }"}#|"|"d         z
  }0||0|#f         }||0|#f         }||0|#f         }t1          |          dk    rt5          | \  }4}5t          j0        |4          }6t          j        |4          }7|  |j        d7|6|7dz   d|j        j        }8n$|                     |6|7dz             j        j        }8| j        j        |6|7dz            }9|9|8z
  }:|4|6z
  };|9|;|5f         }<|8|;|5f         }=|:|;|5f         }>| j,        j
        d         dk    r| j,        d         d         }nn|| j        k    r'| j,        d||f         .                    ddd          }n<|t          d          |j1        dk    r	|d         }n|.                    ddd          }|2                    ||||          }?||dddd|f         }|?dd|f         }?||?z  }@|@|>z  }A||@d         }@|Ad         }An
d}Ad}=d}<d}>d}@tg          d7i d |Ad!|d"|>d#|d$|d%|@d&|d'|=d(|<d)|d*|d+|d,|d-|d.|d/| d0|!d1|d2|d3|d4d5|d6|}B|BS )8u  
        Compute the news and impacts associated with a data release

        Parameters
        ----------
        previous : SmootherResults
            Prior results object relative to which to compute the news. This
            results object must have identical state space representation for
            the prior sample period so that the only difference is that this
            results object has updates to the observed data.
        t : int, optional
            A specific period for which to compute the news. Cannot be used in
            combination with `start` or `end`.
        start : int, optional
            The start of the interval (inclusive) of news to compute. Cannot be
            used in combination with the `t` argument. Default is the last
            period of the sample (`nobs - 1`).
        end : int, optional
            The end of the interval (exclusive) of news to compute. Note that
            since it is an exclusive endpoint, the returned news do not include
            the value at this index. Cannot be used in combination with the `t`
            argument.
        revisions_details_start : bool or int, optional
            The period at which to beging computing the detailed impacts of
            data revisions. Any revisions prior to this period will have their
            impacts grouped together. If a negative integer, interpreted as
            an offset from the end of the dataset. If set to True, detailed
            impacts are computed for all revisions, while if set to False, all
            revisions are grouped together. Default is False. Note that for
            large models, setting this to be near the beginning of the sample
            can cause this function to be slow.
        design : array, optional
            Design matrix for the period `t` in time-varying models. If this
            model has a time-varying design matrix, and the argument `t` is out
            of this model's sample, then a new design matrix for period `t`
            must be provided. Unused otherwise.
        state_index : array_like, optional
            An optional index specifying a subset of states to use when
            constructing the impacts of revisions and news. For example, if
            `state_index=[0, 1]` is passed, then only the impacts to the
            observed variables arising from the impacts to the first two
            states will be returned.

        Returns
        -------
        news_results : SimpleNamespace
            News and impacts associated with a data release. Includes the
            following attributes:

            - `update_impacts`: update to forecasts of impacted variables from
              the news. It is equivalent to E[y^i | post] - E[y^i | revision],
              where y^i are the variables of interest. In [1]_, this is
              described as "revision" in equation (17).
            - `revision_detailed_impacts`: update to forecasts of variables
              impacted variables from data revisions. It is
              E[y^i | revision] - E[y^i | previous], and does not have a
              specific notation in [1]_, since there for simplicity they assume
              that there are no revisions.
            - `news`: the unexpected component of the updated data. Denoted
              I = y^u - E[y^u | previous], where y^u are the data points that
              were newly incorporated in a data release (but not including
              revisions to data points that already existed in the previous
              release). In [1]_, this is described as "news" in equation (17).
            - `revisions`: y^r(updated) - y^r(previous) for periods in
              which detailed impacts were computed
            - `revisions_all` : y^r(updated) - y^r(previous) for all revisions
            - `gain`: the gain matrix associated with the "Kalman-like" update
              from the news, E[y I'] E[I I']^{-1}. In [1]_, this can be found
              in the equation For E[y_{k,t_k} \mid I_{v+1}] in the middle of
              page 17.
            - `revision_weights` weights on observations for the smoothed
              signal
            - `update_forecasts`: forecasts of the updated periods used to
              construct the news, E[y^u | previous].
            - `update_realized`: realizations of the updated periods used to
              construct the news, y^u.
            - `revised`: revised observations of the periods that were revised
              and for which detailed impacts were computed
            - `revised`: revised observations of the periods that were revised
            - `revised_prev`: previous observations of the periods that were
              revised and for which detailed impacts were computed
            - `revised_prev_all`: previous observations of the periods that
              were revised and for which detailed impacts were computed
            - `prev_impacted_forecasts`: previous forecast of the periods of
              interest, E[y^i | previous].
            - `post_impacted_forecasts`: forecast of the periods of interest
              after taking into account both revisions and updates,
              E[y^i | post].
            - `revision_results`: results object that updates the `previous`
              results to take into account data revisions.
            - `revision_results`: results object associated with the revisions
            - `revision_impacts`: total impacts from all revisions (both
              grouped and detailed)
            - `revisions_ix`: list of `(t, i)` positions of revisions in endog
            - `revisions_details`: list of `(t, i)` positions of revisions to
              endog for which details of impacts were computed
            - `revisions_grouped`: list of `(t, i)` positions of revisions to
              endog for which impacts were grouped
            - `revisions_details_start`: period in which revision details start
              to be computed
            - `updates_ix`: list of `(t, i)` positions of updates to endog
            - `state_index`: index of state variables used to compute impacts

        Notes
        -----
        This method computes the effect of new data (e.g. from a new data
        release) on smoothed forecasts produced by a state space model, as
        described in [1]_. It also computes the effect of revised data on
        smoothed forecasts.

        References
        ----------
        .. [1] Bańbura, Marta and Modugno, Michele. 2010.
               "Maximum likelihood estimation of factor models on data sets
               with arbitrary pattern of missing data."
               No 1189, Working Paper Series, European Central Bank.
               https://EconPapers.repec.org/RePEc:ecb:ecbwps:20101189.
        .. [2] Bańbura, Marta, and Michele Modugno.
               "Maximum likelihood estimation of factor models on datasets with
               arbitrary pattern of missing data."
               Journal of Applied Econometrics 29, no. 1 (2014): 133-160.

        Nr   r   r   r   r   zECannot compute news without having applied the Kalman smoother first.zThis results object has %s and so it does not appear to by an extension of `previous`. Can only compute the news by comparing this results set to previous results objects.z"fewer observations than `previous`z0different state space dimensions than `previous`obsr   ztime-varying z while `previous` does notztime-invariant rL   z[Cannot compute the impacts of news on periods outside of the sample in time-varying models..)r   r   TFr   )	compute_t	compute_jcompute_prior_weightsr   .Nr      c                 ,    g | ]}|d          k    |S )r   r    )r$   srevisions_details_starts     r'   
<listcomp>z(SmootherResults.news.<locals>.<listcomp>|  s3     -8 -8 -8t666 666r)   .r   r   zcModel has time-varying design matrix, so an updated time-varying matrix for period `t` is required.)r   r   r   update_impactsrevision_detailed_impactsnews	revisionsrevisions_allgainrevision_weightsupdate_forecastsupdate_realizedrevisedrevised_allrevised_prevrevised_prev_allprev_impacted_forecastspost_impacted_forecastsrevision_resultsrevision_impactsrevisions_ixrevisions_detailsrevisions_groupedr   
updates_ixstate_indexr    )4rX   r   r|   r7   r8   r9   r   shapesr;   r   r   r   
atleast_1dsortr   inttime_invariantr   
diff_endogrB   r   predictsmoothed_forecastsr   r   r   ziparanger2   r   r   astypeboolr   r   cloner   Initializationfrom_results
initializerd   r
   _compute_smoothed_state_weightsr   designnansumr   	forecastsminndimsmoothed_state_gainr   )Cr6   previousr   r   r   r   r  r   error_ssr%   tvtv_prevr   matprev_matr   r   r   r   r   r   r   r   revised_endogr   r   r   r   r   r   r   r   r   r   	revised_j	revised_pr   	tmp_endogtmp_nobsoos_nobsclone_kwargsrev_modinitoffsetr   smoothed_state_weights_ZTix_jrevised_impact_forecastspredict_startpupdate_tupdate_kupdate_start_tupdate_end_tr  realizedforecasts_errorix_tr   r   update_forecasts_error
state_gainobs_gainr   r   sC        `                                                             r'   r   zSmootherResults.news#  s   | =e/3?LMMM=Ea%C =IME;)C 199aNOOO%<<:;;;"* 7 8 8 8  9x}$$X )+ + , , ,  000!222!222X )+ + , , , :$))++ 
	9 
	9Ce||s##)"-1Bh,,226:G 9' 9  -8C -8 -8 -8 "8 9 9 9 9' 9  -8c -8 -8 -8 "8 9 9 9 "-C88899; ;K ??4:#<?  * + + +
 :$))++ 	C 	CCe||$$$Cx--Hy}x~b111%(hnR.@.A.A)A%Bc" $,>#<#<TZ\#J#J j #3("2 #3S#3 #3$1#3 #33E 	 "&,,S #/ #" #""4 	 
 #d**&'##$--&.m##$q((&.m6M&M#"Q&&$ 5 51...%,,aV4444%,,aV4444	5 !- |q  &),q/!*<*A'C 'C# 	$(! |q  #&#5 Iy	)A,	"0ABBI !Jqqq.8=.'89>>@@M <>6M(*11$778'/)4K  (~/	: )+;;M
 &,,..I3..H(-/H!||Nrx4<(@AABFJ,  	
 Lz(--// < <%<<dC((9R=1$$(+C(N(;L%*hn*9EEEEG!0==dCCDt$$$&~~// $%%)) I&=&/ma&79 9	 19Q<?%fgg./8)&''2	 IeS11	 99	.38>K K K -&1 ^%8A;??IB *AAA{AAA-.B.qqq!!![/@A + $&9*95D!!!T111,-.45$7 $7 $77@yAq!7L7L !" (+ -8 -8 -8 -8+-8 -8 -8 (9$	9 !9Q</ %..q!Q::111aaa;?<K L ! &dIo6	,<y,H) "$	/2+D)O< ='7':$0I!0L- !3CsNC %%*** #E+;+@ A A,$, C'SC C4AC C+->-q{;!,E ,E ,E( !9 7!89: }#3A#6  |q  #&#5 Iyy|+D)$	/:M%dIo6K/i@ z??Q!$j!1HhVH--N6(++L',H, %(lQ.>% %#% %%7 	 -44($q( 5 * **<Q  z|N<!3C$CDH&2O n,D&tX~6O(x8%4T8^%D" { #q((V,Y7	!!S%)^4>>q!QGG >$ &@ A A A [A%%#I.FF#--aA66F!55%S 6 O OJ &111k 12';7
 
*H &(>>N }#A;!/!2!N#"O%)"H  ;% ;% ;% *>;% '@&?;% (';%  i;% (-;% ;%" .-#;%( .-);%. ,O/;%6 G7;%< $=;%D &E;%J .-K;%N %<$;O;%R %<$;S;%V .-W;%Z .-[;%^ &_;%d 0/e;%j 0/k;%n %<$;o;%r "zs;%v $w;%z 
r)   c           	      \    |||t          d          ||}|dz   }|
 j        dz
  }| j        }i |dk     s|dk     rt          d          ||k    rt          d          ||z
  }t                     fd fd}t          j        | j        f          }t          ||          D ]}	 ||	          ||	|z
  <   t          j        f          }
t                    D ]	}|         \  }}t          |dz             D ]}|         \  }} d	|          } d	|          }                     ||z
  |
          }t          j        |||dz            |z  |||dz            j	        z            x|
||f<   |
||f<   ||k    ra d|          }||k    r|
||fxx         |||f         z  cc<   |
||fxx         |||f         z  cc<   |
||fxx         |||f         z  cc<   |t          j
                            |
          z  }||d         }|S )ae  
        Cov(\tilde \alpha_{t}, I) Var(I, I)^{-1}

        where I is a vector of forecast errors associated with
        `update_indices`.

        Parameters
        ----------
        updates_ix : list
            List of indices `(t, i)`, where `t` denotes a zero-indexed time
            location and `i` denotes a zero-indexed endog variable.
        Nr   r   r   r   r   c                 $   t          |           }|j        d         dk    re|j        k     r|d|f         }nW| vs|          j        d         |j        z
  k    rt          d|  d          |          d|j        z
  f         }n|d         }|S )Nr   r   .zModel has time-varying zP matrix, so an updated time-varying matrix for the extension period is required.r   )r   r   r   rX   )whichr   r  r   r   r6   s       r'   get_matz4SmootherResults.smoothed_state_gain.<locals>.get_mat[  s    $&&Cy}q  ty==c1f+CC]22)%06r:a$)mKK( *65 *6 *6 *6 7 7 7 (.sA	M/ABCC&kJr)   c                    t          j        
j        	f          }t          	          D ]U}|         \  }}
                    | |z
  |           } d|          }||||dz            j        z  |d d ||dz   f<   V|S )Nr   r   r   r  r   )r   r   r8   r   r   r   )r   tmp1r   t_ik_ir   Z_ir   r7  	n_updatesr6   r   s          r'   get_cov_state_revisionzCSmootherResults.smoothed_state_gain.<locals>.get_cov_state_revisionm  s    8T]I677D9%% = =%a=S99C1M : C Cgh,,#'#c#'k*:*<#<QQQ!a%Z  Kr)   r  r9  r   )rX   r   r   r   r   r8   r   r   squeezer   linalginv)r6   r   r   r   r   r   	n_periodsr?  r:  r   tmp2r   r;  r<  jt_jk_jr=  Z_jr   Hr   r7  r>  s   ``   `                @@r'   r  z#SmootherResults.smoothed_state_gain3  s    =e/3?LMMM=Ea%C =IME;)C M 199aNOOO%<<:;;; %K	
OO		 	 	 	 	 	$	 	 	 	 	 	 	 	 	 xDM9=>>uc"" 	8 	8A44Q77DUOO xI.//y!! 	2 	2A!!}HC1q5\\ 2 2%a=Sgh,,gh,,99c	S : G G*,*C!G$t+c#cAg+.>.@@+ + QT
T!Q$Z #::	3//AAvvQT


aSk1



QT


aSk1


QT


aSk1


'2, bimmD)))=7Dr)   c           
         | j         <t          j        | j        j        | j                  | _         t          j        | j        j        | j                  | _        t          j        | j        j        | j                  | _	        t          | j                  D ]}| j        j        d         dk    rdn|}| j        j        d         dk    rdn|}| j        j        d         dk    rdn|}| j        d d |f                             t"                     }t          j        | j        d d d d |f         | j        d d |f                   | j        d d |f         z   | j         d d |f<   | j        |         dk    rt          j        | j        d d |f<   | j        ||f         | j         ||f         z
  | j        ||f<   t          j        t          j        | j        d d d d |f         | j        d d d d |f                   | j        d d d d |f         j                  | j        d d d d |f         z   | j	        d d d d |f<   | j         | j        | j	        fS )Nr   r   r   r   )r   r   r   r  r   rL   r/  r   forecasts_error_covr   r   r   r  r   obs_interceptr   r  r  dotr{   r   r   rB   r|   r   )r6   r   design_t	obs_cov_tobs_intercept_tmasks         r'   _get_smoothed_forecastsz'SmootherResults._get_smoothed_forecasts  s   #+')x0D6:j(B (B (BD$ -34:FFF * 17tzJJJ . 49%% 2 2 $ 1! 4 9 911q!%!3A!6!!;!;AA	'+'9'?'Ba'G'G!!QQQQT*11$77713K111h/1DQQQT1J2 2&qqq/'9:2;(A. =#a'';=6D2111a48JtQw'$*B47*KK .tQw7 ?AfF4;qqq!!!X~62111aaa7;= =K111h/1? ? LAAAy1	?22111aaa7;; $*.
 	
r)   c                 6    |                                  d         S )Nr   rR  r6   s    r'   r  z"SmootherResults.smoothed_forecasts      ++--a00r)   c                 6    |                                  d         S )Nr   rT  rU  s    r'   smoothed_forecasts_errorz(SmootherResults.smoothed_forecasts_error  rV  r)   c                 6    |                                  d         S )Nr   rT  rU  s    r'   smoothed_forecasts_error_covz,SmootherResults.smoothed_forecasts_error_cov  rV  r)   r{   c           
      F   |dvrt          d          t          j        | j        d| j                  \  }}}| j        j        j        }| j        j        j        }| j        j        j        }|dk    r/|-|dd|ddf         }|dddd|f         }|dd|ddf         }|dk    rt          j
        |d         |ddddddddf         z  d	                              d
ddd          }t          j
        |d         |ddddddddf         z  d	                              d
ddd          }t          j
        |d         |dddddddf         z  d	                              d
dd          }|| j        j        j        ddddddf         z  }	|	                    d
ddd          }	| |ddddddf         z  }
|
                    d
ddd          }
||ddddddf         z  }|                    d
ddd          }|| j        ddddf         z  }|	|
||fS )a4  
        Decompose smoothed output into contributions from observations

        Parameters
        ----------
        decomposition_of : {"smoothed_state", "smoothed_signal"}
            The object to perform a decomposition of. If it is set to
            "smoothed_state", then the elements of the smoothed state vector
            are decomposed into the contributions of each observation. If it
            is set to "smoothed_signal", then the predictions of the
            observation vector based on the smoothed state vector are
            decomposed. Default is "smoothed_state".
        state_index : array_like, optional
            An optional index specifying a subset of states to use when
            constructing the decomposition of the "smoothed_signal". For
            example, if `state_index=[0, 1]` is passed, then only the
            contributions of observed variables to the smoothed signal arising
            from the first two states will be returned. Note that if not all
            states are used, the contributions will not sum to the smoothed
            signal. Default is to use all states.

        Returns
        -------
        data_contributions : array
            Contributions of observations to the decomposed object. If the
            smoothed state is being decomposed, then `data_contributions` are
            shaped `(nobs, k_states, nobs, k_endog)`, where the
            `(t, m, j, p)`-th element is the contribution of the `p`-th
            observation at time `j` to the `m`-th state at time `t`. If the
            smoothed signal is being decomposed, then `data_contributions` are
            shaped `(nobs, k_endog, nobs, k_endog)`, where the
            `(t, k, j, p)`-th element is the contribution of the `p`-th
            observation at time `j` to the smoothed prediction of the `k`-th
            observation at time `t`.
        obs_intercept_contributions : array
            Contributions of the observation intercept to the decomposed
            object. If the smoothed state is being decomposed, then
            `obs_intercept_contributions` are shaped
            `(nobs, k_states, nobs, k_endog)`, where the `(t, m, j, p)`-th
            element is the contribution of the `p`-th observation intercept at
            time `j` to the `m`-th state at time `t`. If the smoothed signal
            is being decomposed, then `obs_intercept_contributions` are shaped
            `(nobs, k_endog, nobs, k_endog)`, where the `(t, k, j, p)`-th
            element is the contribution of the `p`-th observation at time `j`
            to the smoothed prediction of the `k`-th observation at time `t`.
        state_intercept_contributions : array
            Contributions of the state intercept to the decomposed object. If
            the smoothed state is being decomposed, then
            `state_intercept_contributions` are shaped
            `(nobs, k_states, nobs, k_states)`, where the `(t, m, j, l)`-th
            element is the contribution of the `l`-th state intercept at
            time `j` to the `m`-th state at time `t`. If the smoothed signal
            is being decomposed, then `state_intercept_contributions` are
            shaped `(nobs, k_endog, nobs, k_endog)`, where the
            `(t, k, j, l)`-th element is the contribution of the `p`-th
            observation at time `j` to the smoothed prediction of the `k`-th
            observation at time `t`.
        prior_contributions : array
            Contributions of the prior to the decomposed object. If the
            smoothed state is being decomposed, then `prior_contributions` are
            shaped `(nobs, k_states, k_states)`, where the `(t, m, l)`-th
            element is the contribution of the `l`-th element of the prior
            mean to the `m`-th state at time `t`. If the smoothed signal is
            being decomposed, then `prior_contributions` are shaped
            `(nobs, k_endog, k_states)`, where the `(t, k, l)`-th
            element is the contribution of the `l`-th element of the prior mean
            to the smoothed prediction of the `k`-th observation at time `t`.

        Notes
        -----
        Denote the smoothed state at time :math:`t` by :math:`\alpha_t`. Then
        the smoothed signal is :math:`Z_t \alpha_t`, where :math:`Z_t` is the
        design matrix operative at time :math:`t`.
        )r{   smoothed_signalz[Invalid value for `decomposition_of`. Must be one of "smoothed_state" or "smoothed_signal".T)r   r   r\  Nr   r   r   r   r   r   )rX   r
   r  r   r   r  r   rL  state_interceptr   r  r   rB   initial_state)r6   decomposition_ofr   weightsstate_intercept_weightsprior_weightsr%  dTcTdata_contributionsobs_intercept_contributionsstate_intercept_contributionsprior_contributionss                r'   get_smoothed_decompositionz*SmootherResults.get_smoothed_decomposition  s   X #HHH N O O O 1
$djJ J J 	8(-
 Z Z%'Z') 000[5LAAA{AAA%&BaaaK/0G)!!![!!!*;<M 000
 i	 2R4D!!!8K5L L%&( ( ((1	!Q1(=(=  ')i'	2R4D!!!8K5LL' ' '!	!Q1-- $ Ii(2aaaD!!!m+<<  !	!Q**  %tz'7'9$4:J'KK/99!Q1EE
 (/hD!!!T1114D1E&E# (11!Q1== 	$ $bqqq$)9&:: 	& *33Aq!Q?? 	&
 ,d.@tQQQ.OO"$?-/BD 	Dr)   )FrD   )r   NNNN)NNNTNN)NNNN)r{   N)re   rf   rg   rh   r   r   r-   r   r   _model_attributes_attributesr_   rb   r   r   r   r  rR  rt   r  rX  rZ  ri  ru   rv   s   @r'   r,   r,     s       D DL   '714HHK2 2 2 2 2 28E2 E2 E2P 6:\ \ \ \| BF>B` ` ` `D 6:DHN N N N` =A48h h h hT%
 %
 %
N 1 1 X1 1 1 X1 1 1 X1 ;K/3TD TD TD TD TD TD TD TDr)   r,   )rh   numpyr   typesr   )statsmodels.tsa.statespace.representationr   (statsmodels.tsa.statespace.kalman_filterr   r    statsmodels.tsa.statespace.toolsr   r   r	   statsmodels.tsa.statespacer
   r   ri   rj   rk   rl   rm   rn   ro   rq   rp   rr   r   r,   r    r)   r'   <module>rr     s        ! ! ! ! ! ! C C C C C CE E E E E E E EG G G G G G G G G G < < < < < < < <    ''*>>56 
     G G G G G\ G G GTxD xD xD xD xDm xD xD xD xD xDr)   