
    M/Ph4                    <   d Z ddlmZ ddlZddlmZ ddlmZ ddl	m
Z
mZ ddlmc mZ ddlmZ ddlmZ d	d
lmZmZmZ d	dlmZ d	dlmZmZmZmZ dddddddddddddZ G d de          Z  G d de          Z! G d de          Z" ej#        e"e!           dS ) z
Univariate structural time series models

TODO: tests: "** On entry to DLASCL, parameter number  4 had an illegal value"

Author: Chad Fulton
License: Simplified-BSD
    )warnN)Appender)Bunch)OutputWarningSpecificationWarning)hpfilter)lagmat   )MLEModel
MLEResultsMLEResultsWrapper)Initialization)companion_matrixconstrain_stationary_univariate!unconstrain_stationary_univariateprepare_exog	irregularfixed interceptdeterministic constantrandom walklocal levelfixed slopedeterministic trendrandom walk with drift local linear deterministic trendlocal linear trendsmooth trendrandom trend)r
                                    c                        e Zd ZdZ	 	 	 	 	 	 	 	 	 	 d fd	Z fdZd ZddZdd	Ze	d
             Z
e	d             Ze	d             Ze	d             Zd Zd Z fdZ	 	 ddZ xZS )UnobservedComponentsa`F  
    Univariate unobserved components time series model

    These are also known as structural time series models, and decompose a
    (univariate) time series into trend, seasonal, cyclical, and irregular
    components.

    Parameters
    ----------

    endog : array_like
        The observed time-series process :math:`y`
    level : {bool, str}, optional
        Whether or not to include a level component. Default is False. Can also
        be a string specification of the level / trend component; see Notes
        for available model specification strings.
    trend : bool, optional
        Whether or not to include a trend component. Default is False. If True,
        `level` must also be True.
    seasonal : {int, None}, optional
        The period of the seasonal component, if any. Default is None.
    freq_seasonal : {list[dict], None}, optional.
        Whether (and how) to model seasonal component(s) with trig. functions.
        If specified, there is one dictionary for each frequency-domain
        seasonal component.  Each dictionary must have the key, value pair for
        'period' -- integer and may have a key, value pair for
        'harmonics' -- integer. If 'harmonics' is not specified in any of the
        dictionaries, it defaults to the floor of period/2.
    cycle : bool, optional
        Whether or not to include a cycle component. Default is False.
    autoregressive : {int, None}, optional
        The order of the autoregressive component. Default is None.
    exog : {array_like, None}, optional
        Exogenous variables.
    irregular : bool, optional
        Whether or not to include an irregular component. Default is False.
    stochastic_level : bool, optional
        Whether or not any level component is stochastic. Default is False.
    stochastic_trend : bool, optional
        Whether or not any trend component is stochastic. Default is False.
    stochastic_seasonal : bool, optional
        Whether or not any seasonal component is stochastic. Default is True.
    stochastic_freq_seasonal : list[bool], optional
        Whether or not each seasonal component(s) is (are) stochastic.  Default
        is True for each component.  The list should be of the same length as
        freq_seasonal.
    stochastic_cycle : bool, optional
        Whether or not any cycle component is stochastic. Default is False.
    damped_cycle : bool, optional
        Whether or not the cycle component is damped. Default is False.
    cycle_period_bounds : tuple, optional
        A tuple with lower and upper allowed bounds for the period of the
        cycle. If not provided, the following default bounds are used:
        (1) if no date / time information is provided, the frequency is
        constrained to be between zero and :math:`\pi`, so the period is
        constrained to be in [0.5, infinity].
        (2) If the date / time information is provided, the default bounds
        allow the cyclical component to be between 1.5 and 12 years; depending
        on the frequency of the endogenous variable, this will imply different
        specific bounds.
    mle_regression : bool, optional
        Whether or not to estimate regression coefficients by maximum likelihood
        as one of hyperparameters. Default is True.
        If False, the regression coefficients are estimated by recursive OLS,
        included in the state vector.
    use_exact_diffuse : bool, optional
        Whether or not to use exact diffuse initialization for non-stationary
        states. Default is False (in which case approximate diffuse
        initialization is used).

    See Also
    --------
    statsmodels.tsa.statespace.structural.UnobservedComponentsResults
    statsmodels.tsa.statespace.mlemodel.MLEModel

    Notes
    -----

    These models take the general form (see [1]_ Chapter 3.2 for all details)

    .. math::

        y_t = \mu_t + \gamma_t + c_t + \varepsilon_t

    where :math:`y_t` refers to the observation vector at time :math:`t`,
    :math:`\mu_t` refers to the trend component, :math:`\gamma_t` refers to the
    seasonal component, :math:`c_t` refers to the cycle, and
    :math:`\varepsilon_t` is the irregular. The modeling details of these
    components are given below.

    **Trend**

    The trend component is a dynamic extension of a regression model that
    includes an intercept and linear time-trend. It can be written:

    .. math::

        \mu_t = \mu_{t-1} + \beta_{t-1} + \eta_{t-1} \\
        \beta_t = \beta_{t-1} + \zeta_{t-1}

    where the level is a generalization of the intercept term that can
    dynamically vary across time, and the trend is a generalization of the
    time-trend such that the slope can dynamically vary across time.

    Here :math:`\eta_t \sim N(0, \sigma_\eta^2)` and
    :math:`\zeta_t \sim N(0, \sigma_\zeta^2)`.

    For both elements (level and trend), we can consider models in which:

    - The element is included vs excluded (if the trend is included, there must
      also be a level included).
    - The element is deterministic vs stochastic (i.e. whether or not the
      variance on the error term is confined to be zero or not)

    The only additional parameters to be estimated via MLE are the variances of
    any included stochastic components.

    The level/trend components can be specified using the boolean keyword
    arguments `level`, `stochastic_level`, `trend`, etc., or all at once as a
    string argument to `level`. The following table shows the available
    model specifications:

    +----------------------------------+--------------------------------------+--------------------+--------------------------------------------------+
    | Model name                       | Full string syntax                   | Abbreviated syntax | Model                                            |
    +==================================+======================================+====================+==================================================+
    | No trend                         | `'irregular'`                        | `'ntrend'`         | .. math:: y_t = \varepsilon_t                    |
    +----------------------------------+--------------------------------------+--------------------+--------------------------------------------------+
    | Fixed intercept                  | `'fixed intercept'`                  |                    | .. math:: y_t = \mu                              |
    +----------------------------------+--------------------------------------+--------------------+--------------------------------------------------+
    | Deterministic constant           | `'deterministic constant'`           | `'dconstant'`      | .. math:: y_t = \mu + \varepsilon_t              |
    +----------------------------------+--------------------------------------+--------------------+--------------------------------------------------+
    | Local level                      | `'local level'`                      | `'llevel'`         | .. math:: y_t &= \mu_t + \varepsilon_t \\        |
    |                                  |                                      |                    |     \mu_t &= \mu_{t-1} + \eta_t                  |
    +----------------------------------+--------------------------------------+--------------------+--------------------------------------------------+
    | Random walk                      | `'random walk'`                      | `'rwalk'`          | .. math:: y_t &= \mu_t \\                        |
    |                                  |                                      |                    |     \mu_t &= \mu_{t-1} + \eta_t                  |
    +----------------------------------+--------------------------------------+--------------------+--------------------------------------------------+
    | Fixed slope                      | `'fixed slope'`                      |                    | .. math:: y_t &= \mu_t \\                        |
    |                                  |                                      |                    |     \mu_t &= \mu_{t-1} + \beta                   |
    +----------------------------------+--------------------------------------+--------------------+--------------------------------------------------+
    | Deterministic trend              | `'deterministic trend'`              | `'dtrend'`         | .. math:: y_t &= \mu_t + \varepsilon_t \\        |
    |                                  |                                      |                    |     \mu_t &= \mu_{t-1} + \beta                   |
    +----------------------------------+--------------------------------------+--------------------+--------------------------------------------------+
    | Local linear deterministic trend | `'local linear deterministic trend'` | `'lldtrend'`       | .. math:: y_t &= \mu_t + \varepsilon_t \\        |
    |                                  |                                      |                    |     \mu_t &= \mu_{t-1} + \beta + \eta_t          |
    +----------------------------------+--------------------------------------+--------------------+--------------------------------------------------+
    | Random walk with drift           | `'random walk with drift'`           | `'rwdrift'`        | .. math:: y_t &= \mu_t \\                        |
    |                                  |                                      |                    |     \mu_t &= \mu_{t-1} + \beta + \eta_t          |
    +----------------------------------+--------------------------------------+--------------------+--------------------------------------------------+
    | Local linear trend               | `'local linear trend'`               | `'lltrend'`        | .. math:: y_t &= \mu_t + \varepsilon_t \\        |
    |                                  |                                      |                    |     \mu_t &= \mu_{t-1} + \beta_{t-1} + \eta_t \\ |
    |                                  |                                      |                    |     \beta_t &= \beta_{t-1} + \zeta_t             |
    +----------------------------------+--------------------------------------+--------------------+--------------------------------------------------+
    | Smooth trend                     | `'smooth trend'`                     | `'strend'`         | .. math:: y_t &= \mu_t + \varepsilon_t \\        |
    |                                  |                                      |                    |     \mu_t &= \mu_{t-1} + \beta_{t-1} \\          |
    |                                  |                                      |                    |     \beta_t &= \beta_{t-1} + \zeta_t             |
    +----------------------------------+--------------------------------------+--------------------+--------------------------------------------------+
    | Random trend                     | `'random trend'`                     | `'rtrend'`         | .. math:: y_t &= \mu_t \\                        |
    |                                  |                                      |                    |     \mu_t &= \mu_{t-1} + \beta_{t-1} \\          |
    |                                  |                                      |                    |     \beta_t &= \beta_{t-1} + \zeta_t             |
    +----------------------------------+--------------------------------------+--------------------+--------------------------------------------------+

    Following the fitting of the model, the unobserved level and trend
    component time series are available in the results class in the
    `level` and `trend` attributes, respectively.

    **Seasonal (Time-domain)**

    The seasonal component is modeled as:

    .. math::

        \gamma_t = - \sum_{j=1}^{s-1} \gamma_{t+1-j} + \omega_t \\
        \omega_t \sim N(0, \sigma_\omega^2)

    The periodicity (number of seasons) is s, and the defining character is
    that (without the error term), the seasonal components sum to zero across
    one complete cycle. The inclusion of an error term allows the seasonal
    effects to vary over time (if this is not desired, :math:`\sigma_\omega^2`
    can be set to zero using the `stochastic_seasonal=False` keyword argument).

    This component results in one parameter to be selected via maximum
    likelihood: :math:`\sigma_\omega^2`, and one parameter to be chosen, the
    number of seasons `s`.

    Following the fitting of the model, the unobserved seasonal component
    time series is available in the results class in the `seasonal`
    attribute.

    **Frequency-domain Seasonal**

    Each frequency-domain seasonal component is modeled as:

    .. math::

        \gamma_t & =  \sum_{j=1}^h \gamma_{j, t} \\
        \gamma_{j, t+1} & = \gamma_{j, t}\cos(\lambda_j)
                        + \gamma^{*}_{j, t}\sin(\lambda_j) + \omega_{j,t} \\
        \gamma^{*}_{j, t+1} & = -\gamma^{(1)}_{j, t}\sin(\lambda_j)
                            + \gamma^{*}_{j, t}\cos(\lambda_j)
                            + \omega^{*}_{j, t}, \\
        \omega^{*}_{j, t}, \omega_{j, t} & \sim N(0, \sigma_{\omega^2}) \\
        \lambda_j & = \frac{2 \pi j}{s}

    where j ranges from 1 to h.

    The periodicity (number of "seasons" in a "year") is s and the number of
    harmonics is h.  Note that h is configurable to be less than s/2, but
    s/2 harmonics is sufficient to fully model all seasonal variations of
    periodicity s.  Like the time domain seasonal term (cf. Seasonal section,
    above), the inclusion of the error terms allows for the seasonal effects to
    vary over time.  The argument stochastic_freq_seasonal can be used to set
    one or more of the seasonal components of this type to be non-random,
    meaning they will not vary over time.

    This component results in one parameter to be fitted using maximum
    likelihood: :math:`\sigma_{\omega^2}`, and up to two parameters to be
    chosen, the number of seasons s and optionally the number of harmonics
    h, with :math:`1 \leq h \leq \lfloor s/2 \rfloor`.

    After fitting the model, each unobserved seasonal component modeled in the
    frequency domain is available in the results class in the `freq_seasonal`
    attribute.

    **Cycle**

    The cyclical component is intended to capture cyclical effects at time
    frames much longer than captured by the seasonal component. For example,
    in economics the cyclical term is often intended to capture the business
    cycle, and is then expected to have a period between "1.5 and 12 years"
    (see Durbin and Koopman).

    .. math::

        c_{t+1} & = \rho_c (\tilde c_t \cos \lambda_c t
                + \tilde c_t^* \sin \lambda_c) +
                \tilde \omega_t \\
        c_{t+1}^* & = \rho_c (- \tilde c_t \sin \lambda_c  t +
                \tilde c_t^* \cos \lambda_c) +
                \tilde \omega_t^* \\

    where :math:`\omega_t, \tilde \omega_t iid N(0, \sigma_{\tilde \omega}^2)`

    The parameter :math:`\lambda_c` (the frequency of the cycle) is an
    additional parameter to be estimated by MLE.

    If the cyclical effect is stochastic (`stochastic_cycle=True`), then there
    is another parameter to estimate (the variance of the error term - note
    that both of the error terms here share the same variance, but are assumed
    to have independent draws).

    If the cycle is damped (`damped_cycle=True`), then there is a third
    parameter to estimate, :math:`\rho_c`.

    In order to achieve cycles with the appropriate frequencies, bounds are
    imposed on the parameter :math:`\lambda_c` in estimation. These can be
    controlled via the keyword argument `cycle_period_bounds`, which, if
    specified, must be a tuple of bounds on the **period** `(lower, upper)`.
    The bounds on the frequency are then calculated from those bounds.

    The default bounds, if none are provided, are selected in the following
    way:

    1. If no date / time information is provided, the frequency is
       constrained to be between zero and :math:`\pi`, so the period is
       constrained to be in :math:`[0.5, \infty]`.
    2. If the date / time information is provided, the default bounds
       allow the cyclical component to be between 1.5 and 12 years; depending
       on the frequency of the endogenous variable, this will imply different
       specific bounds.

    Following the fitting of the model, the unobserved cyclical component
    time series is available in the results class in the `cycle`
    attribute.

    **Irregular**

    The irregular components are independent and identically distributed (iid):

    .. math::

        \varepsilon_t \sim N(0, \sigma_\varepsilon^2)

    **Autoregressive Irregular**

    An autoregressive component (often used as a replacement for the white
    noise irregular term) can be specified as:

    .. math::

        \varepsilon_t = \rho(L) \varepsilon_{t-1} + \epsilon_t \\
        \epsilon_t \sim N(0, \sigma_\epsilon^2)

    In this case, the AR order is specified via the `autoregressive` keyword,
    and the autoregressive coefficients are estimated.

    Following the fitting of the model, the unobserved autoregressive component
    time series is available in the results class in the `autoregressive`
    attribute.

    **Regression effects**

    Exogenous regressors can be pass to the `exog` argument. The regression
    coefficients will be estimated by maximum likelihood unless
    `mle_regression=False`, in which case the regression coefficients will be
    included in the state vector where they are essentially estimated via
    recursive OLS.

    If the regression_coefficients are included in the state vector, the
    recursive estimates are available in the results class in the
    `regression_coefficients` attribute.

    References
    ----------
    .. [1] Durbin, James, and Siem Jan Koopman. 2012.
       Time Series Analysis by State Space Methods: Second Edition.
       Oxford University Press.
    FNTc                 p    | _         | _        ||nd _         j        dk     _        |r#d |D              _        d |D              _        ng  _        g  _        t          d  j        D                        _        | _        ||nd _	         j	        dk     _
        |	 _        |
 _        | _        | _        |dgt           j                  z   _        ndt          |          t          |          k    r=t#          d                    t          |          t          |                              | _        | _        | _        | _        | _        d  _        t1           j         t2                    r.| _        d _         g d}|D ]=}t5           |          dur)t7          d	|z  t8                     t;           |d           > j        }|d
k    s|dk    rd _        d
 _        n|dk    r	d _         n|dk    s|dk    rd _        d _         d _        n|dk    s|dk    rd _        d _         d _        d _        n]|dk    s|dk    rd _         d _        d _        n:|dk    rd _         d _        n$|dk    s|dk    rd _        d _         d _        d _        n|dk    s|dk    r$d _        d _         d _        d _        d _        n|dk    s|dk    rd _         d _        d _        d _        n|dk    s|dk    r+d _        d _         d _        d _        d _        d _        nk|dk    s|dk    r$d _        d _         d _        d _        d _        n;|dk    s|dk    rd _         d _        d _        d _        nt#          d |z            |r%|s#t7          d!t8                     d _         d _         j        sv j         r j        sh j        r j        sZ j        r j        sL j        rt           j                  s1 j        r j        s# j
        st7          d"t8                     d _         j        r j        d#k     rt#          d$           j        r j        D ]}|d#k     rt#          d%           j        d&z   j         d#z  z   j          j        z  d'z  z   j        d(z  z   j         j        z  d)z  z   _         j        %t>                                j        d            _        tC          |          \   _"        } j"        dk     _#         j        d&z
   j        z   _$        tK          d*  j        D                        j        z   _&         j        d#z   _'         j          j        z    j$        z    j&        z    j'        z    j	        z    j          j"        z  z   } j         j         z   j         j        z  z    j         j        z  z   tK           fd+tQ           j                  D                        j        z  z    j         j'        z  z    j
        z   }|                     d,d            _)        d _*        |dk    r j        st#          d-          d&}d _*        |dk    rd&} tW                      j,        ||f||d.|  -                                  j"        dk    rd j.        _/         j0         j1        _0        |G j1        j2         j1        j2        d         nd/}|d0v rd1}n |d2k    rd3}n|d4k    rd5}nd#tf          j4        f}d#tf          j5        z  |d&         z  d#tf          j5        z  |d         z  f _6         xj7        g d6tq          |9                                          z   z  c_7         :                                 d S )7Nr   c                     g | ]
}|d          S )period .0ds     e/var/www/html/test/jupyter/venv/lib/python3.11/site-packages/statsmodels/tsa/statespace/structural.py
<listcomp>z1UnobservedComponents.__init__.<locals>.<listcomp>~  s    )M)M)M!!H+)M)M)M    c                     g | ]@}|                     d t          t          j        |d         dz                                AS )	harmonicsr.   r   )getintnpfloorr0   s     r3   r4   z1UnobservedComponents.__init__.<locals>.<listcomp>  sU     ,$ ,$ ,$ -.EES!H+/!:!:;;-= -= ,$ ,$ ,$r5   c              3   "   K   | ]
}|d k    V  dS )r   Nr/   )r1   xs     r3   	<genexpr>z0UnobservedComponents.__init__.<locals>.<genexpr>  s&       K K1Q K K K K K Kr5   TzSLength of stochastic_freq_seasonal must equal length of freq_seasonal: {!r} vs {!r}F)r   leveltrendstochastic_levelstochastic_trendz[Value of `%s` may be overridden when the trend component is specified using a model string.r   ntrendr   r   	dconstantr   llevelr   rwalkr   r   dtrendr   lldtrendr   rwdriftr   lltrendr   strendr   rtrendz'Invalid level/trend specification: '%s'zWTrend component specified without level component; deterministic level component added.zQSpecified model does not contain a stochastic element; irregular component added.r   z=Seasonal component must have a seasonal period of at least 2.zNFrequency Domain seasonal component must have a seasonal period of at least 2.r
      r#      c              3       K   | ]	}d |z  V  
dS )r   Nr/   )r1   hs     r3   r>   z0UnobservedComponents.__init__.<locals>.<genexpr>"  s&      <<!A<<<<<<r5   c              3   F   K   | ]\  }}j         |         rd |z  ndV  dS )r   r   N)stochastic_freq_seasonal)r1   ixrP   selfs      r3   r>   z0UnobservedComponents.__init__.<locals>.<genexpr>1  sX       D D"a  8<C!a%%! D D D D D Dr5   loglikelihood_burnz"Model has no components specified.)k_posdefexog )AY)g      ?   Q)g      @0   M)g      2@   )r?   r@   seasonalfreq_seasonalcycleautoregressiver   rA   rB   stochastic_seasonalrR   stochastic_cycledamped_cyclecycle_period_boundsmle_regression);r?   r@   seasonal_periodsr`   freq_seasonal_periodsfreq_seasonal_harmonicsanyra   rb   ar_orderrc   r   rA   rB   rd   lenrR   
ValueErrorformatre   rf   rh   use_exact_diffusetrend_specification
isinstancestrgetattrr   r   setattr
trend_mask	_mask_mapr8   r   k_exog
regression_k_seasonal_statessum_k_freq_seas_states_k_cycle_states	enumerate_loglikelihood_burn_unused_statesuper__init__setupssm_time_invariantparam_namesdatafreqr:   infpicycle_frequency_bound
_init_keyslistkeysinitialize_default)rT   endogr?   r@   r`   ra   rb   rc   rW   r   rA   rB   rd   rR   re   rf   rg   rh   rq   kwargstrend_attributes	attributespecpk_statesrV   r   	__class__s   `                          r3   r   zUnobservedComponents.__init__l  s	    

,4,@a-1 	.)M)M})M)M)MD&,$ ,$",$ ,$ ,$D(( *,D&+-D(  K K0J K K KKK
*8*D!"ma/" 0 0#6 #+-1FS*6, 6, -,D)) +,,M0B0BBB 66<f455s=7I7I7K 7KL L L -ED) 0(,!2 $( dj#&& K	)',D$DJ H  H  H- 4 4	4++588 I$%&:< < < D)U333 +D{""dh&6&6!%+6((***!

111T[5H5H!%!
+C((&&$(*:*:!%!
(,%+8((&&$'//!
(,%+8((&&!
!

...$(2B2B!%!
!
+@((<<<J&&!%!
(,%!
+M((111TY5F5F!
(,%!
+C((---1B1B!%!
(,%!
(,%+?((''48+;+;!%!
!
(,%+9((''48+;+;!
!
(,%+9(( !J#'"( ) ) )  	* 	* 9:NP P PDJ$)D! 
	"
	" $ 5
	"
	" $ 5
	" 
	" $(#;
	" #	
	" ),1)3 )3	
	" 
	" !% 5
	" #
	"  /0DF F F!DN= 	0T2Q66 / 0 0 0  	:/ : :q55$9: : :  NT!JJ..56 J J..5	6 	 #+ (1}}T_d'K'KD$ +400d+/ $(#81#<"M<<t;<<<<< ! 	   $zA~J##$$%  ! M	
 $$34 	 !DJ.!DJ./$t}45  D D D D$T%ABBD D D D D ! !T%9:;   	 $*::.BD#I#I  #q==> G !EFFFH!%Dq==H 	8	
&.T	
 	
=C	
 	
 	
 	

 ;??',DH$ !% 0	 &(,	(B49>!$$Dz!!&/##&3##&5## ()"&k# beG)!,,ag8KA8N.N&
"
 	 . . . 15V[[]]0C0CD 	D 	!!!!!r5   c                      t                                                      } j         j        |d<   dD ]}d||<    j        |d<    fdt	           j                  D             |d<    j        |d<   |S )Nr?   )r   r@   rA   rB   Fr`   c                 6    g | ]\  }}|j         |         d S ))r.   r7   )rk   )r1   rS   r   rT   s      r3   r4   z7UnobservedComponents._get_init_kwds.<locals>.<listcomp>  sD     !< !< !< B 6r:< <!< !< !<r5   ra   rc   )r   _get_init_kwdsrr   ri   r   rj   rm   )rT   kwdsattrr   s   `  r3   r   z#UnobservedComponents._get_init_kwdss  s    ww%%'' #/ 4DM- # #"T

0Z!< !< !< !< t9::!< !< !<_ "&r5   c                    i | _         i | _        i | _        i | _        i | _        d}d}| j        r
d| j        d<   | j        rYd| j        dd|f<   d| j        d||f<   | j        rd| j        d||dz   f<   | j	        rd| j        d||f<   d| j        d<   |dz  }|dz  }| j        r5d| j        d||f<   | j
        rd| j        d||f<   d| j        d	<   |dz  }|dz  }| j        r| j        dz
  }d| j        dd|f<   t          t          j        ddg|z  f                                                   | j        d|||z   |||z   f<   | j        rd| j        d||f<   d| j        d
<   |dz  }||z  }| j        r<t'          | j                  D ]&\  }}d|z  }| j        |         }dt          j        z  t/          |          z  }d}t1          d|dz             D ]}	d| j        dd||z   f<   t          j        ||	z            }
t          j        ||	z            }t          j        |
|g| |
gg          }t          j        ||z   ||z   dz            }|| j        d||f<   |dz  }| j        |         r=t          j        |          | j        d|||z   |||z   f<   d|}d| j        |<   ||z  }||z  }(| j        rd| j        dd|f<   d| j        d<   | j         r
d| j        d<   | j!        r8t          j        d          | j        d||dz   ||dz   f<   d| j        d<   |dz  }t          j        d||dz   ||dz   f         | _"        |dz  }| j#        rd| j        dd|f<   | j$        | j        d<   d| j        d<   d| j        d||f<   t          | j$                  j%        | j        d||| j$        z   ||| j$        z   f<   t          j        d|||| j$        z   f         | _&        |dz  }|| j$        z  }| j'        r| j(        r| j)        | j        d<   nt          j*        | j        ddddddf         | j+        d          }|                                t          j,        ddddf         | j        d<   | j-                                        | j        dd||| j)        z   ddf<   t          j        | j)                  | j        d||| j)        z   ||| j)        z   f<   || j)        z  }| j         .                    | j                   | j         .                    | j                   | j         .                    | j                   | j         .                    | j                   t_          | j        0                                          | _1        t_          | j        0                                          | _2        t_          | j        0                                          | _3        t_          | j        0                                          | _4        t_          | j         0                                          | _5        t          j6        | j        j7                  }d|d         |d         f| _8        ts          | j        :                                          }t          j;        | j4        tx                    | _=        | j        rRt'          | j                  D ]=\  }}|r6| j        |         }d|z  }d|}|>                    |          }|| j=        |<   >| j!        r&| j        r|>                    d          }d| j=        |<   t          | j=        dk              | _@        dS )zA
        Setup the structural time series representation
        r   r
   irregular_varg      ?design
transition	selection	level_var	trend_varseasonal_varr   freq_seasonal_var_
cycle_freq
cycle_damp	cycle_varar_coeffar_var	reg_coeffNaxis	state_covdtype)A
parametersparameters_obs_interceptparameters_obs_covparameters_transitionparameters_state_covr   r?   r   r@   rA   rB   r`   ri   r   r:   r_	transposerd   ra   r   rk   rj   r   floatrangecossinarrays_rR   eyerb   rf   re   _idx_cycle_transitionrc   rm   T_idx_ar_transitionrz   rh   ry   repeatnobsnewaxisrW   updater|   valuesk_obs_intercept	k_obs_covk_transitionk_state_covk_paramsdiag_indicesrV   _idx_state_covr   r   onesr9   _var_repetitionsindexrl   _repeat_any_var)rT   ijnrS   rP   r   lambda_ptblockcos_lambda_blocksin_lambda_blocktranstrans_scov_keyr   idx
param_keysis_stochasticnum_harmonicsrepeat_timescov_ixs                         r3   r   zUnobservedComponents.setup  s%   
 (*%"$%'"$&! > 	978D#O4: 		')DHXq!^$+-DH\1a'(z 413q!A#-.$ .0a*+9:)+6QFA: 	+-DH\1a'($ .0a*+9:)+6QFA= 
	%)A')DHXq!^$ q1#'z!233==?? H\1QU7Aa!eG34 ' .0a*+<=).9QFA 	"4#?@@  AE.r2ru9uQxx/"1a!e__  E13DHXq!A#-. (*vh.>'?'?$')vh.>'?'?$H'79I&J(8'8:J&K&M N NE eAE!a%!)O4G?DDH\7G;<FAA04 >@fQiiDH[!AE'1QU7:;9299G9:D-g6FAQ: 
	')DHXq!^$78D&|4  =;<*<8$ 68fQiia!eQqsU239:)+6Q)+|QqsUAacE/I)JD&FA 	')DHXq!^$59]D&z223D%h/*+DH[!Q&' //1 H\1Qt}_#4a$-6GGH lAq4='889 # FAA? 	!" !=A[-k::48HaaaA,=#>	()+ + +%+%5%5%7%7
AAAqqq8H%I"I'')) 1a$+oqqq89 F4;'' q4;!DK-GH T[  	t6777t8999t9:::t<==="4#@#G#G#I#IJJT4;;==>> : A A C CDDt8??AABBDO224455 odh/00*CFCF; $388::;;
 "(8 D D D 	A%.t/L%M%M A A!M  A$($@$DM#$}#4L9299G'--g66F4@D)&1  	.TZ 	.%%k22F,-D!&)"4#81#<==r5   c                 b   || j         j        }| j        rd}n4d}| j        +| j        t          | j                  z
  | j        z
  }|| _        t          | j        |          }| j        r|
                    dddg           n| j        r| j        | j        z   | j        z   | j        z   | j        z   }| j        }|
                    d|f|           |
                    |||z   fd           |
                    ||z   | j        f|           n|
                    d |           || j         _        d S )Ndiffuseapproximate_diffuse)approximate_diffuse_variancer   known)constant
stationary)r   initial_variancerq   r   r   r9   r   rm   rU   r   setrc   r?   r@   r{   r}   r~   initialization)rT   r   diffuse_typek_diffuse_statesinitoffsetlengths          r3   r   z'UnobservedComponents.initialize_default  sk   '/+/8+D(! 		;$LL0L '/MC(:$;$;;dmK !*:'M)EG G G  	)
 HHQ1#H....  	)j4:--../ *+F ]FHHa[,///HHffvo.===HHfvot}5|DDDD HHT<((("&r5   c                 "     | j         |fd|i|S )NrW   )_clone_from_init_kwds)rT   r   rW   r   s       r3   clonezUnobservedComponents.cloneA  s"    )t)%EEdEfEEEr5   c                 "    dt           t          fiS )Nfit)UnobservedComponentsResults"UnobservedComponentsResultsWrapper)rT   s    r3   _res_classesz!UnobservedComponents._res_classesD  s    3:< = 	=r5   c                    t          | d          sg S | j        }| j        }t          j        t          j        |                    r9t          j        |                                           }||         }|||         }i }| j        rt          |          \  }}| j	        rNt          |          \  }}t          j
        |          dz  |d<   | j        rt          j
        |          dz  |d<   n4| j        rt          j
        |          dz  |d<   n| j        j        d         }| j        r~| j        rwt          j                            |                              |                                          |d<   t          j        |t          j        ||d                   z
            }| j        r|| j        d          }	t+          || j        d          }
t          j                            |
                              |	                                          |d	<   t          j        |	t          j        |
|d	                   z
            }t          j        |          |d
<   t          j        |          }| j        r||d<   t1          | j                  D ]\  }}d|}|||<   | j        rb||d<   t          j        t          j                            |d dd f                                       |dd                    d         dd          |d<   | j        j        | j        j        d         nd}|dk    rdt          j        z  dz  |d<   n|dk    rdt          j        z  dz  |d<   n|dk    rdt          j        z  dz  |d<   nt          j        t          j        | j                             st          j!        | j                   |d<   n@t          j        | j         d                   r| j         d         |d<   n| j         d         |d<   | j"        r||d<   g }| j#        $                                D ]C}t          j%        ||                   r|&                    ||                    8|||         z  }D|S )Nr   r   r   r   r   r   both)trimr   r   r   r   r   r
   gGz?r   rX   rY   r    r   r\   r[   r^   $   r   )'hasattrr   rW   r:   rl   isnansqueezer?   r   rB   stdrA   r   rz   rh   linalgpinvdottolistrc   rm   r	   varrd   r   rR   rb   clipr   r   r   isinfr   meanr   r   r   isscalarappend)rT   r   rW   mask_start_paramsresidtrend1cycle2trend2rZ   X	var_residrS   r   r   r   start_paramskeys                     r3   r  z!UnobservedComponents.start_paramsI  s   t\** 	I 
y6"(5//"" 	"HUOO++---D$KEDz : 	&$UOOME6$ ?!)&!1!1-/VF^^Q->k*( C131BM+.& ?-/VF^^Q->k*HN1%E ? 	t2 		t$$((//6688 +& Jt];%?@@@ E
  	4dmnn%Audm&999A(*	q(9(9(=(=a(@(@(G(G(I(IM*%Jq26!]:-F#G#GGHHE&(fUmmM(# F5MM	 # 	6,5M.) "+4+H!I!I 	/ 	/B1211G%.M'"" : 	P)2M+& +-'	uSbS$Y/0044U122Y??BAt+ +M,' )-	(B49>!$$Ds{{./"%i!ml++./"%i"nl++./"%i"nl++vbht'ABBCC P :;; ",//Xd8;<< P262LQ2OM,//262LQ2OM,/ > 	7-6M/* ?'')) 	3 	3C{=-.. 3##M#$67777c 22r5   c                 F    t           d          sg S g } j                                        D ]}|dk    r|                    d           |dk    r|                    d           ;|dk    r|                    d           W|dk    r|                    d	           s|                    d
          rzt          |d                   } j        |         } j        |         }d                    t          |          t          |                    }|                    d|z              |dk    r|                    d           |dk    r|                    d           <|dk    r|                    d           Y|dk    r4t           j                  D ]}|                    d|dz   z             |dk    r|                    d           |dk    r%| fdt           j                  D             z  }|                    |           |S )Nr   r   zsigma2.irregularr   zsigma2.levelr   zsigma2.trendr   zsigma2.seasonalr   r   z{p}({h})r   rP   zsigma2.freq_seasonal_r   zsigma2.cycler   zfrequency.cycler   zdamping.cycler   ar.L%dr
   r   z	sigma2.arr   c                 0    g | ]}d j         |         z  S zbeta.%s
exog_namesr1   r   rT   s     r3   r4   z4UnobservedComponents.param_names.<locals>.<listcomp>  s5            22     r5   )r   r   r   r  
startswithr9   rj   rk   rp   reprr   rm   ry   )rT   r   r  idx_fseas_compperiodicityr7   freq_seasonal_namer   s   `       r3   r   z UnobservedComponents.param_names  s   t\** 	I?'')) %	( %	(Co%%""#56666##"">2222##"">2222&&""#45555 455 ( "%SW"8H 8H	%/%6%6;''9oo &7 &' &'" ""03EEG G G G##"">2222$$""#45555$$""?3333
""t}-- 9 9A&&x1Q3'788889"";////##        "4;//      
 ""3''''r5   c                 H    g } j         r|                    d            j        r|                    d            j        r7|                    d           |d t	          d j                  D             z  } j        r!|d t	           j                  D             z  } j        r|ddgz  } j	        d	k    r%|d
 t	          d j	        dz             D             z  } j
        d	k    r* j        s#| fdt	           j
                  D             z  } j        r|dgz  }|S )Nr?   r@   r`   c                     g | ]}d |z  S )zseasonal.L%dr/   r1   r   s     r3   r4   z4UnobservedComponents.state_names.<locals>.<listcomp>  s3     B B B %q( B B Br5   r
   c                     g | ]}d |z  S )zfreq_seasonal.%dr/   r'  s     r3   r4   z4UnobservedComponents.state_names.<locals>.<listcomp>  s3     @ @ @ )1, @ @ @r5   rb   zcycle.auxilliaryr   c                     g | ]}d |z  S )r  r/   r'  s     r3   r4   z4UnobservedComponents.state_names.<locals>.<listcomp>  s,     < < < l < < <r5   c                 0    g | ]}d j         |         z  S r  r  r  s     r3   r4   z4UnobservedComponents.state_names.<locals>.<listcomp>  s5     3 3 3  $/!"44 3 3 3r5   dummy)r?   r  r@   r`   r   r{   ra   r}   rb   rm   ry   rh   r   )rT   namess   ` r3   state_namesz UnobservedComponents.state_names  s   : 	"LL!!!: 	"LL!!!= 	BLL$$$ B B$Q(?@@B B B BE 	@ @ @$T%=>>@ @ @ @E: 	3g122E=1 < <$Q(9::< < < <E;??4#6? 3 3 3 3$T[113 3 3 3E 	gYEr5   c                 R   t          j        |d          }t          j        |j        |j                  }| j        | j        z   }|d|         dz  |d|<   | j        rl| j        \  }}ddt          j	        ||                    z   z  ||z
  z  |z   ||<   |dz  }| j
        r)ddt          j	        ||                    z   z  ||<   |dz  }| j        r6t          |||| j        z                      |||| j        z   <   || j        z  }|||| j        z            |||| j        z   <   |S )z
        Transform unconstrained parameters used by the optimizer to constrained
        parameters used in likelihood evaluation
        r
   ndminr   Nr   )r:   r   zerosshaper   r   r   rb   r   exprf   rc   r   rm   ry   )rT   unconstrainedconstrainedr   lowhighs         r3   transform_paramsz%UnobservedComponents.transform_params  s   
 a888h}2-:MNNN $"22,WfW5q8GVG : 	2ICQv!6 67778#"##K aKF   RV]6%:$:;;;< F# !  	$/!&$-)?"?@  v556
 dm#F &$+!556 	F6DK//0 r5   c                 ^   t          j        |d          }t          j        |j        |j                  }| j        | j        z   }|d|         dz  |d|<   | j        rr| j        \  }}||         |z
  ||z
  z  }t          j	        |d|z
  z            ||<   |dz  }| j
        r.t          j	        ||         d||         z
  z            ||<   |dz  }| j        r6t          |||| j        z                      |||| j        z   <   || j        z  }|||| j        z            |||| j        z   <   |S )z,
        Reverse the transformation
        r
   r/  r   Ng      ?)r:   r   r1  r2  r   r   r   rb   r   logrf   rc   r   rm   ry   )rT   r5  r4  r   r6  r7  r=   s          r3   untransform_paramsz'UnobservedComponents.untransform_params!  s    h{!444!2+:KLLL $"22!,WfW!5s!:gvg : 	2ICV$s*tcz:A$&FQU% %M&! aKF   (*'1{6/B+BC) )f% !  	$1v'= =>  &$-!778
 dm#F v334 	fVdk112 r5   c                 <   t                                          |           d| j        v rld t          | j                  D             }|                    |          }t          |                    |                    dk    }|r|st          d          d S d S d S )Nr   c                     g | ]
}d |dz   z  S )r  r
   r/   r'  s     r3   r4   zAUnobservedComponents._validate_can_fix_params.<locals>.<listcomp>Q  s!    GGGQAaC(GGGr5   r   zhCannot fix individual autoregressive. parameters. Must either fix all autoregressive parameters or none.)	r   _validate_can_fix_paramsr   r   rm   
issupersetrn   intersectionro   )rT   r   ar_names
fix_all_ar
fix_any_arr   s        r3   r>  z-UnobservedComponents._validate_can_fix_paramsM  s    ((555((GG%2F2FGGGH$//99J[55h??@@1DJ H* H  "G H H H )(H H H Hr5   c                 .   |                      |||          }d}| j        r||         | j        d<   |dz  }| j        dk    rL|||| j        z            }| j        rt          j        || j                  }|| j        | j        <   || j        z  }| j	        rzt          j
        ||                   }t          j        ||                   }t          j        ||g| |gg          }	| j        r|dz  }|	||         z  }	|	| j        | j        <   |dz  }| j        r)|||| j        z            | j        | j        <   || j        z  }| j        rO| j        r<t          j        | j        |||| j        z                      d d d f         | j        d<   || j        z  }d S d S )N)transformedincludes_fixedr   )obs_covr   r   r
   obs_intercept)handle_paramsr   r   r   r   r:   r   r   r   rb   r   r   r   rf   r   rc   rm   r   rz   rh   r  rW   ry   )
rT   paramsrE  rF  complex_stepr   	variancescos_freqsin_freqcycle_transitions
             r3   r   zUnobservedComponents.updateY  s    ##F3A $ C C  > 	(.vDH_%aKF avfT-=&==>I# HIi1FGG	,5DHT()d&&F : 	vfVn--HvfVn--H!xH%)X&(      3! F6N2 3CDHT/0aKF  	$vfT]223 HT,- dm#F ? 	"" ,.FI6&"445- - '-) dk!FFF	" 	"r5   )FFNNFNNFFFTNFFNTFN)TFF)__name__
__module____qualname____doc__r   r   r   r   r   propertyr   r  r   r-  r8  r;  r>  r   __classcell__r   s   @r3   r+   r+   ,   s       } }~	 BFAE&+"'"'%)*."'9=8=E" E" E" E" E" E"N    *O> O> O>b&' &' &' &'PF F F F = = X= a a XaF * * X*X   X4* * *X* * *X
H 
H 
H 
H 
H ?D!0" 0" 0" 0" 0" 0" 0" 0"r5   r+   c                       e Zd ZdZd f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 eej        j                  d fd	            Z xZS )r   a  
    Class to hold results from fitting an unobserved components model.

    Parameters
    ----------
    model : UnobservedComponents instance
        The fitted model instance

    Attributes
    ----------
    specification : dictionary
        Dictionary including all attributes from the unobserved components
        model instance.

    See Also
    --------
    statsmodels.tsa.statespace.kalman_filter.FilterResults
    statsmodels.tsa.statespace.mlemodel.MLEResults
    Nc           
      ,    t                      j        ||||fi | t          j        | _        | j                                        | _        | j        j        | j        j	        | j        j
        d| _        t          di i d| j        j        d| j        j        d| j        j        d| j        j        d| j        j        d| j        j        d| j        j        d	| j        j        d
| j        j        d| j        j        d| j        j        d| j        j        d| j        j        d| j        j        d| j        j        d| j        j        d| j        j        | j        j        | j        j        | j        j         | j        j!        d| _"        d S )N)r`   ra   rb   r?   r@   ri   r`   ra   rj   rk   rb   rm   rc   r   rA   rB   rd   rR   re   rf   )rz   rh   ry   rr   r/   )#r   r   r:   r   df_residmodelr   
_init_kwdsr{   r}   r~   _k_states_by_typer   r?   r@   ri   r`   ra   rj   rk   rb   rm   rc   r   rA   rB   rd   rR   re   rf   rz   rh   ry   rr   specification)rT   r[  rJ  filter_resultscov_typer   r   s         r3   r   z$UnobservedComponentsResults.__init__  s   6>8	? 	?7=	? 	? 	?  *3355 
5!Z;Z/"1 "1 #   &
TZ%&
 TZ%&
 
 ;	&

 
+&
 TZ5&
 $TZ%E&
 &tz'I&
 TZ%&
 
+&
 dj7&
 -&
 
 ;&
 
 ;&
 "4:#A&
  '
(K!&
" 
 ;#&
& DJ3'&
( */"j7j' $(:#A3&
 &
 &
  r5   c                     d}| j         }|j        rbd}t          | j        |         | j        ||f         dd|          }| j        | j        |         |_        | j        | j        ||f         |_        |S )a#  
        Estimates of unobserved level component

        Returns
        -------
        out: Bunch
            Has the following attributes:

            - `filtered`: a time series array with the filtered estimate of
                          the component
            - `filtered_cov`: a time series array with the filtered estimate of
                          the variance/covariance of the component
            - `smoothed`: a time series array with the smoothed estimate of
                          the component
            - `smoothed_cov`: a time series array with the smoothed estimate of
                          the variance/covariance of the component
            - `offset`: an integer giving the offset in the state vector where
                        this component begins
        Nr   filteredfiltered_covsmoothedsmoothed_covr   )	r^  r?   r   filtered_statefiltered_state_covsmoothed_statere  smoothed_state_covrf  rT   outr   r   s       r3   r?   z!UnobservedComponentsResults.level  s    , !: 		KF!4V!<%)%<VV^%L!%D%' ' 'C ".#26:&2#'#:66>#J 
r5   c                    d}| j         }|j        rtt          |j                  }t	          | j        |         | j        ||f         dd|          }| j        | j        |         |_        | j	        | j	        ||f         |_
        |S )a&  
        Estimates of of unobserved trend component

        Returns
        -------
        out: Bunch
            Has the following attributes:

            - `filtered`: a time series array with the filtered estimate of
                          the component
            - `filtered_cov`: a time series array with the filtered estimate of
                          the variance/covariance of the component
            - `smoothed`: a time series array with the smoothed estimate of
                          the component
            - `smoothed_cov`: a time series array with the smoothed estimate of
                          the variance/covariance of the component
            - `offset`: an integer giving the offset in the state vector where
                        this component begins
        Nrb  )r^  r@   r9   r?   r   rg  rh  ri  re  rj  rf  rk  s       r3   r@   z!UnobservedComponentsResults.trend  s    . !: 		K__F!4V!<%)%<VV^%L!%D%' ' 'C ".#26:&2#'#:66>#J 
r5   c                    d}| j         }|j        r|t          |j        |j        z             }t          | j        |         | j        ||f         dd|          }| j        | j        |         |_	        | j
        | j
        ||f         |_        |S )a&  
        Estimates of unobserved seasonal component

        Returns
        -------
        out: Bunch
            Has the following attributes:

            - `filtered`: a time series array with the filtered estimate of
                          the component
            - `filtered_cov`: a time series array with the filtered estimate of
                          the variance/covariance of the component
            - `smoothed`: a time series array with the smoothed estimate of
                          the component
            - `smoothed_cov`: a time series array with the smoothed estimate of
                          the variance/covariance of the component
            - `offset`: an integer giving the offset in the state vector where
                        this component begins
        Nrb  )r^  r`   r9   r@   r?   r   rg  rh  ri  re  rj  rf  rk  s       r3   r`   z$UnobservedComponentsResults.seasonal  s    2 != 		Kdj011F!4V!<%)%<VV^%L!%D%' ' 'C ".#26:&2#'#:66>#J 
r5   c                     g } j         }|j        rxt          |j        |j        z    j        d         z             }d}t          |j                  D ]6\  }}||z   |j        |         }t          j
        dd|z  d          }t          j         fd|D             d          }	t          j         fd|D             d          }
t          |	|
ddd                    t          |          t          |          	          
          } j        (t          j         fd|D             d          |_         j        (t          j         fd|D             d          |_        |                    |           |d|z  z  }8|S )aV  
        Estimates of unobserved frequency domain seasonal component(s)

        Returns
        -------
        out: list of Bunch instances
            Each item has the following attributes:

            - `filtered`: a time series array with the filtered estimate of
                          the component
            - `filtered_cov`: a time series array with the filtered estimate of
                          the variance/covariance of the component
            - `smoothed`: a time series array with the smoothed estimate of
                          the component
            - `smoothed_cov`: a time series array with the smoothed estimate of
                          the variance/covariance of the component
            - `offset`: an integer giving the offset in the state vector where
                        this component begins
        r`   r   r   c                 0    g | ]}j         |z            S r/   )rg  r1   r   r   rT   s     r3   r4   z=UnobservedComponentsResults.freq_seasonal.<locals>.<listcomp>p  s%    LLLT(!4LLLr5   r   c                 :    g | ]}j         |z   |z   f         S r/   )rh  rq  s     r3   r4   z=UnobservedComponentsResults.freq_seasonal.<locals>.<listcomp>s  s:     $ $ $T,VaZ!-CD $ $ $r5   Nzseasonal {p}({h})r  )rc  rd  re  rf  r   pretty_namec                 0    g | ]}j         |z            S r/   )ri  rq  s     r3   r4   z=UnobservedComponentsResults.freq_seasonal.<locals>.<listcomp>  s%    NNN1,VAX6NNNr5   c                 :    g | ]}j         |z   |z   f         S r/   )rj  rq  s     r3   r4   z=UnobservedComponentsResults.freq_seasonal.<locals>.<listcomp>  s>     1 1 1 06!81CD 1 1 1r5   )r^  ra   r9   r@   r?   r]  r   rk   rj   r:   aranger|   r   rp   r!  ri  re  rj  rf  r  )rT   rl  r   previous_states_offsetprevious_f_seas_offsetrS   rP   r.   states_in_sumrg  rd  itemr   s   `           @r3   ra   z)UnobservedComponentsResults.freq_seasonal>  s*   D ! $	0%(dj)@+/+A*+M*N &O &O"%&""4#?@@  0  0A/2HH3B7 !#	!QUA 6 6!#LLLLLmLLL" " "  "v$ $ $ $ $"$ $ $*+ -  -  - +!-!! 3 : :T&\\=A!WW !; !F !FG G G &2$&FNNNNNNNN%  %  % DM *6(*1 1 1 1 1"/1 1 178): ): ):D% 

4   &!a%/&&
r5   c                 V   d}| j         }|j        rt          |j        |j        z   | j        d         z   | j        d         z             }t          | j        |         | j        ||f         dd|          }| j	        | j	        |         |_
        | j        | j        ||f         |_        |S )a#  
        Estimates of unobserved cycle component

        Returns
        -------
        out: Bunch
            Has the following attributes:

            - `filtered`: a time series array with the filtered estimate of
                          the component
            - `filtered_cov`: a time series array with the filtered estimate of
                          the variance/covariance of the component
            - `smoothed`: a time series array with the smoothed estimate of
                          the component
            - `smoothed_cov`: a time series array with the smoothed estimate of
                          the variance/covariance of the component
            - `offset`: an integer giving the offset in the state vector where
                        this component begins
        Nr`   ra   rb  )r^  rb   r9   r@   r?   r]  r   rg  rh  ri  re  rj  rf  rk  s       r3   rb   z!UnobservedComponentsResults.cycle  s    6 !: 	Kdj01*=>1/BC D DF !4V!<%)%<VV^%L!%D%' ' 'C ".#26:&2#'#:66>#J 
r5   c                 r   d}| j         }|j        rt          |j        |j        z   | j        d         z   | j        d         z   | j        d         z             }t          | j        |         | j        ||f         dd|          }| j	        | j	        |         |_
        | j        | j        ||f         |_        |S )a,  
        Estimates of unobserved autoregressive component

        Returns
        -------
        out: Bunch
            Has the following attributes:

            - `filtered`: a time series array with the filtered estimate of
                          the component
            - `filtered_cov`: a time series array with the filtered estimate of
                          the variance/covariance of the component
            - `smoothed`: a time series array with the smoothed estimate of
                          the component
            - `smoothed_cov`: a time series array with the smoothed estimate of
                          the variance/covariance of the component
            - `offset`: an integer giving the offset in the state vector where
                        this component begins
        Nr`   ra   rb   rb  )r^  rc   r9   r@   r?   r]  r   rg  rh  ri  re  rj  rf  rk  s       r3   rc   z*UnobservedComponentsResults.autoregressive  s    2 ! 	Kdj01*=>1/BC  1':; < <F !4V!<%)%<VV^%L!%D%' ' 'C ".#26:&2#'#:66>#J 
r5   c                     d}| j         }|j        r|j        r ddl}|                    dt
                     nt          |j        |j        z   | j	        d         z   | j	        d         z   | j	        d         z   |j
        z             }|}||j        z   }t          | j        ||         | j        ||||f         dd|          }| j        | j        ||         |_        | j        | j        ||||f         |_        |S )a+  
        Estimates of unobserved regression coefficients

        Returns
        -------
        out: Bunch
            Has the following attributes:

            - `filtered`: a time series array with the filtered estimate of
                          the component
            - `filtered_cov`: a time series array with the filtered estimate of
                          the variance/covariance of the component
            - `smoothed`: a time series array with the smoothed estimate of
                          the component
            - `smoothed_cov`: a time series array with the smoothed estimate of
                          the variance/covariance of the component
            - `offset`: an integer giving the offset in the state vector where
                        this component begins
        Nr   zRegression coefficients estimated via maximum likelihood. Estimated coefficients are available in the parameters list, not as part of the state vector.r`   ra   rb   rb  )r^  rz   rh   warningsr   r   r9   r@   r?   r]  rm   ry   r   rg  rh  ri  re  rj  rf  )rT   rl  r   r~  r   startends          r3   regression_coefficientsz3UnobservedComponentsResults.regression_coefficients  sY   2 !? 	G" G 6 8EF F F F
 TZ$*4#5jAB#5oFG  $5g>?  $}	- . .
 t{*!0s;!%!8sE#I9M!N!!	   &2#'#6uSy#ACL*6/c	590DE $
r5   皙?Tupper rightc                  
   ddl m} ddlm}m}  |            } |||          }|| j        dnd}| j        }d|o|j        fd|o|j        fd	|o|j	        fg}|r=|j
        r6t          |j                  D ]!\  }}d
|}|                    |df           "|                    d|o|j        fd|	o|j        fg           t#          |          }| j        j        }|t)          j        t-          |                                                    z   }t1          | j        d          r+| j        j        | j        j                                        }n+t)          j        t;          | j        j                            }|                    d|dz  z
            }d}|r|                     |d|          }|dz  }|!                    ||d         | j"        j        |d         dd           | j        j#        d         }t)          j$        | j        j%        d                   }|||z  z
  }|||z  z   } |!                    ||d         ||d         d           |&                    ||d         ||d         | |d         d          }!dd|z
  dz  z  }"|'                    ddd|!(                                d                   }#|)                                \  }$}%|$                    |#           |%                    |"           |*                    |$|%|
           |+                    d           |,                                D ]\  }&}'|'s	|                     |d|          }|dz  }	 t[          | |&          }(|&.                                })ni# t^          $ r\ |&0                    d
          rCtc          |&2                    d
d                    }t[          | d          }*|*|         }(|(j3        })n Y nw xY w||(vrti          d           d!|z  }+|(|         },|) d"| d#}-|!                    ||d         |,|d         |-           |+|(v rit)          j$        |(d!|z                     }|,||z  z
  }|,||z  z   } |&                    ||d         ||d         | |d         d          }!dd|z
  dz  z  }"|*                    |
           |+                    d$|)z             |dk    rd%}.|5                    d&d'|.|z  d()           |S )*aI	  
        Plot the estimated components of the model.

        Parameters
        ----------
        which : {'filtered', 'smoothed'}, or None, optional
            Type of state estimate to plot. Default is 'smoothed' if smoothed
            results are available otherwise 'filtered'.
        alpha : float, optional
            The confidence intervals for the components are (1 - alpha) %
        observed : bool, optional
            Whether or not to plot the observed series against
            one-step-ahead predictions.
            Default is True.
        level : bool, optional
            Whether or not to plot the level component, if applicable.
            Default is True.
        trend : bool, optional
            Whether or not to plot the trend component, if applicable.
            Default is True.
        seasonal : bool, optional
            Whether or not to plot the seasonal component, if applicable.
            Default is True.
        freq_seasonal : bool, optional
            Whether or not to plot the frequency domain seasonal component(s),
            if applicable. Default is True.
        cycle : bool, optional
            Whether or not to plot the cyclical component, if applicable.
            Default is True.
        autoregressive : bool, optional
            Whether or not to plot the autoregressive state, if applicable.
            Default is True.
        fig : Figure, optional
            If given, subplots are created in this figure instead of in a new
            figure. Note that the grid will be created in the provided
            figure using `fig.add_subplot()`.
        figsize : tuple, optional
            If a figure is created, this argument allows specifying a size.
            The tuple is (width, height).

        Notes
        -----
        If all options are included in the model and selected, this produces
        a 6x1 plot grid with the following plots (ordered top-to-bottom):

        0. Observed series against predicted series
        1. Level
        2. Trend
        3. Seasonal
        4. Freq Seasonal
        5. Cycle
        6. Autoregressive

        Specific subplots will be removed if the component is not present in
        the estimated model or if the corresponding keyword argument is set to
        False.

        All plots contain (1 - `alpha`) %  confidence intervals.
        r   )norm)_import_mplcreate_mpl_figNrc  re  r?   r@   r`   freq_seasonal_Trb   rc   datesr
   g       @kObserved)colorlabel)r   r   zOne-step-ahead predictions)r  g?)alphaz$%.3g \%%$ confidence intervald   )fc)loczPredicted vs observedrX   ra   zInvalid type of state estimate.z%s_covz ()z%s componentzYNote: The first %d observations are not shown, due to approximate diffuse initialization.g?g{Gz?large)fontsize)6scipy.statsr  statsmodels.graphics.utilsr  r  ri  r^  r?   r@   r`   ra   r   rj   r  extendrb   rc   dictr_  rU   r:   r|   r   r   r   r   r  	_mpl_reprrv  rn   r   ppfadd_subplotplotr[  	forecastssqrtforecasts_error_covfill_between	Rectangleget_facecolorget_legend_handles_labelslegend	set_titleitemsru   titleAttributeErrorr   r9   replacers  ro   text)/rT   whichr  observedr?   r@   r`   ra   rb   rc   
legend_locfigfigsizer  r  r  pltr   comprS   _r  
componentsllbk_plotsr  critical_valueplot_idxaxpredict
std_errorsci_lowerci_upperci_polyci_labelr   handleslabels	component
is_plottedcomponent_bunchr  	big_bunch	which_covvaluestate_labelr  s/                                                  r3   plot_componentsz+UnobservedComponentsResults.plot_components  s   @ 	%$$$$$JJJJJJJJkmmnS'** ="&"5"=JJ:E ! e*
+e*
+3dm4
  	)T/ 	)"4#=>> ) )A-r--S$K((((u+, F43FGI	J 	J 	J $ZZ
!4 RVD):):)<)<$=$=>>> 49g&& 	449?+FIO--//EEIc$)/2233E !ebj.11   	2!X66BMH GGE#$$K!1#$$!7s$  & & & )3A6G!4!H!NOOJ*!<<H*!<<H GGE#$$K6  8 8 8oocddXcdd^Xcdd^3 &  G 9QY#<MNH faw/D/D/F/Fq/IJJA !::<<OGVNN1MM(###IIgv:I666LL0111 &0%5%5%7%7 0	1 0	1!Iz !X66BMH")$	":":!))! 	 	 	 ''(899 Y../?DDEEB 'o > >I&/mO+7EE E	 O++ !BCCC 5(I $E*E #..e...KGGE#$$KsttKG@@@ O++W_X5E%FGG
 >J#>> >J#>>//#$$K#$$#$$s *   > !E	S02 II*I%%%LL%/0000 77;DHHS$s
WH===
s   /$NA#O:9O:c                    | j         j        g}| j         j        r5d| j         j        z  }| j         j        rd|z   }|                    |           | j         j        rt          | j         j                  D ]v\  }}| j         j	        |         }| j         j
        |         }d                    t          |          t          |                    }	|rd|	z   }	|                    |	           w| j         j        r9d}
| j         j        rd|
z   }
| j         j        rd|
z   }
|                    |
           | j         j        r$d| j         j        z  }|                    |           t%                                          ||d|	          S )
Nzseasonal(%d)zstochastic zfreq_seasonal({p}({h}))r  rb   zdamped zAR(%d)zUnobserved Components Results)r  r  r  
model_name)r^  rr   r`   ri   rd   r  ra   r   rR   rj   rk   rp   r!  rb   re   rf   rc   rm   r   summary)rT   r  r  r  seasonal_namerS   r   r#  r7   r$  
cycle_nameautoregressive_namer   s               r3   r  z#UnobservedComponentsResults.summary  s    (<=
& 	-+#1BCM!5 > - =m,,,+ 
	6%.&?&A &A 	6 	6!M"0FrJ .FrJ	%>%E%E;''9oo &F &' &'" ! L)69K)K&!!"45555# 	* J!2 8*Z7
!. 4&3
j))), 	3"*T-?-H"H1222wwu,K!  
 
 	
r5   rP  )Nr  TTTTTTTr  NN)r  N)rQ  rR  rS  rT  r   rU  r?   r@   r`   ra   rb   rc   r  r  r   r   r  rV  rW  s   @r3   r   r     st        (+ + + + + +Z ! ! X!F " " X"H $ $ X$L H H XHT ( ( X(T ' ' X'R 4 4 X4l 159=5937DH	I I I IV Xj ())'
 '
 '
 '
 '
 *)'
 '
 '
 '
 '
r5   r   c                   n    e Zd Zi Z ej        ej        e          Zi Z ej        ej	        e          Z	dS )r   N)
rQ  rR  rS  _attrswrapunion_dictsr   _wrap_attrs_methods_wrap_methodsr/   r5   r3   r   r     sR        F"$"#4#@#)+ +KH$D$%6%D%-/ /MMMr5   r   )$rT  r~  r   numpyr:   statsmodels.compat.pandasr   statsmodels.tools.toolsr   statsmodels.tools.sm_exceptionsr   r   statsmodels.base.wrapperbasewrapperr  !statsmodels.tsa.filters.hp_filterr   statsmodels.tsa.tsatoolsr	   mlemodelr   r   r   r   r   toolsr   r   r   r   rx   r+   r   r   populate_wrapperr/   r5   r3   <module>r     s              . . . . . . ) ) ) ) ) ) O O O O O O O O ' ' ' ' ' ' ' ' ' 6 6 6 6 6 6 + + + + + + = = = = = = = = = = * * * * * *5 5 5 5 5 5 5 5 5 5 5 5
  * 	 ]" ]" ]" ]" ]"8 ]" ]" ]"@#|	
 |	
 |	
 |	
 |	
* |	
 |	
 |	
~/ / / / /): / / /  813 3 3 3 3r5   