
    Dj`W                        d dl mZ d dlZd dlmZ d dlmZ d dlmZ d dl	m
Z
 d dlmZ d dlmZ d d	lmZmZ d d
lmZ d dlZddlmZ ddlmZ ddlmZ ddlmZmZm Z  ddl!m"Z" g dZ#ddZ$ G d dee      Z% G d de%      Z& G d de%      Z'y)    )
namedtupleN)LinearRegression)make_pipeline)StandardScaler)svd)api)add_constant)ABCMetaabstractmethod)solve   )_aicc   )DTYPE)_BaseStationarityTest)cdiffcheck_endog)C_canova_hansen_sd_test)CHTest	decomposeOCSBTestc                    dd}|dz  dk(  }fd}	 t        |t              r|dkD  sJ 	 |t	        j
                  |f      |z  }|fvrd}t        |j                  |            | j                  d	   |z  dk  rt        d
      |dz  }t	        j                  | |d      }	|s|	dd }	t        |t        |	      |z         }
 || |
   |	      }t        j                  d|	j                  d	   z  |z        }||z  |	j                  d	   z
  }|d	kD  r:|t        j                  gz  }t	        j                  |j                         |z         }t	        j                   |||f      }t	        j"                  |d	      j                         }t	        j                  ||d |d| z         }|}t        |j                  d	         D ]  }t	        j$                  ||f      } |d	kD  r|d|  }|r|dd }t        j                  g|z  }t'        ||	j                         z   |z         }	 | || |	      |      }t)        dd      } || |	||      }|S # t        t        f$ r t        d      w xY w)a@  
    Decompose the time series into trend, seasonal, and random components.

    Parameters
    ----------
    x : np.array, shape=(n_samples,)
        The time series of which the trend, seasonal, and noise/random
        components will be extracted.

    type_: str
        The type of decomposition that will be performed - 'multiplicative' or
        'additive'. We would use 'multiplicative' generally when we see an
        increasing trend. We use 'additive' when the trend is relatively
        stable over time.

    m: int
        The frequency in terms of number of observations. This behaves
        similarly to R's frequency for a time series (ts).

    filter_: np.array, optional (default=None)
        A filter by which the convolution will be performed.

    Returns
    -------
    decomposed_tuple : namedtuple
        A named tuple with ``x``, ``trend``, ``seasonal``, and ``random``
        components where ``x`` is the input signal, ``trend`` is the overall
        trend, ``seasonal`` is the seasonal component, and `random` is the
        noisy component. The input signal ``x`` can be mostly reconstructed by
        the other three components with a number of points missing equal to
        ``m``.

    Notes
    -----
    This function is generally used in conjunction with
    :func:`pmdarima.utils.visualization.decomposed_plot`,
    which plots the decomposed components. Also there is an example script in
    the ``examples`` folder of the repo and the ``Examples`` section of the
    docs as well.

     References
    ----------
    .. [1] Example of decompose using both multiplicative and additive types:
           https://anomaly.io/seasonal-trend-decomposition-in-r/index.html

    .. [2] R documentation for decompose:
           https://www.rdocumentation.org/packages/stats/versions/3.6.1/topics/decompose
    multiplicativeadditiver   r   c                 "    k(  r| |z  S | |z
  S N )abr   type_s     ^C:\Crop_Prediction\Backend\crop-ai-system\venv\Lib\site-packages\pmdarima/arima/seasonality.py_decomposer_helperz%decompose.<locals>._decomposer_helper[   s    N"q5Lq5L    z 'f' should be a positive integerNz)'type_' can only take values '{}' or '{}'r   z)time series has no or less than 2 periodsvalid)mode      ?axis
decomposedzx trend seasonal random)
isinstanceint
ValueErrorAssertionErrornponesformatshapeconvolverangelenmathceilnanarraytolistreshapenanmeanconcatenatelistr   )xr!   mfilter_r   is_m_oddr#   err_msghalf_mtrendsma_xsdetrendnum_seasons
pad_lengthbufferm_arrseasonaltempirandomr+   decomposed_tupler   s    `                    @r"   r   r   $   s   d &NHA
H=!S!a!e+e ''1$-!# ^X..=ABB 	

Q!DEE !VFKK71Ecr
 63u:./F 6E2G))S5;;q>1Q67K/U[[^3JA~rvvh&((7>>+f45 JJwa 01Ezz%a(//1Hxx)HWf,==>HD5;;q>" 4>>8T"234A~Lj[)CR=
 ffXF%,,.(612E   21e <hGF L*CDJ!!UHf=u ' =;<<=s   I I*c                   &    e Zd ZdZd Zed        Zy)_SeasonalStationarityTestzProvides the base class for seasonal differencing tests such as the
    Canova-Hansen test and the Osborn-Chui-Smith-Birchenhall tests. These tests
    are used to determine the seasonal differencing term for a time-series.
    c                 2    || _         |dk  rt        d      y )Nr   zm must be > 1)rA   r.   )selfrA   s     r"   __init__z"_SeasonalStationarityTest.__init__   s     q5_-- r$   c                      y)zEstimate the seasonal differencing term.

        Parameters
        ----------
        x : array-like, shape=(n_samples,)
            The time series vector.
        Nr   )rU   r@   s     r"   #estimate_seasonal_differencing_termz=_SeasonalStationarityTest.estimate_seasonal_differencing_term   s    r$   N)__name__
__module____qualname____doc__rV   r   rX   r   r$   r"   rS   rS      s     .
  r$   rS   )	metaclassc                   l     e Zd ZdZ edddddddd	d
dd      Z fdZed        Zed        Z	d Z
 xZS )r   a  Conduct a CH test for seasonality.

    The Canova-Hansen test for seasonal differences. Canova and Hansen
    (1995) proposed a test statistic for the null hypothesis that the seasonal
    pattern is stable. The test statistic can be formulated in terms of
    seasonal dummies or seasonal cycles. The former allows us to identify
    seasons (e.g. months or quarters) that are not stable, while the latter
    tests the stability of seasonal cycles (e.g. cycles of period 2 and 4
    quarters in quarterly data). [1]

    Parameters
    ----------
    m : int
        The seasonal differencing term. For monthly data, e.g., this would be
        12. For quarterly, 4, etc. For the Canova-Hansen test to work,
        ``m`` must exceed 1.

    Notes
    -----
    This test is generally not used directly, but in conjunction with
    :func:`pmdarima.arima.nsdiffs`, which directly estimates the number
    of seasonal differences.

    References
    ----------
    .. [1] Testing for seasonal stability using the Canova
           and Hansen test statistic: http://bit.ly/2wKkrZo

    .. [2] R source code for CH test:
           https://github.com/robjhyndman/forecast/blob/master/R/arima.R#L148
    gv|d?gE)!XU?g3?g[|
?gwِf?gB?gjWWx?gxOԈ @glf@gKnVS@g@c                 .    t         t        |   |       y N)rA   )superr   rV   )rU   rA   	__class__s     r"   rV   zCHTest.__init__   s    fd$q$)r$   c                    | j                   d   }t        j                  t        |dz   dz        t              }t        t        j                  ||dz  dz  z              }t
        j                  | |      }t        t        d      t                     j                  ||       }| |j                  |      z
  }|j                  |z  j                  j                  t        j                        }|j                   d   }	t        ||	|||      \  }
}t!        |d	      }|j#                         t        j$                  |j&                        j(                  k  ry|j+                  d
      }t-        |t        j.                  |j                   d               }d|dz  z  |j1                  |
j                        j1                  |j                        j1                  |      j1                  |
      j3                         j5                         z  S )Nr   r   r   )dtypeg      Y@g      ?F)	with_mean)
compute_uvr)   r(   )r3   r0   r1   r-   roundr   _seas_dummyr   r   r   fitpredictTastypefloat64r   r   minfinford   epscumsumr   identitydotdiagonalsum)wtssnfrecltruncR1lmch	residualsFhatauxNeA	AtOmfhatAsvFhatsolveds                  r"   _sd_testzCHTest._sd_test   s    IIaL wwsAEQ;'s3RXXaAI$#6789Q' U+
 #b#, 	
 $,,r**	 44)#&&--bjj9 ]]1
 /vr7D!L9 u- 668bhhrxx(,,, ~~1~%y"++iooa.@"ABa1f

133 3 3FF!CIcc!fXXZ6 	6r$   c                    | j                   d   }|dkD  sJ d       t        j                  |      dz   }t        j                  |d|z  f      t        j                  z  }t        j
                  }t        d|dz         D ]^  }t        j                  d|z  |z  |z  |z        |d d d|z  dz
  f<   t        j                  d|z  |z  |z  |z        |d d d|dz
  z  f<   ` |d d d |dz
  f   S )Nr   r   zFThis function is called internally and should not encounter this issuer   )	r3   r0   aranger1   r9   pir5   sincos)r@   rA   rx   ttfmatr   rO   s          r"   rh   zCHTest._seas_dummy"  s    ( GGAJ 1u 	8 8 	8 YYq\Aww1q5z"RVV+UUq!a% 		?A $&66!b&1*r/A*=#>DQUaK 
 $&66!b&1*r/A*=#>DAQK 		? AvAvIr$   c                    | j                  |      syt        |t        d      }|j                  d   }t	        | j
                        }|d|z  dz   k  ry| j                  ||      }|dk  rt	        || j                  |dz
     kD        S |dk(  rt	        |dkD        S |d	k(  rt	        |d
kD        S |dk(  rt	        |dkD        S t	        |d|dz  z  kD        S )a  Estimate the seasonal differencing term.

        Parameters
        ----------
        x : array-like, shape=(n_samples,)
            The time series vector.

        Returns
        -------
        D : int
            The seasonal differencing term. The CH test defines a set of
            critical values::

                (0.4617146, 0.7479655, 1.0007818,
                 1.2375350, 1.4625240, 1.6920200,
                 1.9043096, 2.1169602, 2.3268562,
                 2.5406922, 2.7391007)

            For different values of ``m``, the CH statistic is compared
            to a different critical value, and returns 1 if the computed
            statistic is greater than the critical value, or 0 if not.
        r   Frd   preserve_seriesr            ggd@4   gή$@im  gCiq\P@gK7?gV-?)
_base_caser   r   r3   r-   rA   r   	crit_vals)rU   r@   rx   rA   chstats        r"   rX   z*CHTest.estimate_seasonal_differencing_termL  s    . q! >GGAJKq1uqy=q!$7vq1u 55667v())7v	)**8v())6EQ%Z0011r$   )rY   rZ   r[   r\   r   r   rV   staticmethodr   rh   rX   __classcell__rb   s   @r"   r   r      sc    > )Y	Y	Y	Y(I
* @6 @6D ' 'R.2r$   r   c                        e Zd ZdZd d d dZd fd	Zed        Zedd       Zedd	       Z	ed
        Z
d Zd Z xZS )r   a  Perform an OCSB test of seasonality.

    Compute the Osborn, Chui, Smith, and Birchenhall (OCSB) test for an input
    time series to determine whether it needs seasonal differencing. The
    regression equation may include lags of the dependent variable. When
    ``lag_method`` = "fixed", the lag order is fixed to ``max_lag``; otherwise,
    ``max_lag`` is the maximum number of lags considered in a lag selection
    procedure that minimizes the ``lag_method`` criterion, which can be
    "aic", "bic" or corrected AIC, "aicc".

    Critical values for the test are based on simulations, which have been
    smoothed over to produce critical values for all seasonal periods

    Parameters
    ----------
    m : int
        The seasonal differencing term. For monthly data, e.g., this would be
        12. For quarterly, 4, etc. For the OCSB test to work, ``m`` must
        exceed 1.

    lag_method : str, optional (default="aic")
        The lag method to use. One of ("fixed", "aic", "bic", "aicc"). The
        metric for assessing model performance after fitting a linear model.

    max_lag : int, optional (default=3)
        The maximum lag order to be considered by ``lag_method``.

    References
    ----------
    .. [1] Osborn DR, Chui APL, Smith J, and Birchenhall CR (1988)
           "Seasonality and the order of integration for consumption",
           Oxford Bulletin of Economics and Statistics 50(4):361-377.

    .. [2] R's forecast::OCSB test source code: https://bit.ly/2QYQHno
    c                     | j                   S r   )aicri   s    r"   <lambda>zOCSBTest.<lambda>  
    377 r$   c                     | j                   S r   )bicr   s    r"   r   zOCSBTest.<lambda>  r   r$   c                 0    t        | | j                  d      S )NF)r   nobsr   s    r"   r   zOCSBTest.<lambda>  s    E#sxx7 r$   )r   r   aiccc                 J    t         t        |   |       || _        || _        y r`   )ra   r   rV   
lag_methodmax_lag)rU   rA   r   r   rb   s       r"   rV   zOCSBTest.__init__  s#    h&&+$r$   c                     t        j                  |       }dt        j                  d|dz
  z  d|dz
  dz  z  z         z  dz
  S )zCompute the OCSB critical valuegmxҿgj>ҿg'*?g!q᢮r   g4,F]ko?)r0   logexp)rA   log_ms     r"   _calc_ocsb_crit_valzOCSBTest._calc_ocsb_crit_val  sW     q	FF:!23{Y&1,7. . //19: 	:r$   c                 <   | j                   d   }|dk(  r| j                  |d      S t        j                  ||dz
  z   |f      t        j                  z  }t        |      D ]  }| ||||z   |f<    |r)|t        j                  |      j                  d          }|S )zPerform the TS laggingr   r   r)   )r3   r<   r0   r1   r9   r5   isnanany)ylagomit_narx   outrO   s         r"   _do_lagzOCSBTest._do_lag  s     GGAJ!899Q?" ggqC!G}c*+bff4s 	 AC!a%
O	  rxx}((a(001C
r$   c                 ~    |dk  r"t        j                  | j                  d         S t        j	                  | ||      S )z>Create the lagged exogenous array used to fit the linear modelr   )r0   zerosr3   r   r   )r   r   r   s      r"   	_gen_lagszOCSBTest._gen_lags  s9     a<88AGGAJ'' 7G44r$   c                    t        | |      }|j                  d   dk(  rt        d      t        |      }t        j	                  ||      }|dkD  r||d }|d|j                  d    }t        j                  |t        |            j                  d      }||d }	t        j	                  ||      d|	j                  d   ddf   }
|j                  t        |
            }|	|z
  }t        |       }t        j	                  ||      }||d }|d|j                  d   ddf   }|j                  t        |            }||z
  }t        j                  ||d|j                  d    j                  dd      |d|j                  d    j                  dd      f      }t        j                  ||      j                  d      S )z7Fit the linear model used to compute the test statisticr   zThere are no more samples after a first-order seasonal differencing. See http://alkaline-ml.com/pmdarima/seasonal-differencing-issues.html for a more in-depth explanation and potential work-arounds.r'   Nqr)methodr   )r   r3   r.   r   r   smOLSr	   ri   rj   r0   hstackr<   )r@   rA   r   r   y_first_order_diffr   ylagmfar_fitz4_yz4_lagz4_predsz4z5_yz5_lagz5_predsz5datas                     r"   	_fit_ocsbzOCSBTest._fit_ocsb  s    "!QZ ##A&!+:  #$!!!S)R<'(A +1771:<+,000= "#$'##$6<^djjm^Q=NO>>,v"67H_ Aw##D#.CDzA)*>>,v"67H_ yy|$$R+|$$R+
  vva""$"//r$   c                 h   | j                   }| j                  }| j                  }d }|dkD  r|dk7  r	 | j                  |   }g }g }t        d|dz         D ]?  }		 | j                  |||	|      }
|j                  |
       |j                   ||
             A t        j                  |      j                         rt        d      t        t        j                   |            }|dz
  }||   }	 | j                  ||||      }|j"                  dd  }|d   S # t        $ r t        d      w xY w# t        j                  j                  $ r4 |j                  t        j                         |j                  d        Y )w xY w# t        j                  j                  $ r ||}nt        d      Y w xY w)	Nr   fixedzI'%s' is an invalid method. Must be one of ('aic', 'aicc', 'bic', 'fixed')r   zAll lag values up to 'maxlag' produced singular matrices. Consider using a longer series, a different lag term or a different test.zXCould not find a solution. Try a longer series, different lag term, or a different test.r'   )rA   r   r   _ic_method_mapKeyErrorr.   r5   r   appendr0   linalgLinAlgErrorr9   r   allr-   	nanargmintvalues)rU   r@   rA   maxlagr   crit_regressionicfuncfitsicvalslag_termri   
best_index
regressiontvalss                 r"   _compute_test_statisticz OCSBTest._compute_test_statistic  s   FF A:&G+G,,V4
 DF!!VaZ0 &&..Ax@CKK$MM&+.	& xx##%  ") * * R\\&12J!^F #:.O		*1ff=J ""23'RyW  G  "F G GG yy,, &MM"&&)KK%&* yy$$ 	**,
 ! ") * * 	*s0   D <D--F D*-AE>=E>-F10F1c                     | j                  |      syt        |t        d      }| j                  |      }| j	                  | j
                        }t        ||kD        S )a  Estimate the seasonal differencing term.

        Parameters
        ----------
        x : array-like, shape=(n_samples,)
            The time series vector.

        Returns
        -------
        D : int
            The seasonal differencing term. For different values of ``m``,
            the OCSB statistic is compared to an estimated critical value, and
            returns 1 if the computed statistic is greater than the critical
            value, or 0 if not.
        r   Fr   )r   r   r   r   r   rA   r-   )rU   r@   statcrit_vals       r"   rX   z,OCSBTest.estimate_seasonal_differencing_term>  sX      q! > ++A.++DFF34(?##r$   )r      )T)rY   rZ   r[   r\   r   rV   r   r   r   r   r   r   rX   r   r   s   @r"   r   r   }  s~    "H #" 8N : :    5 5 /0 /0b5n$r$   r   r   )(collectionsr   r7   sklearn.linear_modelr   sklearn.pipeliner   sklearn.preprocessingr   scipy.linalgr   statsmodelsr   r   statsmodels.toolsr	   abcr
   r   numpy.linalgr   numpyr0   arimar   compat.numpyr   stationarityr   utils.arrayr   r   r   _arimar   __all__r   rS   r   r   r   r$   r"   <module>r      sv    #  1 * 0  ! * '      / . . +{| 5 *C2& C2LZ$( Z$r$   