
    Dj                         d dl Zd dlZd dlmc mZ d dlZd dlZd dl	m
Z
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mZ ddlmZ ddlmZ ddl m!Z!m"Z"m#Z#m$Z$ ddl%m&Z& ddl'm(Z(m)Z) d dl*Z*ddgZ+d Z,d Z-d Z.d Z/ G d de      Z0y)    N)gaussian_kdenorm)check_array)api   )_validation   )	BaseARIMA)DTYPE)check_is_fittedif_delegate_has_methodsafe_indexing)statsmodels)
matplotlib)if_has_delegateis_iterablecheck_endog
check_exog)_get_plt)diff_invdiffARIMAARMAtoMAc                    t        |       }t        |      }t        j                  |      }t        d|      D ]R  }||k  r||   nd}t        dt	        |dz   |            D ]#  }|| |   ||z
  dz
  dk\  r|||z
  dz
     ndz  z  }% |||<   T |S )ar  
    Convert ARMA coefficients to infinite MA coefficients.

    Compute coefficients of MA model equivalent to given ARMA model.
    MA coefficients are cut off at max_deg.
    The same function as ARMAtoMA() in stats library of R

    Parameters
    ----------
    ar : array-like, shape=(n_orders,)
        The array of AR coefficients.

    ma : array-like, shape=(n_orders,)
        The array of MA coefficients.

    max_deg : int
        Coefficients are computed up to the order of max_deg.

    Returns
    -------
    np.ndarray, shape=(max_deg,)
        Equivalent MA coefficients.

    Notes
    -----
    Here is the derivation. Suppose ARMA model is defined as
    .. math::
    x_t - ar_1*x_{t-1} - ar_2*x_{t-2} - ... - ar_p*x_{t-p}\\
        = e_t + ma_1*e_{t-1} + ma_2*e_{t-2} + ... + ma_q*e_{t-q}
    namely
    .. math::
    (1 - \sum_{i=1}^p[ar_i*B^i]) x_t = (1 + \sum_{i=1}^q[ma_i*B^i]) e_t
    where :math:`B` is a backward operator.

    Equivalent MA model is
    .. math::
        x_t = (1 - \sum_{i=1}^p[ar_i*B^i])^{-1}\\
        * (1 + \sum_{i=1}^q[ma_i*B^i]) e_t\\
        = (1 + \sum_{i=1}[ema_i*B^i]) e_t
    where :math:``ema_i`` is a coefficient of equivalent MA model.
    The :math:``ema_i`` satisfies
    .. math::
        (1 - \sum_{i=1}^p[ar_i*B^i]) * (1 + \sum_{i=1}[ema_i*B^i]) \\
        = 1 + \sum_{i=1}^q[ma_i*B^i]
    thus
    .. math::
        \sum_{i=1}[ema_i*B^i] = \sum_{i=1}^p[ar_i*B^i] \\
        + \sum_{i=1}^p[ar_i*B^i] * \sum_{j=1}[ema_j*B^j] \\
        + \Sum_{i=1}^q[ma_i*B^i]
    therefore
    .. math::
        ema_i = ar_i (but 0 if i>p) \\
        + \Sum_{j=1}^{min(i-1,p)}[ar_j*ema_{i-j}] + ma_i(but 0 if i>q) \\
        = \sum_{j=1}{min(i,p)}[ar_j*ema_{i-j}(but 1 if j=i)] \\
        + ma_i(but 0 if i>q)

    Examples
    --------
    >>> ar = np.array([0.1])
    >>> ma = np.empty(0)
    >>> ARMAtoMA(ar, ma, 3)
    array[0.1, 0.01, 0.001]
    r   g        r         ?)lennpemptyrangemin)	armamax_degpqemaitempjs	            XC:\Crop_Prediction\Backend\crop-ai-system\venv\Lib\site-packages\pmdarima/arima/arima.pyr   r   '   s    @ 	BABA
((7
C1g Ar!u3q#a!eQ-( 	HABqEq1uqyA~SQ^3GGD	HA	
 J    c                 n    | j                   }| j                  }|r|dz  }|d|z  |||z
  dz
  z  dz
  z  z   S )z2Compute the corrected Akaike Information Criterionr   g       @r   )aicdf_model)model_resultsnobsadd_constantr-   r.   s        r*   _aiccr2   r   sN    


C %%Hh$$/B*>"?""DEEEr+   c                     | j                   dk(  rt        j                  | |f      S t        j                  | j                         |f      ddt        j                  f   S )zAppend to the endogenous array

    Parameters
    ----------
    endog : np.ndarray, shape=(n_samples, [1])
        The existing endogenous array

    new_y : np.ndarray, shape=(n_samples)
        The new endogenous array to append
    r   N)ndimr   concatenateravelnewaxis)endognew_ys     r*   _append_to_endogr:   ~   sO     	

a >>5%.) >
u-.q"**}=>r+   c                 d    | j                   d|||d|}|j                  }|j                  |      }| j                  d   rL| j                  j
                  }	| j                  j                  }
| j                  j                  }| j                  j                  }|
dkD  rC|dk(  r|	nt        |	||      }t        j                  ||
 d |      }t        |d|
      }|d|
z  d }|dkD  r:|dkD  r5t        j                  |	||z   d |      }t        |||      }|d|z  |z  d }| j                  }t        j                  t        j                   dd	g      |
      }t        j"                  |dz         }d|d<   d|d
<   t        j                  ||      }t        j$                  |t        j$                  ||            dd  }| j&                  dd }||z
  }t)        |||      }| j*                  d   }t        j,                  t        j                  d||z              |z  } |j.                  j0                  d|dz  z
  g|j2                   }||t        j4                  |      z  z
  |dddf<   ||t        j4                  |      z  z   |dddf<   t7        |ddd      }t9        |dd      }||fS )aM  Compute the prediction for a SARIMAX and get a conf interval

    Unfortunately, SARIMAX does not really provide a nice way to get the
    confidence intervals out of the box, so we have to perform the
    ``get_prediction`` code here and unpack the confidence intervals manually.

    Notes
    -----
    For internal use only.
    )startendexogalphasimple_differencingr   Nr   r	   r   g      FT)dtypecopypreserve_series)rD   rC    )get_predictionpredicted_meanconf_intspecificationmodel
orig_endogorig_k_difforig_k_seasonal_diffseasonal_periodsr   r   appendr   polynomial_reduced_arnp_polynomialpolypowarrayzerospolymulpolynomial_reduced_mar   _params_variancecumsumdistppf	dist_argssqrtr   r   )	arima_resr<   r=   Xr@   kwargsresultsfrI   y_orgdDperiody_sdifff_tempar_poly	poly_diffsdiff
poly_sdiffr!   r"   n_predMinus1r&   sigma2varr%   y_preds                              r*   $_seasonal_prediction_with_confidencerq      s   $ 'i&&  	G 	Ae,H45 **OO''OO0011q5 Ave4vq+AGYYwrs|Q/Ffa+FAx Aq5VaZYYuq6z]^4a8Fffa0FA()A11!))"((B9*=qA	!$ab	"**5!4
jj"**Y
"CDQRHH,,QR0U{r2|,++A.ii		"cCi01F:GLLR%!)^@g.?.?@Q--AQ--A$UDIF8%t<H8r+   c                       e Zd ZdZ	 	 	 	 	 	 	 	 	 	 d" fd	Zd#dZd#dZd Z	 	 	 	 	 	 d$dZ	 	 	 	 d%dZ	d Z
d	 Zd
 Zd Zd&dZ ed      d        Z ed      d        Z ed      d        Z ed      d        Z ed      d        Z ed      d        Z ed      d'd       Z ed      d        Z ed      d        Z ed      d        Z ed      d        Z ed      d        Z ed      d        Zd Z ed      d        Z ed      d        Z  ed      d        Z! ed      d        Z" ed      d         Z# ed      d(d!       Z$ xZ%S ))r   a&  An ARIMA estimator.

    An ARIMA, or autoregressive integrated moving average, is a
    generalization of an autoregressive moving average (ARMA) and is fitted to
    time-series data in an effort to forecast future points. ARIMA models can
    be especially efficacious in cases where data shows evidence of
    non-stationarity.

    The "AR" part of ARIMA indicates that the evolving variable of interest is
    regressed on its own lagged (i.e., prior observed) values. The "MA" part
    indicates that the regression error is actually a linear combination of
    error terms whose values occurred contemporaneously and at various times
    in the past. The "I" (for "integrated") indicates that the data values
    have been replaced with the difference between their values and the
    previous values (and this differencing process may have been performed
    more than once). The purpose of each of these features is to make the model
    fit the data as well as possible.

    Non-seasonal ARIMA models are generally denoted ``ARIMA(p,d,q)`` where
    parameters ``p``, ``d``, and ``q`` are non-negative integers, ``p`` is the
    order (number of time lags) of the autoregressive model, ``d`` is the
    degree of differencing (the number of times the data have had past values
    subtracted), and ``q`` is the order of the moving-average model. Seasonal
    ARIMA models are usually denoted ``ARIMA(p,d,q)(P,D,Q)m``, where ``m``
    refers to the number of periods in each season, and the uppercase ``P``,
    ``D``, ``Q`` refer to the autoregressive, differencing, and moving average
    terms for the seasonal part of the ARIMA model.

    When two out of the three terms are zeros, the model may be referred to
    based on the non-zero parameter, dropping "AR", "I" or "MA" from the
    acronym describing the model. For example, ``ARIMA(1,0,0)`` is ``AR(1)``,
    ``ARIMA(0,1,0)`` is ``I(1)``, and ``ARIMA(0,0,1)`` is ``MA(1)``. [1]

    See notes for more practical information on the ``ARIMA`` class.

    Parameters
    ----------
    order : iterable or array-like, shape=(3,)
        The (p,d,q) order of the model for the number of AR parameters,
        differences, and MA parameters to use. ``p`` is the order (number of
        time lags) of the auto-regressive model, and is a non-negative integer.
        ``d`` is the degree of differencing (the number of times the data have
        had past values subtracted), and is a non-negative integer. ``q`` is
        the order of the moving-average model, and is a non-negative integer.

    seasonal_order : array-like, shape=(4,), optional (default=(0, 0, 0, 0))
        The (P,D,Q,s) order of the seasonal component of the model for the
        AR parameters, differences, MA parameters, and periodicity. ``D`` must
        be an integer indicating the integration order of the process, while
        ``P`` and ``Q`` may either be an integers indicating the AR and MA
        orders (so that all lags up to those orders are included) or else
        iterables giving specific AR and / or MA lags to include. ``S`` is an
        integer giving the periodicity (number of periods in season), often it
        is 4 for quarterly data or 12 for monthly data. Default is no seasonal
        effect.

    start_params : array-like, optional (default=None)
        Starting parameters for ``ARMA(p,q)``.  If None, the default is given
        by ``ARMA._fit_start_params``.

    method : str, optional (default='lbfgs')
        The ``method`` determines which solver from ``scipy.optimize``
        is used, and it can be chosen from among the following strings:

        - 'newton' for Newton-Raphson
        - 'nm' for Nelder-Mead
        - 'bfgs' for Broyden-Fletcher-Goldfarb-Shanno (BFGS)
        - 'lbfgs' for limited-memory BFGS with optional box constraints
        - 'powell' for modified Powell's method
        - 'cg' for conjugate gradient
        - 'ncg' for Newton-conjugate gradient
        - 'basinhopping' for global basin-hopping solver

        The explicit arguments in ``fit`` are passed to the solver,
        with the exception of the basin-hopping solver. Each
        solver has several optional arguments that are not the same across
        solvers. These can be passed as **fit_kwargs

    maxiter : int, optional (default=50)
        The maximum number of function evaluations. Default is 50

    suppress_warnings : bool, optional (default=False)
        Many warnings might be thrown inside of statsmodels. If
        ``suppress_warnings`` is True, all of these warnings will be squelched.

    out_of_sample_size : int, optional (default=0)
        The number of examples from the tail of the time series to hold out
        and use as validation examples. The model will not be fit on these
        samples, but the observations will be added into the model's ``endog``
        and ``exog`` arrays so that future forecast values originate from the
        end of the endogenous vector. See :func:`update`.

        For instance::

            y = [0, 1, 2, 3, 4, 5, 6]
            out_of_sample_size = 2

            > Fit on: [0, 1, 2, 3, 4]
            > Score on: [5, 6]
            > Append [5, 6] to end of self.arima_res_.data.endog values

    scoring : str or callable, optional (default='mse')
        If performing validation (i.e., if ``out_of_sample_size`` > 0), the
        metric to use for scoring the out-of-sample data:

            * If a string, must be a valid metric name importable from
              ``sklearn.metrics``.
            * If a callable, must adhere to the function signature::

                def foo_loss(y_true, y_pred)

        Note that models are selected by *minimizing* loss. If using a
        maximizing metric (such as ``sklearn.metrics.r2_score``), it is the
        user's responsibility to wrap the function such that it returns a
        negative value for minimizing.

    scoring_args : dict, optional (default=None)
        A dictionary of key-word arguments to be passed to the
        ``scoring`` metric.

    trend : str or None, optional (default=None)
        The trend parameter. If ``with_intercept`` is True, ``trend`` will be
        used. If ``with_intercept`` is False, the trend will be set to a no-
        intercept value. If None and ``with_intercept``, 'c' will be used as
        a default.

    with_intercept : bool, optional (default=True)
        Whether to include an intercept term. Default is True.

    **sarimax_kwargs : keyword args, optional
        Optional arguments to pass to the SARIMAX constructor.
        Examples of potentially valuable kwargs:

          - time_varying_regression : boolean
            Whether or not coefficients on the exogenous regressors are allowed
            to vary over time.

          - enforce_stationarity : boolean
            Whether or not to transform the AR parameters to enforce
            stationarity in the auto-regressive component of the model.

          - enforce_invertibility : boolean
            Whether or not to transform the MA parameters to enforce
            invertibility in the moving average component of the model.

          - simple_differencing : boolean
            Whether or not to use partially conditional maximum likelihood
            estimation for seasonal ARIMA models. If True, differencing is
            performed prior to estimation, which discards the first
            :math:`s D + d` initial rows but results in a smaller
            state-space formulation. If False, the full SARIMAX model is
            put in state-space form so that all datapoints can be used in
            estimation. Default is False.

          - measurement_error: boolean
            Whether or not to assume the endogenous observations endog were
            measured with error. Default is False.

          - mle_regression : boolean
            Whether or not to use estimate the regression coefficients for the
            exogenous variables as part of maximum likelihood estimation or
            through the Kalman filter (i.e. recursive least squares). If
            time_varying_regression is True, this must be set to False.
            Default is True.

          - hamilton_representation : boolean
            Whether or not to use the Hamilton representation of an ARMA
            process (if True) or the Harvey representation (if False).
            Default is False.

          - concentrate_scale : boolean
            Whether or not to concentrate the scale (variance of the error
            term) out of the likelihood. This reduces the number of parameters
            estimated by maximum likelihood by one, but standard errors will
            then not be available for the scale parameter.

    Attributes
    ----------
    arima_res_ : ModelResultsWrapper
        The model results, per statsmodels

    endog_index_ : pd.Series or None
        If the fitted endog array is a ``pd.Series``, this value will be
        non-None and is used to validate args for in-sample predictions with
        non-integer start/end indices

    oob_ : float
        The MAE or MSE of the out-of-sample records, if ``out_of_sample_size``
        is > 0, else np.nan

    oob_preds_ : np.ndarray or None
        The predictions for the out-of-sample records, if
        ``out_of_sample_size`` is > 0, else None

    Notes
    -----
    * The model internally wraps the statsmodels `SARIMAX class <https://www.statsmodels.org/stable/generated/statsmodels.tsa.statespace.sarimax.SARIMAX.html>`_
    * After the model fit, many more methods will become available to the
      fitted model (i.e., :func:`pvalues`, :func:`params`, etc.). These are
      delegate methods which wrap the internal ARIMA results instance.

    See Also
    --------
    :func:`pmdarima.arima.auto_arima`

    References
    ----------
    .. [1] https://wikipedia.org/wiki/Autoregressive_integrated_moving_average
    c                 X   t         t        |           || _        || _        || _        || _        || _        || _        || _	        || _
        |	| _        |
| _        || _        dD ]>  \  }}|j                  |d       sd|z  }|r|dz  }t        j                   |t"               @ || _        y )N))dispT)callbackT)transparamsF)solverFzT'%s' is deprecated in the ARIMA constructor and will be removed in a future release.z Pass via **fit_kwargs instead)superr   __init__orderseasonal_orderstart_paramsmethodmaxitersuppress_warningsout_of_sample_sizescoringscoring_argstrendwith_interceptpopwarningswarnDeprecationWarningsarimax_kwargs)selfrz   r{   r|   r}   r~   r   r   r   r   r   r   r   deprecated_keystill_in_usemsg	__class__s                   r*   ry   zARIMA.__init__  s    $ 	eT#%
,(!2"4(
,-# 
	7(NL
 !!.$79;IJ;;Cc#56
	7 -r+   c                      fd} j                   rDt        j                  d      5  t        j                  d        |       \  } _        ddd       n |       \  } _        t        j                   j                         du _        j                  d    _	        t        j                   _         S # 1 sw Y   ]xY w)zInternal fitc            	      :   j                   } j                  }| t        d      |j                  rd}j                  si nj                  }t        j                  j                        }t        j                  j                  j                  d
	j                  ||d|}
j                  dj                        }j                  }|t        d      
j                  d|      }
j                  dd      } |j                   d
|| ||d	
}||fS )Nz$Expected non-None value for `method`c)r8   r>   rz   r{   r   r|   z%Expected non-None value for `maxiter`r~   rt   r   )r|   r}   r~   rt   rF   )r}   r   
ValueErrorr   r   	sm_compatcheck_seasonal_orderr{   smtsa
statespaceSARIMAXrz   r   r|   r~   fit)r}   r   r   r{   arimar|   _maxiterrt   fittedr_   fit_argsr   ys            r*   _fit_wrapperz ARIMA._fit.<locals>._fit_wrapper  s7   [[FJJE~ !GHH
 }!4!4 --43F3F  ..t/B/BC FF%%-- "atzz-" !	"E $<<8I8IJL ||H !HII  ||Ix8H<<*DUYY ) 	
 F &= r+   FrecordignoreNr   )r   r   catch_warningssimplefilter
arima_res_r   bind_df_modelfit_with_exog_shapenobs_pmdarima__version__pkg_version_)r   r   r_   r   r   r   s   ````  r*   _fitz
ARIMA._fit  s    /	!d !!((6 6%%h/'3~$T_6 6 $0> C 	T__5  tm WWQZ
 %00'6 6s   %C  C	c                    t        |t        d      }|j                  d   }t        |t        j
                        r|j                  nd| _        |t        |ddt              }| j                  }t        j                  | j                        }t        |d      }||k\  rt        d      d}d}|rO|| d }|d|  }|A|j                  d   }	t        |t!        |	|z
  |	            }t        |t!        d|	|z
              } | j"                  ||fi | |Y| j%                  ||      }
| j&                  si n| j&                  } |||
fi || _        |
| _         | j,                  ||fi | | S t.        j0                  | _        d| _        | S )	aD  Fit an ARIMA to a vector, ``y``, of observations with an
        optional matrix of ``X`` variables.

        Parameters
        ----------
        y : array-like or iterable, shape=(n_samples,)
            The time-series to which to fit the ``ARIMA`` estimator. This may
            either be a Pandas ``Series`` object (statsmodels can internally
            use the dates in the index), or a numpy array. This should be a
            one-dimensional array of floats, and should not contain any
            ``np.nan`` or ``np.inf`` values.

        X : array-like, shape=[n_obs, n_vars], optional (default=None)
            An optional 2-d array of exogenous variables. If provided, these
            variables are used as additional features in the regression
            operation. This should not include a constant or trend. Note that
            if an ``ARIMA`` is fit on exogenous features, it must be provided
            exogenous features for making predictions.

        **fit_args : dict or kwargs
            Any keyword arguments to pass to the statsmodels ARIMA fit.
        TrC   rE   r   NF)force_all_finiterD   rC   z7out-of-sample size must be less than number of samples!)	n_periodsr_   )r   r   r   
isinstancepdSeriesindexendog_index_r   r   valget_scoring_metricr   maxr   r   slicer   predictr   oob_
oob_preds_updater   nan)r   r   r_   r   	n_samplescvr   
cv_samplescv_exogn_exogpredr   s               r*   r   z	ARIMA.fit  s   . =GGAJ	 (2!RYY'?AGGT =1u5NA $$((6 QZ ? + , ,
 
B34J$B3A }'5"f+EF!!U1frk%:; 			!Q#(# ! <<"<8D%)%6%62D<M<ML
DALADI"DO
 DKK
G8x8
  DI"DOr+   c                 Z    | j                   r|t        d      t        |dt              S y )NzkWhen an ARIMA is fit with an X array, it must also be provided one for predicting or updating observations.T)r   rC   )r   r   r   r   )r   r_   s     r*   _check_exogzARIMA._check_exogq  s9    y  "H I I "!d%HHr+   c                 f   t        | d       | j                  d   }t        |t        j                        r||k  rt        d| d|       | j                  |      }| j                  }	|s|	j                  ||||      }
|
S |rt        j                  d       d}t        |	|||||      \  }
}|
|fS )	a	  Generate in-sample predictions from the fit ARIMA model.

        Predicts the original training (in-sample) time series values. This can
        be useful when wanting to visualize the fit, and qualitatively inspect
        the efficacy of the model, or when wanting to compute the residuals
        of the model.

        Parameters
        ----------
        X : array-like, shape=[n_obs, n_vars], optional (default=None)
            An optional 2-d array of exogenous variables. If provided, these
            variables are used as additional features in the regression
            operation. This should not include a constant or trend. Note that
            if an ``ARIMA`` is fit on exogenous features, it must be provided
            exogenous features for making predictions.

        start : int or object, optional (default=None)
            Zero-indexed observation number at which to start forecasting, ie.,
            the first forecast is start. Note that if this value is less than
            ``d``, the order of differencing, an error will be raised.
            Alternatively, a non-int value can be given if the model was fit
            on a ``pd.Series`` with an object-type index, like a timestamp.

        end : int or object, optional (default=None)
            Zero-indexed observation number at which to end forecasting, ie.,
            the first forecast is start. Alternatively, a non-int value can be
            given if the model was fit on a ``pd.Series`` with an object-type
            index, like a timestamp.

        dynamic : bool, optional (default=False)
            The `dynamic` keyword affects in-sample prediction. If dynamic
            is False, then the in-sample lagged values are used for
            prediction. If `dynamic` is True, then in-sample forecasts are
            used in place of lagged dependent variables. The first forecasted
            value is `start`.

        return_conf_int : bool, optional (default=False)
            Whether to get the confidence intervals of the forecasts.

        alpha : float, optional (default=0.05)
            The confidence intervals for the forecasts are (1 - alpha) %

        Returns
        -------
        preds : array
            The predicted values.

        conf_int : array-like, shape=(n_periods, 2), optional
            The confidence intervals for the predictions. Only returned if
            ``return_conf_int`` is True.
        r   r   z*In-sample predictions undefined for start=z when d=)r>   r<   r=   dynamiczUCannot produce in-sample confidence intervals for dynamic=True. Setting dynamic=FalseF)r^   r<   r=   r_   r@   r   )r   rz   r   numbersIntegralr   r   r   r   r   r   rq   )r   r_   r<   r=   r   return_conf_intr@   r`   rd   results_wrapperpredsrI   s               r*   predict_in_samplezARIMA.predict_in_sample|  s    z 	l+
 JJqMeW--.519<UG8A3O 
 Q// #++	 , E L MM @ AG ?%
x hr+   c                 r   t        | d       t        |t              st        d      | j	                  |      }|0|j
                  d   |k7  rt        d|j
                  d    d|       | j                  }|j                  |z   dz
  }t        ||j                  |||      \  }}	|r|t        |	d	      fS |S )
an  Forecast future values

        Generate predictions (forecasts) ``n_periods`` in the future.
        Note that if ``exogenous`` variables were used in the model fit, they
        will be expected for the predict procedure and will fail otherwise.

        Parameters
        ----------
        n_periods : int, optional (default=10)
            The number of periods in the future to forecast.

        X : array-like, shape=[n_obs, n_vars], optional (default=None)
            An optional 2-d array of exogenous variables. If provided, these
            variables are used as additional features in the regression
            operation. This should not include a constant or trend. Note that
            if an ``ARIMA`` is fit on exogenous features, it must be provided
            exogenous features for making predictions.

        return_conf_int : bool, optional (default=False)
            Whether to get the confidence intervals of the forecasts.

        alpha : float, optional (default=0.05)
            The confidence intervals for the forecasts are (1 - alpha) %

        Returns
        -------
        forecasts : array-like, shape=(n_periods,)
            The array of fore-casted values.

        conf_int : array-like, shape=(n_periods, 2), optional
            The confidence intervals for the forecasts. Only returned if
            ``return_conf_int`` is True.
        r   zn_periods must be an intr   z4X array dims (n_rows) != n_periods. Received n_rows=z and n_periods=r   )r^   r<   r=   r_   r@   F)r   )r   r   int	TypeErrorr   r   r   r   r0   rq   r   )
r   r   r_   r   r@   r`   r   r=   rb   rI   s
             r*   r   zARIMA.predict  s    N 	l+)S)677 Q=QWWQZ94''!*_YKA  jj9$q(:**8  k(UCCCr+   c                     | j                   S )zI am being pickled...)__dict__r   s    r*   __getstate__zARIMA.__getstate__*  s     }}r+   c                 4    || _         | j                          | S )zI am being unpickled...)r   _warn_for_older_version)r   states     r*   __setstate__zARIMA.__setstate__9  s     	$$&r+   c                     d}d }t         j                  }	 t        | d      }||k7  rd}|r"t        j                  d|d|dt               y y # t        $ r t	        | d      rd}d}Y @w xY w)	NFr   Tr   z<0.8.1z-You've deserialized an ARIMA from a version (z:) that does not match your installed version of pmdarima (z(). This could cause unforeseen behavior.)r   r   getattrAttributeErrorhasattrr   r   UserWarning)r   do_warnmodl_versionthis_versions       r*   r   zARIMA._warn_for_older_versionA  s     ++	("48L |+ MM *<	9 ;F	G   	( t\*'	(s   A A*)A*c                     | j                   \  }}}| j                  \  }}}}d}| j                  }	dj                  ||||||||	r|      S dt	        |      z        S )z?Different from __repr__, returns a debug string used in logging	interceptz1 ARIMA({p},{d},{q})({P},{D},{Q})[{m}] {intercept} )r$   rd   r%   Pre   Qmr   )rz   r{   r   formatr   )
r   r$   rd   r%   r   re   r   r   int_strr   s
             r*   __str__zARIMA.__str__a  s    **1a((
1a,,?FF%3' G 
	
 :=s7|9K G 
	
r+   c                    t        | d       | j                  }t        |      s|g}t        |t        d      }|j
                  d   }| j                  |      }|`|j                  j                  }|j
                  \  }}	|j
                  d   |k7  rt        d| d|	 d	      ||k7  rt        d
| d| d	      t        j                  t        |j                  j                  |            }|.t        j                  |j                  j                   |fd      }
nd}
|t#        d|dz        }|j$                  } | j&                  ||
f||d| | S )a  Update the model fit with additional observed endog/exog values.

        Updating an ARIMA adds new observations to the model, updating the
        MLE of the parameters accordingly by performing several new iterations
        (``maxiter``) from the existing model parameters.

        Parameters
        ----------
        y : array-like or iterable, shape=(n_samples,)
            The time-series data to add to the endogenous samples on which the
            ``ARIMA`` estimator was previously fit. This may either be a Pandas
            ``Series`` object or a numpy array. This should be a one-
            dimensional array of finite floats.

        X : array-like, shape=[n_obs, n_vars], optional (default=None)
            An optional 2-d array of exogenous variables. If the model was
            fit with an exogenous array of covariates, it will be required for
            updating the observed values.

        maxiter : int, optional (default=None)
            The number of iterations to perform when updating the model. If
            None, will perform ``max(5, n_samples // 10)`` iterations.

        **kwargs : keyword args
            Any keyword args that should be passed as ``**fit_kwargs`` in the
            new model fit.

        Notes
        -----
        * Internally, this calls ``fit`` again using the OLD model parameters
          as the starting parameters for the new model's MLE computation.
        r   Tr   r   Nr   zDim mismatch in fit `X` (z) and new `X` ()zDim mismatch in n_samples (y=z, X=)axis   
   )r|   r~   )r   r   r   r   r   r   r   rK   k_exogr   r   squeezer:   datar8   r5   r>   r   paramsr   )r   r   r_   r~   r`   	model_resr   r   r   exog_dimX_primer   s               r*   r   zARIMA.updateu  so   B 	l+OO	 1~A =GGAJ	 Q =__++F wwFHwwqzV# /x 8$:Q(  " 3I;d6(!L 
 JJ'	(<(<a@A =nninn&9&91%=AFG G
 ?!Y"_-G !!		!WM67MfM r+   r   c                 .    | j                   j                  S )a  Get the AIC, the Akaike Information Criterion:

            :code:`-2 * llf + 2 * df_model`

        Where ``df_model`` (the number of degrees of freedom in the model)
        includes all AR parameters, MA parameters, constant terms parameters
        on constant terms and the variance.

        Returns
        -------
        aic : float
            The AIC

        References
        ----------
        .. [1] https://en.wikipedia.org/wiki/Akaike_information_criterion
        )r   r-   r   s    r*   r-   z	ARIMA.aic      & """r+   c                 Z    t        | j                  | j                  | j                         S )a:  Get the AICc, the corrected Akaike Information Criterion:

            :code:`AIC + 2 * df_model * (df_model + 1) / (nobs - df_model - 1)`

        Where ``df_model`` (the number of degrees of freedom in the model)
        includes all AR parameters, MA parameters, constant terms parameters
        on constant terms and the variance. And ``nobs`` is the sample size.

        Returns
        -------
        aicc : float
            The AICc

        References
        ----------
        .. [1] https://en.wikipedia.org/wiki/Akaike_information_criterion#AICc
        )r2   r   r   r   r   s    r*   aiccz
ARIMA.aicc  s*    . T__ZZ,,,. 	.r+   c                 .    | j                   j                  S )zGet the parameters associated with the AR coefficients in the model.

        Returns
        -------
        arparams : array-like
            The AR coefficients.
        )r   arparamsr   s    r*   r   zARIMA.arparams       '''r+   c                 .    | j                   j                  S )at  The roots of the AR coefficients are the solution to:

            :code:`(1 - arparams[0] * z - arparams[1] * z^2 - ... - arparams[
            p-1] * z^k_ar) = 0`

        Stability requires that the roots in modulus lie outside the unit
        circle.

        Returns
        -------
        arroots : array-like
            The roots of the AR coefficients.
        )r   arrootsr   s    r*   r   zARIMA.arroots       &&&r+   c                 .    | j                   j                  S )a  Get the BIC, the Bayes Information Criterion:

            :code:`-2 * llf + log(nobs) * df_model`

        Where if the model is fit using conditional sum of squares, the
        number of observations ``nobs`` does not include the ``p`` pre-sample
        observations.

        Returns
        -------
        bse : float
            The BIC

        References
        ----------
        .. [1] https://en.wikipedia.org/wiki/Bayesian_information_criterion
        )r   bicr   s    r*   r  z	ARIMA.bic  r   r+   c                 .    | j                   j                  S )zGet the standard errors of the parameters. These are
        computed using the numerical Hessian.

        Returns
        -------
        bse : array-like
            The BSE
        )r   bser   s    r*   r  z	ARIMA.bse4  s     """r+   c                 >     | j                   j                  dd|i|S )a  Returns the confidence interval of the fitted parameters.

        Returns
        -------
        alpha : float, optional (default=0.05)
            The significance level for the confidence interval. ie.,
            the default alpha = .05 returns a 95% confidence interval.

        **kwargs : keyword args or dict
            Keyword arguments to pass to the confidence interval function.
            Could include 'cols' or 'method'
        r@   rF   )r   rI   )r   r@   r`   s      r*   rI   zARIMA.conf_int@  s#     (t''>e>v>>r+   c                 .    | j                   j                  S )zThe model degrees of freedom: ``k_exog`` + ``k_trend`` +
        ``k_ar`` + ``k_ma``.

        Returns
        -------
        df_model : array-like
            The degrees of freedom in the model.
        )r   r.   r   s    r*   r.   zARIMA.df_modelP  s     '''r+   c                 .    | j                   j                  S )zGet the residual degrees of freedom:

            :code:`nobs - df_model`

        Returns
        -------
        df_resid : array-like
            The residual degrees of freedom.
        )r   df_residr   s    r*   r	  zARIMA.df_resid\  s     '''r+   c                 .    | j                   j                  S )zGet the fitted values from the model

        Returns
        -------
        fittedvalues : array-like
            The predicted values for the original series
        )r   fittedvaluesr   s    r*   r  zARIMA.fittedvaluesi  s     +++r+   c                 .    | j                   j                  S )a  Get the Hannan-Quinn Information Criterion:

            :code:`-2 * llf + 2 * (`df_model`) * log(log(nobs))`

        Like :func:`bic` if the model is fit using conditional sum of squares
        then the ``k_ar`` pre-sample observations are not counted in ``nobs``.

        Returns
        -------
        hqic : float
            The HQIC

        References
        ----------
        .. [1] https://en.wikipedia.org/wiki/Hannan-Quinn_information_criterion
        )r   hqicr   s    r*   r  z
ARIMA.hqict  s    $ ###r+   c                 .    | j                   j                  S )zGet the value of the moving average coefficients.

        Returns
        -------
        maparams : array-like
            The MA coefficients.
        )r   maparamsr   s    r*   r  zARIMA.maparams  r   r+   c                 .    | j                   j                  S )a]  The roots of the MA coefficients are the solution to:

            :code:`(1 + maparams[0] * z + maparams[1] * z^2 + ... + maparams[
            q-1] * z^q) = 0`

        Stability requires that the roots in modules lie outside the unit
        circle.

        Returns
        -------
        maroots : array-like
            The MA roots.
        )r   marootsr   s    r*   r  zARIMA.maroots  r  r+   c                     | j                   S )zIf the model was built with ``out_of_sample_size`` > 0, a validation
        score will have been computed. Otherwise it will be np.nan.

        Returns
        -------
        oob_ : float
            The "out-of-bag" score.
        )r   r   s    r*   oobz	ARIMA.oob  s     yyr+   c                 .    | j                   j                  S )a\  Get the parameters of the model. The order of variables is the trend
        coefficients and the :func:`k_exog` exogenous coefficients, then the
        :func:`k_ar` AR coefficients, and finally the :func:`k_ma` MA
        coefficients.

        Returns
        -------
        params : array-like
            The parameters of the model.
        )r   r   r   s    r*   r   zARIMA.params  s     %%%r+   c                 .    | j                   j                  S )zGet the p-values associated with the t-values of the coefficients.
        Note that the coefficients are assumed to have a Student's T
        distribution.

        Returns
        -------
        pvalues : array-like
            The p-values.
        )r   pvaluesr   s    r*   r  zARIMA.pvalues  s     &&&r+   c                 .    | j                   j                  S )a  Get the model residuals. If the model is fit using 'mle', then the
        residuals are created via the Kalman Filter. If the model is fit
        using 'css' then the residuals are obtained via
        ``scipy.signal.lfilter`` adjusted such that the first :func:`k_ma`
        residuals are zero. These zero residuals are not returned.

        Returns
        -------
        resid : array-like
            The model residuals.
        )r   residr   s    r*   r  zARIMA.resid  s     $$$r+   c                 6    | j                   j                         S )z Get a summary of the ARIMA model)r   summaryr   s    r*   r  zARIMA.summary  s     &&((r+   c                 N   t        j                  | j                        }| j                         | j	                         | j
                  || j                         | j                         | j                         | j                         | j                         | j                         d
S )zGet the ARIMA model as a dictionary

        Return the dictionary representation of the ARIMA model

        Returns
        -------
        res : dictionary
            The ARIMA model as a dictionary.
        )
r  r  rz   r{   r  r-   r   r  r  r   )r   r   r{   r  r  rz   r  r-   r   r  r  r   )r   seasonals     r*   to_dictzARIMA.to_dict  sv     11$2E2EF||~ZZ\ZZ&88:88:IIK88:88:kkm
 	
r+   c                 r   t                ddlm} |j                  ||      }| j                  }|j
                  }t        |d      rV|j                  }t        |d      r t        j                  ||j                        }|j                  j                  ||df   }	n<d}|j                  }
|
t        j                  |
      z
  t        j                  |
      z  }	|j!                  d      }t        |d      r*|j"                  |j"                  |d j%                         }nt        j&                  t)        |	            }|j+                  ||	       |j-                  d|d   |d   d	
       |j/                  |d   |d          |j1                  d       |	t        j2                  |	          }|j!                  d      }t5        j6                  d      5   |j8                  |fddit;        j<                          ddd       t?        |      }d}t        j@                  |d   |d         }|j+                  | ||      d       |j+                  |tC        jD                  |      d       |j/                  |       |jG                          |j1                  d       |j!                  d      }ddlm$} |jK                  |d|       |j1                  d       |j!                  d      }ddlm&} |jO                  |	||       |j1                  d       |jQ                  dd       |S # 1 sw Y   2xY w) a  Plot an ARIMA's diagnostics.

        Diagnostic plots for standardized residuals of one endogenous variable

        Parameters
        ----------
        variable : integer, optional
            Index of the endogenous variable for which the diagnostic plots
            should be created. Default is 0.

        lags : integer, optional
            Number of lags to include in the correlogram. Default is 10.

        fig : Matplotlib Figure instance, optional
            If given, subplots are created in this figure instead of in a new
            figure. Note that the 2x2 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
        -----
        Produces a 2x2 plot grid with the following plots (ordered clockwise
        from top left):

        1. Standardized residuals over time
        2. Histogram plus estimated density of standardized residuals, along
           with a Normal(0,1) density plotted for reference.
        3. Normal Q-Q plot, with Normal reference line.
        4. Correlogram

        See Also
        --------
        statsmodels.graphics.gofplots.qqplot
        pmdarima.utils.visualization.plot_acf

        References
        ----------
        .. [1] https://www.statsmodels.org/dev/_modules/statsmodels/tsa/statespace/mlemodel.html#MLEResults.plot_diagnostics
        r   )utilsloglikelihood_burnnobs_diffuseN   datesrB   g      ?r?   zStandardized residual   Tr   labelHist)g\(\g\(\@r   KDE)r%  zN(0,1)z Histogram plus estimated density   )gofplotss)lineaxz
Normal Q-Q   )tsaplots)r,  lagsCorrelogram))r   statsmodels.graphicsr  create_mpl_figr   r   r   r   r   maximumr!  filter_resultsstandardized_forecasts_errorr  nanmeannanstdadd_subplotr#  	_mpl_repraranger   plothlinesset_xlim	set_titleisnanr   r   hist
mpl_compatmpl_hist_argr   linspacer   pdflegendr)  qqplotr.  plot_acfset_ylim)r   variabler/  figfigsizesm_graphicsres_wprr   rd   r  rr,  xresid_nonmissingkdexlimr)  r.  s                     r*   plot_diagnosticszARIMA.plot_diagnostics  s   Z 	

 	>((g6//|| 701 **Aw/JJq'"6"67**8812GE AAA&"))A,6E __S!4!djj&<

12((*A		#e*%A
5
		!QqT1R5	,
AaD!B% 
,-
 !288E?!34__S!
 $$D1 	BGG  ))+	 +,$KKQa)
3q6'
488A;h/
D
		
78 __S!1(sr:
\" __S!1%BT2
]#
B
=	 	s   (L,,L6)
)r   r   r   r   Nlbfgs2   Fr   mseNNT)N)NNNFF皙?)r   NFrW  )NN)rW  )r   r   NN)&__name__
__module____qualname____doc__ry   r   r   r   r   r   r   r   r   r   r   r   r-   r   r   r   r   r  r  rI   r.   r	  r  r  r  r  r  r   r  r  r  r  rS  __classcell__)r   s   @r*   r   r      sr   Ph $--^JXPd	 gT  %	CJG@
([z L)# *#* \". #.4 L)( *( L)' *'  L)# *#( L)	# *	# L)? *? L)	( *	( L)
( *
( L), *, L)$ *$& L)( *( L)' *' 	 L)& *& L)
' *
' L)% *% L)) *) \"
 #
0 \"B #Br+   )1pandasr   numpyr   numpy.polynomial.polynomial
polynomialrR   r   r   scipy.statsr   r   sklearn.utils.validationr   r   r   r    r   r   baser
   compat.numpyr   compat.sklearnr   r   r   compatr   r   rA  r  r   r   r   r   utils.visualizationr   utils.arrayr   r   r   __all__r   r2   r:   rq   r   rF   r+   r*   <module>rk     s      3 3   * 0 !       . - I I * (  HV	F> AHhI hr+   