
    DjX                         d dl 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mZ dd	lmZ dd
lmZmZ ddlmZ dgZd Z G d de      Zy)    )isliceN)BaseEstimatorclone   )	BaseARIMA)BaseTransformer)BaseEndogTransformer)BaseExogTransformerBaseExogFeaturizer)check_endog)DTYPEcheck_is_fitted)if_delegate_has_methodPipelinec                  t    dD ]2  }| j                  |d       st        j                  d|z  t               4 | S )N)typz:'%s' is deprecated and will be removed in a future release)popwarningswarnDeprecationWarning)kwargsks     UC:\Crop_Prediction\Backend\crop-ai-system\venv\Lib\site-packages\pmdarima/pipeline.py_warn_for_deprecatedr      sB     .::aMM $&'(,..
 M    c                       e Zd ZdZd Zd Zd ZddZd Zd Z	e
d        Ze
d	        Zd
 ZddZd ZddZ	 	 	 	 	 	 	 ddZ	 	 	 	 	 ddZd Z ed      d        ZddZy)r   aL	  A pipeline of transformers with an optional final estimator stage

    The pipeline object chains together an arbitrary number of named, ordered
    transformations, passing the output from one as the input to the next. As
    the last stage, an ``ARIMA`` or ``AutoARIMA`` object will be fit. This
    pipeline takes after the scikit-learn ``sklearn.Pipeline`` object, which
    behaves similarly but does not share the same time-series interface
    that ``pmdarima`` follows.

    The purpose of the pipeline is to assemble several steps that can be
    cross-validated together while setting different parameters.
    For this, it enables setting parameters of the various steps using their
    names and the parameter name separated by a `'__'`, as in the example
    below.

    Parameters
    ----------
    steps : list
        List of (name, transform) tuples (implementing fit/transform) that are
        chained, in the order in which they are chained, with the last object
        an ARIMA or AutoARIMA estimator.

    Examples
    --------
    >>> from pmdarima.datasets import load_wineind
    >>> from pmdarima.arima import AutoARIMA
    >>> from pmdarima.pipeline import Pipeline
    >>> from pmdarima.preprocessing import FourierFeaturizer
    >>>
    >>> wineind = load_wineind()
    >>> pipeline = Pipeline([
    ...     ("fourier", FourierFeaturizer(m=12, k=3)),
    ...     ("arima", AutoARIMA(seasonal=False, stepwise=True,
    ...                         suppress_warnings=True,
    ...                         error_action='ignore'))
    ... ])
    >>> pipeline.fit(wineind)
    Pipeline(steps=[('fourier', FourierFeaturizer(k=3, m=12)),
                    ('arima', AutoARIMA(D=None, alpha=0.05, callback=None,
                                        d=None, disp=0, error_action='ignore',
                                        information_criterion='aic', m=1,
                                        max_D=1, max_P=2, max_Q=2, max_d=2,
                                        max_order=10, max_p=5, max_q=5,
                                        maxiter=None, method=None,
                                        n_fits=10, n...s_warnings=True,
                                        test='kpss', trace=False,
                                        transparams=True, trend=None,
                                        with_intercept=True))])
    c                 2    || _         | j                          y N)steps_validate_steps)selfr   s     r   __init__zPipeline.__init__Q   s    
r   c                    t        t        |            t        |      k7  r#t        dj                  t	        |                  t        |      j                  | j                  d            }|r#t        dj                  t        |                  |D cg c]	  }d|v s| }}|rt        dj                  |            y c c}w )Nz$Names provided are not unique: {0!r}F)deepz:Estimator names conflict with constructor arguments: {0!r}__z.Estimator names must not contain __: got {0!r})lenset
ValueErrorformatlistintersection
get_paramssorted)r!   namesinvalid_namesnames       r   _validate_nameszPipeline._validate_namesU   s    s5z?c%j( %%+VDK%8: :E
//U0KL 006vm7L0MO O*/@$44<@@ %%+VM%:< <  As   	C!Cc           	      F   t        | j                   \  }}| j                  |       |d d }|d   }|D ]-  }t        |t              rt        d|dt        |      d       t        |t              st        d|dt        |      d      t        | j                        S )NzDAll intermediate steps should be instances of BaseTransformer, but 'z' (type z) is notz4Last step of Pipeline should be of type BaseARIMA. 'z) isn't)	zipr   r1   
isinstancer   	TypeErrortyper   r*   )r!   r.   
estimatorstransformers	estimatorts         r   r    zPipeline._validate_stepsb   s    ,z 	U# "#2rN	 	HAa1;<d1g!G H H	H )Y/*3T)_FG G
 DJJr   c              #      K   t        | j                        }|s|dz  }t        t        | j                  d|            D ]  \  }\  }}|||f  yw)z/
        Generate (name, trans) tuples
        r   r   N)r&   steps_	enumerater   )r!   
with_finalstopidxr0   transs         r   _iterzPipeline._iter{   sY     
 4;;AID"+F4;;4,H"I 	#C$tU""	#s   AAc                     | j                   D ci c]
  \  }}||i  }}}|j                         D ]"  \  }}|j                  dd      \  }}|||   |<   $ |S c c}}w )Nr%   r   )r   itemssplit)r!   paramsr0   stepparams_stepspnamepvalparams           r   _get_kwargszPipeline._get_kwargs   sy    37:: -ZT4+ b - -!<<> 	-KE4++dA.KD%(,Lu%	- -s   Ac                 ,    t        | j                        S )z4
        Returns the length of the Pipeline
        )r&   r   r!   s    r   __len__zPipeline.__len__   s     4::r   c                 ,    t        | j                        S )zMap the steps to a dictionary)dictr   rO   s    r   named_stepszPipeline.named_steps   s     DJJr   c                 *    | j                   d   d   }|S )Nr3   r   )r   )r!   r:   s     r   _final_estimatorzPipeline._final_estimator   s    JJrN1%	r   c                 <    |t        |      |k7  rt        |      }|S r   )r&   )r!   	n_periodsexogs      r   _check_n_periodszPipeline._check_n_periods   s"    D	Y 6D	Ir   Nc                    | j                         x}| _        t        |t        dd      }|} | j                  d	i |}|j
                  d   | _        | j                  d      D ]4  \  }}	}
t        |
      }||	   } |j                  ||fi |\  }}|	|f||<   6 t        |t        j                        r|j                  j                         nd| _        ||d   d      } | j                   j"                  |fd|i| | S )
a  Fit the pipeline of transformers and the ARIMA model

        Chain the time-series and X array through a series of
        transformations, fitting each stage along the way, finally fitting an
        ARIMA or AutoARIMA model.

        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_kwargs : keyword args
            Extra keyword arguments used for each stage's ``fit`` stage.
            Similar to scikit-learn pipeline keyword args, the keys are
            compound, comprised of the stage name and the argument name
            separated by a "__". For instance, if fitting an ARIMA in stage
            "arima", your kwargs may resemble::

                {"arima__maxiter": 10}
        FT)dtypecopypreserve_seriesr   r?   Nr3   X )r    r=   r   r   rM   shape
n_samples_rC   r   fit_transformr5   pd	DataFramecolumnstolistx_feats_rU   fit)r!   yr_   
fit_kwargsr   ytXtnamed_kwargsstep_idxr0   transformercloned_transformerr   s                r   ri   zPipeline.fit   s   B #2244%eTJ't''5*5 ((1++/:::+G 	9'HdK!&{!3!$'F5'55b"GGFB  $%78E(O	9 "bll+ 

))+15 	 eBil+!!!"55f5r   c           
         t        | d       |} | j                  di |}| j                  d      D ]v  \  }}}t        |t              s||   }	t        |t
              r3|	j                  dd      }
|
|
|k7  rt        d|d|
d|d	      ||	d<    |j                  d|fi |	\  }}x | j                  || j                     }| j                  d
   \  }}||||   fS )z3Runs transformation steps before predicting on datar=   Fr^   rW   Nz)Manually set 'n_periods' kwarg for step 'z&' differs from forecasting n_periods (z != )r3   r`   )r   rM   rC   r5   r
   r   getr(   	transformrh   r=   )r!   rW   r_   r   rm   rn   ro   r0   rp   kwnum_p_nmests                 r   _pre_predictzPipeline._pre_predict   s   h' 't''1&1+/:::+G 	>'HdK+':;!$' k+=>FF;5E(Ui-?( -1%*D E E '0B{O .--dB="=2!	>* ==$DMM"B ++b/C3R(((r   c                 p    | j                  ||      }t        di |} | j                  ||fi |\  }}}|S )a  Get the transformed X array

        Generate the X array ``n_periods`` in the future. This passes
        the provided exog variables through all transformation steps, returning
        it before it's passed into the model.

        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.
        **kwargs : keyword args
            Extra keyword arguments used for each stage's ``transform`` stage
            and the estimator's ``predict`` stage. Similar to scikit-learn
            pipeline keyword args, the keys are compound, comprised of the
            stage name and the argument name separated by a "__". For instance,
            if you have a FourierFeaturizer whose stage is named
            "fourier", your transform kwargs could resemble::

                {"fourier__n_periods": 50}

        Returns
        -------
        X_prime : pd.DataFrame
            The transformed exog array.
        r`   )rY   r   r{   )r!   rW   r_   r   rm   rx   s         r   ru   zPipeline.transform  sH    D )))Q7	%//$4$$Y<V<Aq	r   c           
          t        di |} | j                  d|fi |\  }	}
} |
j                  d|	|||||d|}| j                  |	|||      S )a
  Generate in-sample predictions from the fit pipeline.

        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, optional (default=None)
            Zero-indexed observation number at which to start forecasting, ie.,
            the first forecast is start.

        end : int, optional (default=None)
            Zero-indexed observation number at which to end forecasting, ie.,
            the first forecast is start.

        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) %

        inverse_transform : bool, optional (default=True)
            Whether to inverse transform predictions, if they are in log or
            BoxCox scale. Any endog transformer will be inverse-transformed.

        **kwargs : keyword args
            Extra keyword arguments used for each stage's ``transform`` stage.
            Similar to scikit-learn pipeline keyword args, the keys are
            compound, comprised of the stage name and the argument name
            separated by a "__". For instance, if you have a FourierFeaturizer
            whose stage is named "fourier", your transform kwargs could
            resemble::

                {"fourier__n_periods": 50}

        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_   startendreturn_conf_intalphadynamicr`   )r   r{   predict_in_sample_post_predict)r!   r_   r~   r   r   r   r   inverse_transformr   rm   rz   predict_kwargsreturn_valss                r   r   zPipeline.predict_in_sample-  s    J &//"3$"3"3Aq"CF"CC+c++ +  !!_.?A 	Ar   c                     | j                  ||      }t        di |} | j                  ||fi |\  }}}	 |j                  d||||d|	}
| j	                  ||
||      S )a  Forecast future (transformed) values

        Generate predictions (forecasts) ``n_periods`` in the future.
        Note that if an ``X`` array was used in the model fit, it
        will be expected for the predict procedure and will fail otherwise.
        Forecasts may be transformed by the endogenous steps along the way and
        might be on a different scale than raw training/test data.

        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) %

        inverse_transform : bool, optional (default=True)
            Whether to inverse transform predictions, if they are in log or
            BoxCox scale. Any endog transformer will be inverse-transformed.

        **kwargs : keyword args
            Extra keyword arguments used for each stage's ``transform`` stage
            and the estimator's ``predict`` stage. Similar to scikit-learn
            pipeline keyword args, the keys are compound, comprised of the
            stage name and the argument name separated by a "__". For instance,
            if you have a FourierFeaturizer whose stage is named
            "fourier", your transform kwargs could resemble::

                {"fourier__n_periods": 50}

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

        conf_int : array-like, shape=(n_periods, 2), optional
            The confidence intervals for the forecasts. Only returned if
            ``return_conf_int`` is True.
        )rW   r_   r   r   r`   )rY   r   r{   predictr   )r!   rW   r_   r   r   r   r   rm   rz   r   r   s              r   r   zPipeline.predict  s    p )))Q7	%//"3$"3"3q#$"#$C "ckk +	
  !!_.?A 	Ar   c                 B   |s|S |}d}|r|\  }}| j                   ddd   D ]t  \  }}t        |t              s|j                  ||      \  }}|s/|j                  |dddf   |      \  |dddf<   }	|j                  |dddf   |      \  |dddf<   }	v |r||fS |S )z4Inverse-transform predictions to original data scaleNr3   r   r   )r=   r5   r	   r   )
r!   rm   r   r   r   y_pred	conf_intsr0   rp   rx   s
             r   r   zPipeline._post_predict  s     !	 &FI "&TrT!2 		-D++';<(::62F
" *5)F)F!!Q$*-&IadOQ)4)F)F!!Q$*-&IadOQ		- 9$$r   rU   c                 6    | j                   j                         S )z Get a summary of the ARIMA model)rU   summaryrO   s    r   r   zPipeline.summary  s     $$,,..r   c                    t        | d       |}|} | j                  di |}| j                  d      D ]G  \  }}	}
||	   }t        |
d      r |
j                  d||d|\  }}1 |
j
                  ||fi |\  }}I | j                  || j                     }| j                  d   \  }} |j                  |f||d||   S )	a  Update an ARIMA or auto-ARIMA as well as any necessary transformers

        Passes the newly observed values through the appropriate endog
        transformations, and the ``X`` array through the exog transformers
        (updating where necessary) before finally updating the ARIMA model.

        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
            Extra keyword arguments used for each stage's ``update`` stage.
            Similar to scikit-learn pipeline keyword args, the keys are
            compound, comprised of the stage name and the argument name
            separated by a "__".
        r=   Fr^   update_and_transform)rj   r_   r3   )r_   maxiterr`   )	r   rM   rC   hasattrr   ru   rh   r=   update)r!   rj   r_   r   r   rl   rm   rn   ro   r0   rp   rv   ry   rz   s                 r   r   zPipeline.update  s   < 	h' 't''1&1+/:::+G 	='HdKd#B{$:;999 &B&"$&B /..r2<<B	= ==$DMM"B ++b/Cszz;g;)5b)9; 	;r   )Tr   )
   N)NNNFF皙?T)r   NFr   T)NN)__name__
__module____qualname____doc__r"   r1   r    rC   rM   rP   propertyrS   rU   rY   ri   r{   ru   r   r   r   r   r   r   r`   r   r   r   r      s    0d< 2
#      :x#)J%P ! $""'*/ $,0RAj  %"&EAN> .// 0/4;r   )	itertoolsr   pandasrd   r   sklearn.baser   r   baser   preprocessing.baser   preprocessing.endog.baser	   preprocessing.exog.baser
   r   utilsr   compatr   r   compat.sklearnr   __all__r   r   r`   r   r   <module>r      sB       -  / : L  * 2,B;} B;r   