Ë
    £�Dj¿-  ã                   óž   — d Z ddlZddlZddlm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 g d	¢Zd
„ Zd„ Z	 	 	 	 	 dd„Z G d„ d«      Zy)z+
Seasonal Decomposition by Moving Averages
é    N)Únanmean)ÚPandasWrapperÚ
array_like)ÚSTL)Úconvolution_filter)ÚMSTL)Úfreq_to_period)r   Úseasonal_decomposeÚseasonal_meanÚDecomposeResultr   c           
      óV  — t        d„ t        | «      D «       «      }| j                  d   dz
  t        d„ t        | ddd…   «      D «       «      z
  }t        ||z   |«      }t	        |||z
  «      }t
        j                  j                  t
        j                  t        j                  ||«      t        j                  ||z
  «      f   | || d¬«      d   \  }}t        j                  d|«      t
        j                  |   z  t
        j                  |   z   j                  }| j                  dk(  r|j                  «       }|| d| t
        j                  j                  t
        j                  t        j                  ||«      t        j                  ||z
  «      f   | || d¬«      d   \  }}t        j                  |dz   | j                  d   «      t
        j                  |   z  t
        j                  |   z   j                  }| j                  dk(  r|j                  «       }|| |dz   d | S )z™
    Replace nan values on trend's end-points with least-squares extrapolated
    values with regression considering npoints closest defined points.
    c              3   óx   K  — | ]2  \  }}t        j                  t        j                  |«      «      rŒ/|–— Œ4 y ­w©N©ÚnpÚanyÚisnan©Ú.0ÚiÚvalss      ú\C:\Crop_Prediction\Backend\crop-ai-system\venv\Lib\site-packages\statsmodels\tsa\seasonal.pyú	<genexpr>z%_extrapolate_trend.<locals>.<genexpr>   s,   è ø€ ò Ùˆa�´·±¼¿¹À»Õ1GŒñùs   ‚0:³:r   é   c              3   óv   K  — | ]1  \  }}t        j                  t        j                  |«      «      s|–— Œ3 y ­wr   r   r   s      r   r   z%_extrapolate_trend.<locals>.<genexpr>"   s0   è ø€ ò 
á��4Ü—6‘6œ"Ÿ(™( 4›.Ô)ô ñ
ùs   ‚79Néÿÿÿÿ)Úrcond)ÚnextÚ	enumerateÚshapeÚminÚmaxr   ÚlinalgÚlstsqÚc_ÚarangeÚonesÚTÚndimÚsqueeze)	ÚtrendÚnpointsÚfrontÚbackÚ
front_lastÚ
back_firstÚkÚnÚextras	            r   Ú_extrapolate_trendr4      s÷  € ô
 ñ Ü" 5Ó)ôó €Eð 	�‰�A‰Ø
ñ	ä
ñ 
ä$ U©4¨R¨4¡[Ó1ô
ó 
ñ	
ð 	ô �U˜W‘_ dÓ+€JÜ�U˜D 7™NÓ+€Jä�9‰9�?‰?Ü
�‰Œb�i‰i˜˜zÓ*¬B¯G©G°JÀÑ4FÓ,GÐGÑHØˆe�JÐØð ó ð ñ		�D€A€qô
 �Y‰Y�q˜%Ó ¤2§5¡5¨¡8Ñ+¬b¯e©e°A©hÑ6×9Ñ9€EØ‡z�z�Q‚Ø—‘“ˆØ€Eˆ&ˆ5€Mä�9‰9�?‰?Ü
�‰Œb�i‰i˜
 DÓ)¬2¯7©7°4¸*Ñ3DÓ+EÐEÑFØˆj˜ÐØð ó ð ñ		�D€A€qô
 �Y‰Y�t˜a‘x §¡¨Q¡Ó0´2·5±5¸±8Ñ;¼b¿e¹eÀA¹hÑF×IÑI€EØ‡z�z�Q‚Ø—‘“ˆØ€Eˆ$�‰(ˆ*Ðà€Ló    c                 ó†   — t        j                  t        |«      D �cg c]  }t        | |d|…   d¬«      ‘Œ c}«      S c c}w )z¥
    Return means for each period in x. period is an int that gives the
    number of periods per cycle. E.g., 12 for monthly. NaNs are ignored
    in the mean.
    Nr   ©Úaxis)r   ÚarrayÚrangeÚ
pd_nanmean)ÚxÚperiodr   s      r   r   r   B   s6   € ô �8‰8¼uÀV»}ÖM¸!”Z  ! ) V )¡°1Ö5ÒMÓNÐNùÒMs   �>c                 óJ  — |}t        | «      }|€t        t        | dd«      dd«      }t        | dd¬«      } t        | «      }t	        j
                  t	        j                  | «      «      st        d«      ‚|j                  d«      r#t	        j                  | d	k  «      rt        d
«      ‚|€|�t        |«      }|}nt        d«      ‚| j                  d	   d|z  k  r"t        dd|z  › d| j                  d	   › d�«      ‚|€I|dz  d	k(  r(t	        j                  dgdg|dz
  z  z   dgz   «      |z  }nt	        j                  d|z  |«      }t        |«      dz   }	t        | ||	«      }
|dk(  r|dz
  }|d	kD  rt!        |
|dz   «      }
|j                  d«      r| |
z  }n| |
z
  }t#        ||«      }|j                  d«      r|t	        j$                  |d	¬«      z  }n|t	        j$                  |d	¬«      z  }t	        j&                  |j(                  ||z  dz   «      j(                  d| }|j                  d«      r	| |z  |
z  }n||z
  }g }t+        ||
|| fd«      D ]5  \  }}|j-                  |j/                  |j1                  «       |¬«      «       Œ7 t3        |d	   |d   |d   |d   ¬«      S )aÆ	  
    Seasonal decomposition using moving averages.

    Parameters
    ----------
    x : array_like
        Time series. If 2d, individual series are in columns. x must contain 2
        complete cycles.
    model : {"additive", "multiplicative"}, optional
        Type of seasonal component. Abbreviations are accepted.
    filt : array_like, optional
        The filter coefficients for filtering out the seasonal component.
        The concrete moving average method used in filtering is determined by
        two_sided.
    period : int, optional
        Period of the series (e.g., 1 for annual, 4 for quarterly, etc). Must
        be used if x is not a pandas object or if the index of x does not have
        a frequency. Overrides default periodicity of x if x is a pandas
        object with a timeseries index.
    two_sided : bool, optional
        The moving average method used in filtering.
        If True (default), a centered moving average is computed using the
        filt. If False, the filter coefficients are for past values only.
    extrapolate_trend : int or 'freq', optional
        If set to > 0, the trend resulting from the convolution is
        linear least-squares extrapolated on both ends (or the single one
        if two_sided is False) considering this many (+1) closest points.
        If set to 'freq', use `freq` closest points. Setting this parameter
        results in no NaN values in trend or resid components.

    Returns
    -------
    DecomposeResult
        A object with seasonal, trend, and resid attributes.

    See Also
    --------
    statsmodels.tsa.filters.bk_filter.bkfilter
        Baxter-King filter.
    statsmodels.tsa.filters.cf_filter.cffilter
        Christiano-Fitzgerald asymmetric, random walk filter.
    statsmodels.tsa.filters.hp_filter.hpfilter
        Hodrick-Prescott filter.
    statsmodels.tsa.filters.convolution_filter
        Linear filtering via convolution.
    statsmodels.tsa.seasonal.STL
        Season-Trend decomposition using LOESS.

    Notes
    -----
    This is a naive decomposition. More sophisticated methods should
    be preferred.

    The additive model is Y[t] = T[t] + S[t] + e[t]

    The multiplicative model is Y[t] = T[t] * S[t] * e[t]

    The results are obtained by first estimating the trend by applying
    a convolution filter to the data. The trend is then removed from the
    series and the average of this de-trended series for each period is
    the returned seasonal component.
    NÚindexÚinferred_freqr<   é   )Úmaxdimz,This function does not handle missing valuesÚmr   zJMultiplicative seasonality is not appropriate for zero and negative valueszxYou must specify a period or x must be a pandas object with a PeriodIndex or a DatetimeIndex with a freq not set to Nonez'x must have 2 complete cycles requires z observations. x only has z observation(s)g      à?r   g      ð?Úfreqr7   )Úseasonalr+   ÚresidN)Úcolumnsé   )rE   r+   rF   Úobserved)r   Úgetattrr   Úlenr   ÚallÚisfiniteÚ
ValueErrorÚ
startswithr   r	   r    r9   ÚrepeatÚintr   r4   r   ÚmeanÚtiler(   ÚzipÚappendÚwrapr*   r   )r<   ÚmodelÚfiltr=   Ú	two_sidedÚextrapolate_trendÚpfreqÚpwÚnobsÚnsidesr+   Ú	detrendedÚperiod_averagesrE   rF   ÚresultsÚsÚnames                     r   r
   r
   K   sÖ  € ðL €EÜ	�qÓ	€BØ€~Üœ  7¨DÓ1°?ÀDÓIˆä�1�c !Ô$€AÜˆq‹6€Dä�6‰6”"—+‘+˜a“.Ô!ÜÐGÓHÐHØ×Ñ˜ÔÜ�6‰6�!�q‘&Œ>Üð/óð ð
 €~ØÐÜ" 5Ó)ˆEØ‰FäðOóð ð 	‡w�wˆq�z�A˜‘IÒÜØ5°a¸%±i°[ð A(Ø()¯©°©
 |°?ðDó
ð 	
ð
 €|Ø�A‰:˜Š?Ü—8‘8˜S˜E Q C¨6°A©:Ñ$6Ñ6¸#¸Ñ>Ó?À&ÑH‰Dä—9‘9˜S 6™\¨6Ó2ˆDä�‹^˜aÑ€FÜ˜q $¨Ó/€Eà˜FÒ"Ø" Q™JÐà˜1ÒÜ" 5Ð*;¸aÑ*?Ó@ˆà×Ñ˜ÔØ˜‘I‰	à˜‘Iˆ	ä# I¨vÓ6€Oà×Ñ˜ÔØœ2Ÿ7™7 ?¸Ô;Ñ;‰àœ2Ÿ7™7 ?¸Ô;Ñ;ˆä�w‰w�×(Ñ(¨$°&©.¸1Ñ*<Ó=×?Ñ?ÀÀÐF€Hà×Ñ˜ÔØ�H‘˜uÑ$‰à˜HÑ$ˆà€GÜØ	�5˜% Ð#Ð%Ióò ;‰ˆˆ4ð 	�‰�r—w‘w˜qŸy™y›{°D�wÓ9Õ:ð;ô Ø˜‘Ø�a‰jØ�a‰jØ˜‘ô	ð r5   c                   óŠ   — e Zd ZdZdd„Zed„ «       Zed„ «       Zed„ «       Zed„ «       Z	ed„ «       Z
ed	„ «       Z	 	 	 	 	 dd
„Zy)r   aÕ  
    Results class for seasonal decompositions

    Parameters
    ----------
    observed : array_like
        The data series that has been decomposed.
    seasonal : array_like
        The seasonal component of the data series.
    trend : array_like
        The trend component of the data series.
    resid : array_like
        The residual component of the data series.
    weights : array_like, optional
        The weights used to reduce outlier influence.
    Nc                 óð   — || _         || _        |€Qt        j                  |«      }t	        |t
        j                  «      r"t        j                  ||j                  d¬«      }|| _        || _	        || _
        y )NÚweights)r?   rc   )Ú	_seasonalÚ_trendr   Ú	ones_likeÚ
isinstanceÚpdÚSeriesr?   Ú_weightsÚ_residÚ	_observed)ÚselfrI   rE   r+   rF   rf   s         r   Ú__init__zDecomposeResult.__init__ò   sa   € Ø!ˆŒØˆŒØˆ?Ü—l‘l 8Ó,ˆGÜ˜(¤B§I¡IÔ.ÜŸ)™)Ø 8§>¡>¸	ô�ð  ˆŒØˆŒØ!ˆ�r5   c                 ó   — | j                   S )zObserved data)ro   ©rp   s    r   rI   zDecomposeResult.observedÿ   ó   € ð �~‰~Ðr5   c                 ó   — | j                   S )z The estimated seasonal component)rg   rs   s    r   rE   zDecomposeResult.seasonal  rt   r5   c                 ó   — | j                   S )zThe estimated trend component)rh   rs   s    r   r+   zDecomposeResult.trend	  ó   € ð �{‰{Ðr5   c                 ó   — | j                   S )zThe estimated residuals)rn   rs   s    r   rF   zDecomposeResult.resid  rw   r5   c                 ó   — | j                   S )z)The weights used in the robust estimation)rm   rs   s    r   rf   zDecomposeResult.weights  s   € ð �}‰}Ðr5   c                 ó.   — | j                   j                  S )zNumber of observations)ro   r    rs   s    r   r]   zDecomposeResult.nobs  s   € ð �~‰~×#Ñ#Ð#r5   c                 óÌ  — ddl m} ddlm}  |«       } |«        |r| j                  dfgng }	|	|r| j
                  dfgng z  }	| j                  j                  dk(  r|	|r| j                  dfgng z  }	n¶| j                  j                  dkD  r�t        | j                  t        j                  «      r5| j                  j                  D ]  }
|	|r| j                  |
   dfgng z  }	Œ nDt        | j                  j                  d   «      D ]  }|	|r| j                  dd…|f   dfgng z  }	Œ! |	|r| j                  d	fgng z  }	|	|r| j                  d
fgng z  }	t        | j                  t        j                  t        j                   f«      rO| j                  j                  d   }| j                  j"                  d   | j                  j"                  |dz
     f}nd| j                  j                  d   dz
  f}|j%                  t'        |	«      dd¬«      \  }}t)        t+        ||	«      «      D ]¥  \  }\  }\  }	}|d	k7  r|j-                  |	«       n)|j-                  |	dd¬«       |j-                  |ddd¬«       t/        |	d|«      }|dk7  r|j1                  «       }|dk(  r|r|j2                  n|j4                  } ||«       |j7                  |«       Œ§ |j9                  «        |S )a@  
        Plot estimated components

        Parameters
        ----------
        observed : bool
            Include the observed series in the plot
        seasonal : bool
            Include the seasonal component in the plot
        trend : bool
            Include the trend component in the plot
        resid : bool
            Include the residual in the plot
        weights : bool
            Include the weights in the plot (if any)

        Returns
        -------
        matplotlib.figure.Figure
            The figure instance that containing the plot.
        r   )Úregister_matplotlib_converters)Ú_import_mplÚObservedr+   r   rE   NÚresidualrf   T)ÚsharexÚoÚnone)ÚmarkerÚ	linestyle)r   r   z#000000éýÿÿÿ)ÚcolorÚzorderrc   )Úpandas.plottingr|   Ústatsmodels.graphics.utilsr}   ro   r+   rE   r)   rj   rk   Ú	DataFramerG   r:   r    rF   rf   rl   r?   ÚsubplotsrK   r   rT   ÚplotrJ   Ú
capitalizeÚ	set_titleÚ
set_ylabelÚset_xlimÚtight_layout)rp   rI   rE   r+   rF   rf   r|   r}   ÚpltÚseriesÚcolr   r]   ÚxlimÚfigÚaxsÚaxÚdef_namerc   Útitles                       r   rŒ   zDecomposeResult.plot  sª  € õ: 	Cå:á‹mˆÙ&Ô(Ù3;�4—>‘> :Ð.Ñ/ÀˆØ©U�D—J‘J Ð(Ñ)¸Ñ:ˆà�=‰=×Ñ Ò"Ø±x˜Ÿ™ zÐ2Ñ3ÀRÑG‰FØ�]‰]×Ñ !Ò#Ü˜$Ÿ-™-¬¯©Ô6ØŸ=™=×0Ñ0ò �CØÙ>F˜$Ÿ-™-¨Ñ,¨jÐ9Ñ:ÈBñ‘Fñô
 ˜tŸ}™}×2Ñ2°1Ñ5Ó6ò �AØÙ?G˜$Ÿ-™-ª¨1¨Ñ-¨zÐ:Ñ;ÈRñ‘Fðð
 	±�D—J‘J 
Ð+Ñ,¸2Ñ=ˆØ±�D—L‘L )Ð,Ñ-¸bÑ@ˆä�d—n‘n¤r§|¡|´R·Y±YÐ&?Ô@Ø—>‘>×'Ñ'¨Ñ*ˆDØ—>‘>×'Ñ'¨Ñ*¨D¯N©N×,@Ñ,@ÀÈÁÑ,JÐJ‰Dà�t—~‘~×+Ñ+¨AÑ.°Ñ2Ð3ˆDà—<‘<¤ F£¨Q°t�<Ó<‰ˆˆSÜ+4´S¸¸fÓ5EÓ+Fò 	Ñ'ˆAÑ'�Ñ&�V˜XØ˜:Ò%Ø—‘˜•à—‘˜ s°f�Ô=Ø—‘˜˜f¨I¸b�ÔAÜ˜6 6¨8Ó4ˆDØ˜:Ò%Ø—‘Ó(�Ø$%¨¢F©x�B—L’L¸R¿]¹]ˆEÙ�$ŒKØ�K‰K˜Õð	ð 	×ÑÔØˆ
r5   r   )TTTTF)Ú__name__Ú
__module__Ú__qualname__Ú__doc__rq   ÚpropertyrI   rE   r+   rF   rf   r]   rŒ   © r5   r   r   r   à   s›   „ ñó""ð ñó ðð ñó ðð ñó ðð ñó ðð ñó ðð ñ$ó ð$ð ØØØØôLr5   r   )ÚadditiveNNTr   )rž   Únumpyr   Úpandasrk   Úpandas.core.nanopsr   r;   Ústatsmodels.tools.validationr   r   Ústatsmodels.tsa.stl._stlr   Ú#statsmodels.tsa.filters.filtertoolsr   Ústatsmodels.tsa.stl.mstlr   Ústatsmodels.tsa.tsatoolsr	   Ú__all__r4   r   r
   r   r    r5   r   ú<module>r«      s[   ðñó Û Ý 4ç BÝ (Ý BÝ )Ý 3ò€ò(òVOð Ø	ØØØóR÷jIò Ir5   