
    M/Phx                         d Z ddlZddlZddlZddlmZ ddlmZ ddl	m
Z
 dZdZeez  ZddZ G d	 d
e          Z G d d          ZdS )z{
State Space Representation, Kalman Filter, Smoother, and Simulation Smoother

Author: Chad Fulton
License: Simplified-BSD
    N   )KalmanSmoother)CFASimulationSmoother)tools   c                    | &t          | t          j        t          j        f          rt          j                            |           S t          | t          j        j        t          j        j        f          r| S t          | d          )ag  Turn `seed` into a `numpy.random.Generator` instance.
    Parameters
    ----------
    seed : {None, int, Generator, RandomState}, optional
        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
        singleton is used.
        If `seed` is an int, a new ``numpy.random.RandomState`` instance
        is used, seeded with `seed`.
        If `seed` is already a ``numpy.random.Generator`` or
        ``numpy.random.RandomState`` instance then that instance is used.
    Returns
    -------
    seed : {`numpy.random.Generator`, `numpy.random.RandomState`}
        Random number generator.
    Nz9 cannot be used to seed a numpy.random.Generator instance)

isinstancenumbersIntegralnpintegerrandomdefault_rngRandomState	Generator
ValueError)seeds    n/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/tsa/statespace/simulation_smoother.pycheck_random_stater      s      |z$)92:(FGG|y$$T***	D290")2EF	G	G =D < < < = = 	=    c                   b     e Zd ZdZg dZ	 	 	 d fd	Z	 	 	 ddZ	 	 ddZddZ	 	 	 ddZ	 xZ
S )SimulationSmoothera  
    State space representation of a time series process, with Kalman filter
    and smoother, and with simulation 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`.
    simulation_smooth_results_class : class, optional
        Default results class to use to save output of simulation smoothing.
        Default is `SimulationSmoothResults`. If specified, class must extend
        from `SimulationSmoothResults`.
    simulation_smoother_classes : dict, optional
        Dictionary with BLAS prefixes as keys and classes as values.
    **kwargs
        Keyword arguments may be used to provide default values for state space
        matrices, for Kalman filtering options, for Kalman smoothing
        options, or for Simulation smoothing options.
        See `Representation`, `KalmanFilter`, and `KalmanSmoother` for more
        details.
    )simulate_statesimulate_disturbancesimulate_allNc                      t                      j        |||fi | |t          }|| _        ||nt          j                                        | _        i | _        d S N)super__init__SimulationSmoothResultssimulation_smooth_results_classr   prefix_simulation_smoother_mapcopy_simulators)selfk_endogk_statesk_posdefr!   simulation_smoother_classeskwargs	__class__s          r   r   zSimulationSmoother.__init__R   s     	Xx	
 	
+1	
 	
 	
 +2.E+/N, +6 ('5::<< 	+ r   c                     |]d}|r
|t           z  }|r
|t          z  }|r
|t          z  }|dk    r1t          |du |du |du g           }|rt	          d          | j        }|S )a  
        Get simulation output bitmask

        Helper method to get final simulation output bitmask from a set of
        optional arguments including the bitmask itself and possibly boolean
        flags.

        Parameters
        ----------
        simulation_output : int, optional
            Simulation output bitmask. If this is specified, it is simply
            returned and the other arguments are ignored.
        simulate_state : bool, optional
            Whether or not to include the state in the simulation output.
        simulate_disturbance : bool, optional
            Whether or not to include the state and observation disturbances
            in the simulation output.
        simulate_all : bool, optional
            Whether or not to include all simulation output.
        \*\*kwargs
            Additional keyword arguments. Present so that calls to this method
            can use \*\*kwargs without clearing out additional arguments.
        Nr   zKInvalid simulation output options: given options would result in no output.)SIMULATION_STATESIMULATION_DISTURBANCESIMULATION_ALLallr   smoother_output)r%   simulation_outputr   r   r   r*   argument_sets          r   get_simulation_outputz(SimulationSmoother.get_simulation_outputf   s    8 $ ! 6!%55!# <!%;;! 4!^3! !A%% $'"d*,@D,H D(( $ $     1$ &0 1 1 1 %)$8!  r   Fc                 
   ||                      ||          } |j        di | t          j        |j        d          }t          j        |j        d          }|j        d |         |j        d |         f}|r||fz   }|S )Nrandom_stateTr#    )	simulatorsimulater   arraygenerated_obsgenerated_stateT)	r%   nsimulationsr:   r7   return_simulatorr*   simulated_obssimulated_stateouts	            r   	_simulatezSimulationSmoother._simulate   s     |,OOI 		$$V$$$ !8tDDD(9#<4HHH}}- ,/1 	%$C
r   c                 4    |                      dd||          S )Nr   kfs)r2   methodnobsr7   )simulation_smoother)r%   r@   r7   s      r   r:   zSimulationSmoother.simulator   s,    ''!E-95A ( C C 	Cr   rG   c                 t   |                                 }|dk    r"|dvrt          d          t          |           S |dk    rt          d|z            || j        }t	          |t
                    st          d          |                                 \  }}}	}
} | j        |fi |}|                    d|          }|                    d	| j	                  }|                    d
| j
                  }|                    d| j                  }|                    d| j                  }|                    d| j                  }|                    d| j                  }|                    d| j                  }| j        |         } || j        |         ||||||||||          } || ||          }|S )a  
        Retrieve a simulation smoother for the statespace model.

        Parameters
        ----------
        simulation_output : int, optional
            Determines which simulation smoother output is calculated.
            Default is all (including state and disturbances).
        method : {'kfs', 'cfa'}, optional
            Method for simulation smoothing. If `method='kfs'`, then the
            simulation smoother is based on Kalman filtering and smoothing
            recursions. If `method='cfa'`, then the simulation smoother is
            based on the Cholesky Factor Algorithm (CFA) approach. The CFA
            approach is not applicable to all state space models, but can be
            faster for the cases in which it is supported.
        results_class : class, optional
            Default results class to use to save output of simulation
            smoothing. Default is `SimulationSmoothResults`. If specified,
            class must extend from `SimulationSmoothResults`.
        prefix : str
            The prefix of the datatype. Usually only used internally.
        nobs : int
            The number of observations to simulate. If set to anything other
            than -1, only simulation will be performed (i.e. simulation
            smoothing will not be performed), so that only the `generated_obs`
            and `generated_state` attributes will be available.
        random_state : {None, int, Generator, RandomState}, optional
            If `seed` is None (or `np.random`), the `numpy.random.RandomState`
            singleton is used.
            If `seed` is an int, a new ``numpy.random.RandomState`` instance
            is used, seeded with `seed`.
            If `seed` is already a ``numpy.random.Generator`` or
            ``numpy.random.RandomState`` instance then that instance is used.
        **kwargs
            Additional keyword arguments, used to set the simulation output.
            See `set_simulation_output` for more details.

        Returns
        -------
        SimulationSmoothResults
        cfa)Nr   rK   zTCan only retrieve simulations of the state vector using the CFA simulation smoother.rG   zJInvalid simulation smoother method "%s". Valid methods are "kfs" or "cfa".NzInvalid results class provided.r1   filter_methodinversion_methodstability_methodconserve_memoryfilter_timingloglikelihood_burn	tolerancer6   )lowerr   r   r!   
issubclassr    _initialize_smootherr4   getrN   rO   rP   rQ   rR   rS   rT   r"   _statespaces)r%   r2   rH   results_classprefixrI   r7   r*   dtypecreate_smoothercreate_filtercreate_statespacer1   rN   rO   rP   rQ   rR   rS   rT   clsrJ   resultss                          r   rJ   z&SimulationSmoother.simulation_smoother   s@   X  U?? 55  "N O O O(...u__ <>DE F F F   @M -)@AA 	@>??? %%'' 	I7H 7D67H A A9?A A !**%68IJJ 

?D4FGG!::&8&*&;= =!::&8&*&;= = **%6%)%9; ;

?#'#57 7#ZZ(<(,(?A AJJ{DN;;	 1&9!cf%+-=9&8/t	
 
  -&9-9; ; ; r   )NNN)NNNN)NNFr   )NrG   NNrK   N)__name__
__module____qualname____doc__simulation_outputsr   r4   rE   r:   rJ   __classcell__)r+   s   @r   r   r   0   s         :   4815-1     ( 7;HL+/8! 8! 8! 8!t DH#(   &C C C C
 BGBD)-f f f f f f f fr   r   c                      e Zd ZdZddZed             Zej        d             Zed             Zej        d             Zed             Z	e	j        d	             Z	ed
             Z
e
j        d             Z
ed             Zed             Zed             Zed             Zed             Zed             Zed             Z	 	 	 	 	 	 	 	 	 	 ddZdS )r    a"  
    Results from applying the Kalman smoother and/or filter to a state space
    model.

    Parameters
    ----------
    model : Representation
        A Statespace representation
    simulation_smoother : {{prefix}}SimulationSmoother object
        The Cython simulation smoother object with which to simulation smooth.
    random_state : {None, int, Generator, RandomState}, optional
        If `seed` is None (or `np.random`), the `numpy.random.RandomState`
        singleton is used.
        If `seed` is an int, a new ``numpy.random.RandomState`` instance
        is used, seeded with `seed`.
        If `seed` is already a ``numpy.random.Generator`` or
        ``numpy.random.RandomState`` instance then that instance is used.

    Attributes
    ----------
    model : Representation
        A Statespace representation
    dtype : dtype
        Datatype of representation matrices
    prefix : str
        BLAS prefix of representation matrices
    simulation_output : int
        Bitmask controlling simulation output.
    simulate_state : bool
        Flag for if the state is included in simulation output.
    simulate_disturbance : bool
        Flag for if the state and observation disturbances are included in
        simulation output.
    simulate_all : bool
        Flag for if simulation output should include everything.
    generated_measurement_disturbance : ndarray
        Measurement disturbance variates used to genereate the observation
        vector.
    generated_state_disturbance : ndarray
        State disturbance variates used to genereate the state and
        observation vectors.
    generated_obs : ndarray
        Generated observation vector produced as a byproduct of simulation
        smoothing.
    generated_state : ndarray
        Generated state vector produced as a byproduct of simulation smoothing.
    simulated_state : ndarray
        Simulated state.
    simulated_measurement_disturbance : ndarray
        Simulated measurement disturbance.
    simulated_state_disturbance : ndarray
        Simulated state disturbance.
    Nc                     || _         |j        | _        |j        | _        || _        t	          |          | _        d | _        d | _        d | _        d | _	        d | _
        d | _        d | _        d S r   )modelr[   r\   _simulation_smootherr   r7   "_generated_measurement_disturbance_generated_state_disturbance_generated_obs_generated_state_simulated_state"_simulated_measurement_disturbance_simulated_state_disturbance)r%   rj   rJ   r7   s       r   r   z SimulationSmoothResults.__init__X  ss    
l[
$7!.|<< 37/,0)" $ $26/,0)))r   c                     | j         j        S r   rk   r2   r%   s    r   r2   z)SimulationSmoothResults.simulation_outputh  s    (::r   c                     || j         _        d S r   rt   r%   values     r   r2   z)SimulationSmoothResults.simulation_outputl  s    6;!333r   c                 :    t          | j        t          z            S r   boolr2   r-   ru   s    r   r   z&SimulationSmoothResults.simulate_statep  s    D*-==>>>r   c                 z    t          |          r| j        t          z  | _        d S | j        t           z  | _        d S r   rz   rw   s     r   r   z&SimulationSmoothResults.simulate_statet  sB    ;; 	P%)%;>N%ND"""%)%;?O>O%OD"""r   c                 :    t          | j        t          z            S r   r{   r2   r.   ru   s    r   r   z,SimulationSmoothResults.simulate_disturbance{  s    D*-CCDDDr   c                 z    t          |          r| j        t          z  | _        d S | j        t           z  | _        d S r   r~   rw   s     r   r   z,SimulationSmoothResults.simulate_disturbance  sJ    ;; 	B&)?? """ &*@)@@ """r   c                 :    t          | j        t          z            S r   r{   r2   r/   ru   s    r   r   z$SimulationSmoothResults.simulate_all  s    D*^;<<<r   c                 z    t          |          r| j        t          z  | _        d S | j        t           z  | _        d S r   r   rw   s     r   r   z$SimulationSmoothResults.simulate_all  s?    ;; 	N%)%;n%LD"""%)%;~o%MD"""r   c                     | j         Mt          j        | j        j        d                              | j        j        | j        j                  | _         | j         S )a~  
        Randomly drawn measurement disturbance variates

        Used to construct `generated_obs`.

        Notes
        -----

        .. math::

           \varepsilon_t^+ ~ N(0, H_t)

        If `disturbance_variates` were provided to the `simulate()` method,
        then this returns those variates (which were N(0,1)) transformed to the
        distribution above.
        NTr8   )	rl   r   r<   rk    measurement_disturbance_variatesreshaperj   rI   r&   ru   s    r   !generated_measurement_disturbancez9SimulationSmoothResults.generated_measurement_disturbance  sX    $ 2:68h)J7 7 7"74:?DJ4FGG 3 66r   c                     | j         Mt          j        | j        j        d                              | j        j        | j        j                  | _         | j         S )a  
        Randomly drawn state disturbance variates, used to construct
        `generated_state` and `generated_obs`.

        Notes
        -----

        .. math::

            \eta_t^+ ~ N(0, Q_t)

        If `disturbance_variates` were provided to the `simulate()` method,
        then this returns those variates (which were N(0,1)) transformed to the
        distribution above.
        NTr8   )	rm   r   r<   rk   state_disturbance_variatesr   rj   rI   r(   ru   s    r   generated_state_disturbancez3SimulationSmoothResults.generated_state_disturbance  sX    " ,402)D1 1 1"74:?DJ4GHH - 00r   c                 h    | j         %t          j        | j        j        d          | _         | j         S )a(  
        Generated vector of observations by iterating on the observation and
        transition equations, given a random initial state draw and random
        disturbance draws.

        Notes
        -----

        .. math::

            y_t^+ = d_t + Z_t \alpha_t^+ + \varepsilon_t^+
        NTr8   )rn   r   r<   rk   r=   ru   s    r   r=   z%SimulationSmoothResults.generated_obs  s<     &"$()7d# # #D ""r   c                 h    | j         %t          j        | j        j        d          | _         | j         S )a  
        Generated vector of states by iterating on the transition equation,
        given a random initial state draw and random disturbance draws.

        Notes
        -----

        .. math::

            \alpha_{t+1}^+ = c_t + T_t \alpha_t^+ + \eta_t^+
        NTr8   )ro   r   r<   rk   r>   ru   s    r   r>   z'SimulationSmoothResults.generated_state  s<      ($&H)9% % %D! $$r   c                 h    | j         %t          j        | j        j        d          | _         | j         S )z
        Random draw of the state vector from its conditional distribution.

        Notes
        -----

        .. math::

            \alpha ~ p(\alpha \mid Y_n)
        NTr8   )rp   r   r<   rk   rC   ru   s    r   rC   z'SimulationSmoothResults.simulated_state  s<      ($&H)9% % %D! $$r   c                 h    | j         %t          j        | j        j        d          | _         | j         S )z
        Random draw of the measurement disturbance vector from its conditional
        distribution.

        Notes
        -----

        .. math::

            \varepsilon ~ N(\hat \varepsilon, Var(\hat \varepsilon \mid Y_n))
        NTr8   )rq   r   r<   rk   !simulated_measurement_disturbanceru   s    r   r   z9SimulationSmoothResults.simulated_measurement_disturbance  s=     2:68h)K7 7 7D3 66r   c                 h    | j         %t          j        | j        j        d          | _         | j         S )z
        Random draw of the state disturbanc e vector from its conditional
        distribution.

        Notes
        -----

        .. math::

            \eta ~ N(\hat \eta, Var(\hat \eta \mid Y_n))
        NTr8   )rr   r   r<   rk   simulated_state_disturbanceru   s    r   r   z3SimulationSmoothResults.simulated_state_disturbance  s=     ,402)E1 1 1D- 00r   rK   Fc                 x   |rd}t          j        |t                     ||t          d          |A|                                }| j        j        | j        j        z  }|d|         }||d         }|5d}t          j        |t                     ||t          d          ||}|}|d}|d}d| _        d| _	        d| _
        d| _        d| _
        d| _        d| _        d| _        |
| j        }
nt!          |
          }
| j                                        \  }}}}}|rt          d          | j                            |           |H| j                            t+          j        || j        	                                          |
           n| j                            |
           |H| j                            t+          j        || j        	                                          |
           n| j                            |
           |l|	r4| j                            t+          j        || j        	                     nP| j                            t+          j        || j        	          d
           n| j                            |
           | j                            |           dS )ac  
        Perform simulation smoothing

        Does not return anything, but populates the object's `simulated_*`
        attributes, as specified by simulation output.

        Parameters
        ----------
        simulation_output : int, optional
            Bitmask controlling simulation output. Default is to use the
            simulation output defined in object initialization.
        measurement_disturbance_variates : array_like, optional
            If specified, these are the shocks to the measurement equation,
            :math:`\varepsilon_t`. If unspecified, these are automatically
            generated using a pseudo-random number generator. If specified,
            must be shaped `nsimulations` x `k_endog`, where `k_endog` is the
            same as in the state space model.
        state_disturbance_variates : array_like, optional
            If specified, these are the shocks to the state equation,
            :math:`\eta_t`. If unspecified, these are automatically
            generated using a pseudo-random number generator. If specified,
            must be shaped `nsimulations` x `k_posdef` where `k_posdef` is the
            same as in the state space model.
        initial_state_variates : array_like, optional
            If specified, this is the state vector at time zero, which should
            be shaped (`k_states` x 1), where `k_states` is the same as in the
            state space model. If unspecified, but the model has been
            initialized, then that initialization is used.
        initial_state_variates : array_likes, optional
            Random values to use as initial state variates. Usually only
            specified if results are to be replicated (e.g. to enforce a seed)
            or for testing. If not specified, random variates are drawn.
        pretransformed_measurement_disturbance_variates : bool, optional
            If `measurement_disturbance_variates` is provided, this flag
            indicates whether it should be directly used as the shocks. If
            False, then it is assumed to contain draws from the standard Normal
            distribution that must be transformed using the `obs_cov`
            covariance matrix. Default is False.
        pretransformed_state_disturbance_variates : bool, optional
            If `state_disturbance_variates` is provided, this flag indicates
            whether it should be directly used as the shocks. If False, then it
            is assumed to contain draws from the standard Normal distribution
            that must be transformed using the `state_cov` covariance matrix.
            Default is False.
        pretransformed_initial_state_variates : bool, optional
            If `initial_state_variates` is provided, this flag indicates
            whether it should be directly used as the initial_state. If False,
            then it is assumed to contain draws from the standard Normal
            distribution that must be transformed using the `initial_state_cov`
            covariance matrix. Default is False.
        random_state : {None, int, Generator, RandomState}, optional
            If `seed` is None (or `np.random`), the `numpy.random.RandomState`
            singleton is used.
            If `seed` is an int, a new ``numpy.random.RandomState`` instance
            is used, seeded with `seed`.
            If `seed` is already a ``numpy.random.Generator`` or
            ``numpy.random.RandomState`` instance then that instance is used.
        disturbance_variates : bool, optional
            Deprecated, please use pretransformed_measurement_shocks and
            pretransformed_state_shocks instead.

            .. deprecated:: 0.14.0

               Use ``measurement_disturbance_variates`` and
               ``state_disturbance_variates`` as replacements.

        pretransformed : bool, optional
            Deprecated, please use pretransformed_measurement_shocks and
            pretransformed_state_shocks instead.

            .. deprecated:: 0.14.0

               Use ``pretransformed_measurement_disturbance_variates`` and
               ``pretransformed_state_disturbance_variates`` as replacements.
        Nz~`disturbance_variates` keyword is deprecated, use `measurement_disturbance_variates` and `state_disturbance_variates` instead.zzCannot use `disturbance_variates` in combination with  `measurement_disturbance_variates` or `state_disturbance_variates`.z`pretransformed` keyword is deprecated, use `pretransformed_measurement_disturbance_variates` and `pretransformed_state_disturbance_variates` instead.zCannot use `pretransformed` in combination with  `pretransformed_measurement_disturbance_variates` or `pretransformed_state_disturbance_variates`.FzThe simulation smoother currently cannot replace the underlying _{{prefix}}Representation model object if it changes (which happens e.g. if the dimensions of some system matrices change.)r[   )r\   )pretransformed)warningswarnFutureWarningr   ravelrj   rI   r&   rl   rm   ro   rn   rp   rq   rr   r7   r   rW   _initialize_staterk   $set_measurement_disturbance_variatesr   r<   r\   %draw_measurement_disturbance_variatesset_state_disturbance_variatesdraw_state_disturbance_variatesset_initial_stateset_initial_state_variatesdraw_initial_state_variatesr;   )r%   r2   disturbance_variatesr   r   initial_state_variatesr   /pretransformed_measurement_disturbance_variates)pretransformed_state_disturbance_variates%pretransformed_initial_state_variatesr7   msgn_mdsr[   r\   r]   r^   r_   s                     r   r;   z SimulationSmoothResults.simulate#  s   l  +<C M#}---0<1=  "B C C C $/';'A'A'C'C$
$**<<3G3O0-A%&&-I*%KC M#}---?K@L DE E E )" @<J9:B>C;4<8=5 37/,0) $" $ $26/,0) ,LL-l;;L J++-- 	I7H 	L K L L L 	
$$F$333 ,7%JJ9#z+ + ++0577N K     %KK  
 &1%DD34:FFFLLNNH E    
 %EE  
 "-4 );;H34:FFF    )DDH34:FFF#( E     %AA   	!**+<=====r   r   )
rK   NNNNNNNFN)rb   rc   rd   re   r   propertyr2   setterr   r   r   r   r   r=   r>   rC   r   r   r;   r9   r   r   r    r    !  s       4 4l1 1 1 1  ; ; X; < < < ? ? X? P P P E E XE  B B ! B = = X= N N N 7 7 X7. 1 1 X1, # # X#& % % X%$ % % X%" 7 7 X7& 1 1 X1& *,&*26,0(, $AE;?7<"D> D> D> D> D> D>r   r    r   )re   r
   r   numpyr   kalman_smootherr   cfa_simulation_smootherr    r   r-   r.   r/   r   r   r    r9   r   r   <module>r      s          + + + + + + : : : : : :        -- = = = =2n n n n n n n nbF> F> F> F> F> F> F> F> F> F>r   