
    'YHhV,                         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      Q/var/www/html/planif/env/lib/python3.12/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66"((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
	
 
$U4R4[1
 
	
 	 UW_d+JUD7N+J99??
biiz*BGGJ4F,GGHeJ   		DAq
 YYq% 2558+beeAh699EzzQE&5M99??
bii
D)2774*3D+EEFj   		DAq
 YYtaxQ02558;beeAhFIIEzzQ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     88uV}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~7D1?DI1c!$Aq6D66"++a.!GHH66!q&>/ 
 ~"5)EFO  	wwqzAI5a%i[ A(()
|?D
 	

 |A:?88SEQC6A:$66#>?&HD99S6\62D^aFq$/EF""QJ1"5*;a*?@I	I	#Iv6O277?;;277?;;ww(($&.1*<=??FHHu$H$G	5%#%I ;4 	rwwqyy{Dw9:; ajaj	 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    !?ll8,G(BII.))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  rt        | 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>>:./UDJJ():=="xz23RGF]]!#$--6==00 C>F$--,j9:BF
 t}}22156 A?G$--1-z:;RF
 	DJJ
+,2=DLL),-b@dnnr||RYY&?@>>''*D>>''*DNN,@,@,JJDt~~++A.23D<<FQt<<S+4Sf5E+F 	'A'&VX:%sf=fIbA6684D:%($%FxBLLR]]E$KKK	 	
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   