
    %gA2                    ,   d dl mZmZ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mZm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mZmZmZ d d
lm Z m!Z!  ejD                  d      Z#e#jI                  ejJ                         dZ& G d de'      Z(y)    )absolute_importdivisionprint_functionN)OrderedDictdefaultdict)deepcopy)	timedelta)DictListUnion)NDArray)get_holiday_namesmake_holidays_df)StanBackendEnumModelInputDataModelParamsTrendIndicator)plotplot_componentspropheti ʚ;c                      e Zd ZdZ	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 	 dIdefdZd Zd Z	 	 dJdZdKdZ	d	 Z
d
 Zedej                  deeef   dedeej(                     fd       Zed        Zd Zd Z	 	 dLdZ	 	 dMdZd Zd Zd Zd Zd Z d Z!ed        Z"ed        Z#ed        Z$dejJ                  de&fdZ'd ede(fd!Z)d" Z*dNdejJ                  d#e+dejJ                  fd$Z,ed%        Z-ed&        Z.ed'        Z/d( Z0d) Z1dejJ                  d#e+dejJ                  fd*Z2dejJ                  d#e+de3eejh                  f   fd+Z5de3eejh                  f   fd,Z6dejJ                  d-ejJ                  d.ed/ejh                  d0ejh                  d1ede7e3eejh                  f      fd2Z8d3 Z9dOdejJ                  d1ed.edejh                  fd4Z:dOdejJ                  d1ed.edejh                  fd5Z;ed6ed7ed8ed1edejh                  f
d9       Z<edPd:       Z=	 dQd;ejh                  d<ejh                  d=ed>ed?ejh                  d@ejh                  dAedBedejh                  fdCZ>dRdejJ                  d#e+fdDZ?dE Z@dSdFZA	 	 dTdGZB	 	 dUdHZCy)VPropheta  Prophet forecaster.

    Parameters
    ----------
    growth: String 'linear', 'logistic' or 'flat' to specify a linear, logistic or
        flat trend.
    changepoints: List of dates at which to include potential changepoints. If
        not specified, potential changepoints are selected automatically.
    n_changepoints: Number of potential changepoints to include. Not used
        if input `changepoints` is supplied. If `changepoints` is not supplied,
        then n_changepoints potential changepoints are selected uniformly from
        the first `changepoint_range` proportion of the history.
    changepoint_range: Proportion of history in which trend changepoints will
        be estimated. Defaults to 0.8 for the first 80%. Not used if
        `changepoints` is specified.
    yearly_seasonality: Fit yearly seasonality.
        Can be 'auto', True, False, or a number of Fourier terms to generate.
    weekly_seasonality: Fit weekly seasonality.
        Can be 'auto', True, False, or a number of Fourier terms to generate.
    daily_seasonality: Fit daily seasonality.
        Can be 'auto', True, False, or a number of Fourier terms to generate.
    holidays: pd.DataFrame with columns holiday (string) and ds (date type)
        and optionally columns lower_window and upper_window which specify a
        range of days around the date to be included as holidays.
        lower_window=-2 will include 2 days prior to the date as holidays. Also
        optionally can have a column prior_scale specifying the prior scale for
        that holiday.
    seasonality_mode: 'additive' (default) or 'multiplicative'.
    seasonality_prior_scale: Parameter modulating the strength of the
        seasonality model. Larger values allow the model to fit larger seasonal
        fluctuations, smaller values dampen the seasonality. Can be specified
        for individual seasonalities using add_seasonality.
    holidays_prior_scale: Parameter modulating the strength of the holiday
        components model, unless overridden in the holidays input.
    changepoint_prior_scale: Parameter modulating the flexibility of the
        automatic changepoint selection. Large values will allow many
        changepoints, small values will allow few changepoints.
    mcmc_samples: Integer, if greater than 0, will do full Bayesian inference
        with the specified number of MCMC samples. If 0, will do MAP
        estimation.
    interval_width: Float, width of the uncertainty intervals provided
        for the forecast. If mcmc_samples=0, this will be only the uncertainty
        in the trend using the MAP estimate of the extrapolated generative
        model. If mcmc.samples>0, this will be integrated over all model
        parameters, which will include uncertainty in seasonality.
    uncertainty_samples: Number of simulated draws used to estimate
        uncertainty intervals. Settings this value to 0 or False will disable
        uncertainty estimation and speed up the calculation.
    stan_backend: str as defined in StanBackendEnum default: None - will try to
        iterate over all available backends and find the working one
    holidays_mode: 'additive' or 'multiplicative'. Defaults to seasonality_mode.
    Nscalingc                    || _         || _        | j                  [t        j                  t        j                  | j                        d      | _        t        | j                        | _        d| _        n|| _        d| _        || _        || _	        || _
        || _        || _        |	| _        || _        || j                  | _        t        |
      | _        t        |      | _        t        |      | _        || _        || _        || _        |dvrt-        d      || _        d | _        d | _        d | _        d| _        d | _        d | _        t=        i       | _        t=        i       | _         d | _!        d | _"        i | _#        d | _$        d | _%        d | _&        d | _'        d | _(        i | _)        | jU                          | jW                  |       y )NdsnameTF)absmaxminmaxz+scaling must be one of 'absmax' or 'minmax'),growthchangepointspdSeriesto_datetimelenn_changepointsspecified_changepointschangepoint_rangeyearly_seasonalityweekly_seasonalitydaily_seasonalityholidaysseasonality_modeholidays_modefloatseasonality_prior_scalechangepoint_prior_scaleholidays_prior_scalemcmc_samplesinterval_widthuncertainty_samples
ValueErrorr   starty_miny_scalelogistic_floort_scalechangepoints_tr   seasonalitiesextra_regressorscountry_holidaysstan_fitparamshistoryhistory_datestrain_component_colscomponent_modestrain_holiday_names
fit_kwargsvalidate_inputs_load_stan_backend)selfr    r!   r&   r(   r)   r*   r+   r,   r-   r0   r2   r1   r3   r4   r5   stan_backendr   r.   s                      O/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/prophet/forecaster.py__init__zProphet.__init__R   s   * (( "		"..9J9J*KRV WD"%d&7&7"8D*.D'"0D*/D'!2"4"4!2  0* !%!6!6D',-D'E$',-D'E$$)*>$?!(,#6 ..JKK 

#"(_ +B $!$(!##' -    c                    |It         D ]?  }	 t        j                  d|j                         | j	                  |j                        c S  n t        j                  |             | _        t        j                  d| j                  j                                y # t
        $ r+}t        j                  d|j                  |       Y d }~d }~ww xY w)NzTrying to load backend: %sz3Unable to load backend %s (%s), trying the next onezLoaded stan backend: %s)	r   loggerdebugr   rI   	Exceptionget_backend_classrK   get_type)rJ   rK   ies       rL   rI   zProphet._load_stan_backend   s    $ ccLL!=qvvF22166::c !P A A, O QD.0A0A0J0J0LM ! cLL!VXYX^X^`abbcs   :B	C#!C		Cc                    | j                   dvrt        d      t        | j                  t        t
        f      st        d      | j                  dk  s| j                  dkD  rt        d      | j                  t        | j                  t        j                        rd| j                  v rd	| j                  v st        d
      t        j                  | j                  d         | j                  d<   | j                  d   j                         j                         s+| j                  d	   j                         j                         rt        d      d| j                  v }d| j                  v }||z   dk(  rt        d      |rV| j                  d   j                         dkD  rt        d      | j                  d   j                         dk  rt        d      | j                  d	   j                         D ]  }| j                  |d        | j                   dvrt        d      | j"                  dvrt        d      y)z Validates the inputs to Prophet.)linearlogisticflatz<Parameter "growth" should be "linear", "logistic" or "flat".z-changepoint_range must be a number in [0, 1]'r      z/Parameter "changepoint_range" must be in [0, 1]Nr   holidayz=holidays must be a DataFrame with "ds" and "holiday" columns.z"Found a NaN in holidays dataframe.lower_windowupper_windowzAHolidays must have both lower_window and upper_window, or neitherz#Holiday lower_window should be <= 0z#Holiday upper_window should be >= 0Fcheck_holidaysadditivemultiplicativez7seasonality_mode must be "additive" or "multiplicative"z4holidays_mode must be "additive" or "multiplicative")r    r6   
isinstancer(   intr/   r,   r"   	DataFramer$   isnullanymaxminuniquevalidate_column_namer-   r.   )rJ   	has_lower	has_upperhs       rL   rH   zProphet.validate_inputs   s   ;;<<NP P$003,?LMM##a'T-C-Ca-GNOO==$4==",,7DMM).  "6 7 7"$..t1D"EDMM$d#**,002==+22488: !EFF&$--7I&$--7I9$)  "< = ===0446:$%JKK==0446:$%JKK]]9-446 C))!E)BC  (FFI  %CCF  DrN   c                    d|v rt        d      g d}|D cg c]  }|dz   	 }}|D cg c]  }|dz   	 }}|j                  |       |j                  |       |j                  g d       ||v rt        dj                  |            |rF| j                  :|| j                  d
   j	                         v rt        dj                  |            |rI| j
                  =|t        | j
                        v r&t        dj                  || j
                              |r)|| j                  v rt        dj                  |            |r*|| j                  v rt        dj                  |            y	y	c c}w c c}w )aY  Validates the name of a seasonality, holiday, or regressor.

        Parameters
        ----------
        name: string
        check_holidays: bool check if name already used for holiday
        check_seasonalities: bool check if name already used for seasonality
        check_regressors: bool check if name already used for regressor
        _delim_zName cannot contain "_delim_")trendadditive_termsdailyweeklyyearlyr,   zerosextra_regressors_additiveyhatextra_regressors_multiplicativemultiplicative_terms_lower_upper)r   ycapfloory_scaled
cap_scaledzName {name!r} is reserved.r   Nr\   z)Name {name!r} already used for a holiday.z6Name {name!r} is a holiday name in {country_holidays}.)r   r?   z-Name {name!r} already used for a seasonality.z2Name {name!r} already used for an added regressor.)	r6   extendformatr,   rk   r?   r   r=   r>   )	rJ   r   r`   check_seasonalitiescheck_regressorsreserved_namesnrn_lrn_us	            rL   rl   zProphet.validate_column_name   s    <==

 '55H55&45H55d#d# A 	B>!,333>  t}}8i07799;BBBM  t44@)$*?*?@@HTD4I4IJ  44+=+=#=?T"  (=(= =DT"  !>5 65s
   E7E<c                 R   d|v rVt        j                  |d         |d<   t        j                  |d   j                        j                         rt        d      |d   j                  t        j                  k(  r|d   j                  t              |d<   t        j                  |d         |d<   |d   j                  j                  t        d      |d   j                         j                         rt        d      | j                  D ]x  }||vrt        dj!                  |            t        j                  ||         ||<   ||   j                         j                         s_t        d	j!                  |             | j"                  j	                         D ]  }|d
   }|||vrt        dj!                  |            ||   j%                  ddg      j'                         st        dj!                  |            ||   j                  d      ||<    |j(                  j*                  dk(  rd|j(                  _        |j-                  dd      }|j/                  d      }| j1                  ||       | j2                  rd|vr>t        d      | j4                  dk(  rd|d<   n| j4                  dk(  r| j6                  |d<   | j8                  dk(  rNd|vrt        d      |d   |d   k  j                         rt        d      |d   |d   z
  | j:                  z  |d<   |d   | j<                  z
  | j>                  z  |d<   d|v r|d   |d   z
  | j:                  z  |d<   | j                  jA                         D ]  \  }}||   |d    z
  |d!   z  ||<    |S )"aF  Prepare dataframe for fitting or predicting.

        Adds a time index and scales y. Creates auxiliary columns 't', 't_ix',
        'y_scaled', and 'cap_scaled'. These columns are used during both
        fitting and predicting.

        Parameters
        ----------
        df: pd.DataFrame with columns ds, y, and cap if logistic growth. Any
            specified additional regressors must also be present.
        initialize_scales: Boolean set scaling factors in self from df.

        Returns
        -------
        pd.DataFrame prepared for fitting or predicting.
        r~   zFound infinity in column y.r   NzJColumn ds has timezone specified, which is not supported. Remove timezone.zFound NaN in column ds.z)Regressor {name!r} missing from dataframer   zFound NaN in column {name!r}condition_namez3Condition {condition_name!r} missing from dataframe)r   TFz.Found non-boolean in column {condition_name!r}bool	mergesort)kind)dropr   zExpected column "floor".r           r   rY   r   z?Capacities must be supplied for logistic growth in column "cap"z5cap must be greater than floor (which defaults to 0).r   tr   mustd)!r"   
to_numericnpisinfvaluesrh   r6   dtypeint64astypestrr$   dttzrg   r>   r   r=   isinallindexr   sort_valuesreset_indexinitialize_scalesr:   r   r8   r    r9   r7   r;   items)rJ   dfr   r   propsr   s         rL   setup_dataframezProphet.setup_dataframe  s   " "9mmBsG,BsGxx3'++- !>??d8>>RXX%$xs+BtH>>"T(+4d8;;>>%#  d8??  "677)) 
	D2~ ?VV&  }}RX.BtH$x $$& 299t9D 
	 ''..0 	GE"#34N)!+$M~>  .)..e}=AAC$H~>  &(%7%>%>v%F>"	G 88==D  BHHM^^D{^3^^^&0"5b  !;<<||x' 7)"jj7;;*$B #  5	R[(--/ K  !#5	BwK 74<<GB|d8djj(DLL83"9 g73t||CBzN00668 	AKD%DE$K/5<?BtH	A	rN   c                 b   |sy| j                   dk(  rd|v rd| _        | j                  dk(  rkt        |d   |d   z
  j	                         j                               | _        t        |d   |d   z
  j	                         j                               | _        n| j                  dk(  r|d   j                         | _        t        |d   j                         | j                  z
        | _        n| j                  dk(  r7d	| _        t        |d   j	                         j                               | _        nU| j                  dk(  rF|d   j                         | _        t        |d   j                         | j                  z
        | _        | j                  d
k(  rd| _        |d   j                         | _	        |d   j                         | j                  z
  | _
        | j                  j                         D ]  \  }}|d   }t        ||   j                               }|dk  rd}|dk(  r&t        ||   j                               dd
hk(  rd}nd}|s\t        ||   j!                               }t        ||   j#                               }|| j                  |   d<   || j                  |   d<    y)zInitialize model scales.

        Sets model scaling factors using df.

        Parameters
        ----------
        initialize_scales: Boolean set the scales or not.
        df: pd.DataFrame for setting scales.
        NrY   r   Tr   r~   r   r   r   r         ?r   standardize   Fautor[   r   r   )r    r:   r   r/   absrj   r8   ri   r9   r7   r;   r>   r   r%   rk   setmeanr   )	rJ   r   r   r   r   r   n_valsr   r   s	            rL   r   zProphet.initialize_scalesd  s?    !;;*$B"&D||x'"BsGbk$9#>#>#@#D#D#FG
$bg7&;%@%@%B%F%F%HI)[__.
$RY]]_tzz%AB||x'
$bg]]_%8%8%:;)W[[]
 %bgkkmdjj&@ A<<1DLX\\^
$x||~

200668 	9KD%.KD*+Fz#f$r$x()aV3"'K"&K2d8==?+BtHLLN+46%%d+D158%%d+E2	9rN   c                    | j                   t        | j                         dk(  rnt        | j                         | j                  d   j                         k  }t	        | j                         | j                  d   j	                         kD  }|s|rOt        d      t        t        j                  | j                  j                  d   | j                  z              }| j                  dz   |kD  r9|dz
  | _        t        j                  dj                  | j                               | j                  dkD  ryt        j                  d|dz
  | j                  dz         j!                         j#                  t              }| j                  j$                  |   d   j'                  d      | _         n/t)        j*                  t)        j,                  g       d	      | _         t        | j                         dkD  rRt        j.                  t        j0                  | j                   | j2                  z
  | j4                  z              | _        yt        j0                  dg      | _        y)
aL  Set changepoints

        Sets m$changepoints to the dates of changepoints. Either:
        1) The changepoints were passed in explicitly.
            A) They are empty.
            B) They are not empty, and need validation.
        2) We are generating a grid of them.
        3) The user prefers no changepoints be used.
        Nr   r   z,Changepoints must fall within training data.r[   zKn_changepoints greater than number of observations. Using {n_changepoints}.)r&   r   )r!   r%   rj   rB   ri   r6   re   r   r   shaper(   r&   rP   infor   linspaceroundr   iloctailr"   r#   r$   sortarrayr7   r;   r<   )rJ   too_lowtoo_high	hist_size
cp_indexess        rL   set_changepointszProphet.set_changepoints  s    (4$$%*d//04<<3E3I3I3KKt001DLL4F4J4J4LLh$FH H
 BHHT\\%7%7%:'+'='=&> ? @I""Q&2&/!m#.V4+>+>V?
 ""Q&KK9q=$2E2E2IJ  LL%%j1$7<<R@ !
 %'IIbnnR.@t$L!t  !A%"$''"((""TZZ/4<<?+A #BD #%((A3-DrN   datesperiodseries_orderreturnc                    |dk\  st        d      | j                  t        j                        t        z  dz  }|t        j
                  z  dz  }t        j                  | j                  d   d|z  f      }t        |      D ]N  }||dz   z  |z  }t        j                  |      |ddd|z  f<   t        j                  |      |ddd|z  dz   f<   P |S )aW  Provides Fourier series components with the specified frequency
        and order.

        Parameters
        ----------
        dates: pd.Series containing timestamps.
        period: Number of days of the period.
        series_order: Number of components.

        Returns
        -------
        Matrix with seasonality features.
        r[   zseries_order must be >= 1)r   g     @r   r   N)r6   to_numpyr   r   NANOSECONDS_TO_SECONDSpiemptyr   rangesincos)r   r   r   r   x_Tfourier_componentsrU   cs           rL   fourier_serieszProphet.fourier_series  s    & !899 NNN*.DD
S"%%i!mXXu{{1~q<7G&HI|$ 	;Aq1u&A+-66!9q!a%x(13q1q5A+~.	; "!rN   c                     | j                  |||      }t        |j                  d         D cg c]  }dj                  ||dz          }}t	        j
                  ||      S c c}w )ap  Data frame with seasonality features.

        Parameters
        ----------
        cls: Prophet class.
        dates: pd.Series containing timestamps.
        period: Number of days of the period.
        series_order: Number of components.
        prefix: Column name prefix.

        Returns
        -------
        pd.DataFrame with seasonality features.
        r[   z{}_delim_{})columns)r   r   r   r   r"   rf   )clsr   r   r   prefixfeaturesrU   r   s           rL   make_seasonality_featuresz!Prophet.make_seasonality_features  sn      %%eV\B 8>>!,-
   Q/
 
 ||Hg66	
s   A#c           	      8   t        j                         }| j                  | j                  j                         }| j                  ft        |D ch c]  }|j                   c}      }t        || j                        }t        j                  ||fd      }|j                  dd       | j                  |j                  t        j                  |j                  j                  | j                                 }|j!                  |      }t        j                  d| j                  t        j                  | j                  j                  |j                                 i      }t        j                  ||fd      }|j                  dd       |S c c}w )a  Construct a dataframe of holiday dates.

        Will combine self.holidays with the built-in country holidays
        corresponding to input dates, if self.country_holidays is set.

        Parameters
        ----------
        dates: pd.Series containing timestamps used for computing seasonality.

        Returns
        -------
        dataframe of holiday dates, in holiday dataframe format used in
        initialization.
        )	year_listcountryF)r   T)r   inplacer\   )r"   rf   r,   copyr?   listyearr   concatr   rF   r   r   logical_notr\   r   r   )rJ   r   all_holidaysxr   country_holidays_dfindex_to_dropholidays_to_adds           rL   construct_holiday_dataframez#Prophet.construct_holiday_dataframe  sh    ||~==$==--/L  ,e4aff45I"2#T-B-B# 99l4G%H*/1L$$$$=##/(.. ((--d.F.FGM
 (,,];L ll433NN4#;#;(,\-A-A(BD, O 99lO%D*/1L$$$$=5 5s   Fc           	      H   t        fd      }i }t        j                  j                  j                        }|j                         D ]}  }|j                  j	                         }	 t        t        |dd            }t        t        |dd            }	t        t        |d| j                              }
t        j                  |
      rt        | j                        }
|j                  |v r7||j                     |
k7  r%t        dj                  |j                              |
dk  rt        d      |
||j                  <   t!        ||	d	z         D ]s  }t        j"                  |t%        |
      z         }	 |j'                  |      }dj                  |j                  |dk\  rdndt+        |            }|	d||   |<   o||    u  t        j,                  |      }|t/        |j0                  j3                                  }|j0                  D cg c]  }||j5                  d      d       }}t7        |j9                               }| j:                  t        j<                  |      | _        |||fS # t        $ r d}d}	Y w xY w# t(        $ r d}Y w xY wc c}w )a  Construct a dataframe of holiday features.

        Parameters
        ----------
        dates: pd.Series containing timestamps used for computing seasonality.
        holidays: pd.Dataframe containing holidays, as returned by
            construct_holiday_dataframe.

        Returns
        -------
        holiday_features: pd.DataFrame with a column for each holiday.
        prior_scale_list: List of prior scales for each holiday column.
        holiday_names: List of names of holidays
        c                  H    t        j                   j                  d         S )Nr   )r   rw   r   )r   s   rL   <lambda>z/Prophet.make_holiday_features.<locals>.<lambda>=  s    Q0H rN   r]   r   r^   prior_scalezGHoliday {holiday!r} does not have consistent prior scale specification.)r\   Prior scale must be > 0r[   daysNz{}_delim_{}{}+-r   rq   )r   r"   DatetimeIndexr   date
itertuplesr   re   getattrr6   r/   r2   r   isnanr\   r   r   r$   r	   get_locKeyErrorr   rf   sortedr   tolistsplitr   keysrF   r#   )rJ   r   r,   expanded_holidaysprior_scales	row_indexrowr   lwuwpsoffset
occurrencelockeyholiday_featuresro   prior_scale_listholiday_namess    `                 rL   make_holiday_featureszProphet.make_holiday_features-  s     ((HI $$UXX]]3	&&( "	+CBna89na89 wsM43L3LMNBxx|4445{{l*|CKK/HB/N ++16#++6+F  Qw !:;;(*L%BF+ +^^B1G,GH
#++J7C &,,KK!Q;CCK
 ?24%c*3/%c*+)"	+F <<(9:+F3C3K3KDJFH-N O &--
 +A./
 
 \..01##+')yy'?D$!1=@@U  &   C
s*   *,I99JJ9J
	J
JJc                    | j                   t        d      | j                  |d       |t        | j                        }|| j
                  }|dk  rt        d      |dvrt        d      ||dd	|d
| j                  |<   | S )a[  Add an additional regressor to be used for fitting and predicting.

        The dataframe passed to `fit` and `predict` will have a column with the
        specified name to be used as a regressor. When standardize='auto', the
        regressor will be standardized unless it is binary. The regression
        coefficient is given a prior with the specified scale parameter.
        Decreasing the prior scale will add additional regularization. If no
        prior scale is provided, self.holidays_prior_scale will be used.
        Mode can be specified as either 'additive' or 'multiplicative'. If not
        specified, self.seasonality_mode will be used. 'additive' means the
        effect of the regressor will be added to the trend, 'multiplicative'
        means it will multiply the trend.

        Parameters
        ----------
        name: string name of the regressor.
        prior_scale: optional float scale for the normal prior. If not
            provided, self.holidays_prior_scale will be used.
        standardize: optional, specify whether this regressor will be
            standardized prior to fitting. Can be 'auto' (standardize if not
            binary), True, or False.
        mode: optional, 'additive' or 'multiplicative'. Defaults to
            self.seasonality_mode.

        Returns
        -------
        The prophet object.
        z0Regressors must be added prior to model fitting.F)r   r   r   ra   z+mode must be 'additive' or 'multiplicative'r   r   )r   r   r   r   mode)rB   rR   rl   r/   r2   r-   r6   r>   )rJ   r   r   r   r
  s        rL   add_regressorzProphet.add_regressort  s    < <<#BD D!!$!? 9 9:K<((D!67755JKK&&'
d# rN   c                 `   | j                   t        d      |dvr| j                  |d       || j                  }nt	        |      }|dk  rt        d      |dk  rt        d      || j                  }|dvrt        d	      || j                  |       |||||d
| j                  |<   | S )a  Add a seasonal component with specified period, number of Fourier
        components, and prior scale.

        Increasing the number of Fourier components allows the seasonality to
        change more quickly (at risk of overfitting). Default values for yearly
        and weekly seasonalities are 10 and 3 respectively.

        Increasing prior scale will allow this seasonality component more
        flexibility, decreasing will dampen it. If not provided, will use the
        seasonality_prior_scale provided on Prophet initialization (defaults
        to 10).

        Mode can be specified as either 'additive' or 'multiplicative'. If not
        specified, self.seasonality_mode will be used (defaults to additive).
        Additive means the seasonality will be added to the trend,
        multiplicative means it will multiply the trend.

        If condition_name is provided, the dataframe passed to `fit` and
        `predict` should have a column with the specified condition_name
        containing booleans which decides when to apply seasonality.

        Parameters
        ----------
        name: string name of the seasonality component.
        period: float number of days in one period.
        fourier_order: int number of Fourier components to use.
        prior_scale: optional float prior scale for this component.
        mode: optional 'additive' or 'multiplicative'
        condition_name: string name of the seasonality condition.

        Returns
        -------
        The prophet object.
        z1Seasonality must be added prior to model fitting.)rt   ru   rv   F)r   r   r   zFourier Order must be > 0ra   z+mode must be "additive" or "multiplicative"r   fourier_orderr   r
  r   )rB   rR   rl   r0   r/   r6   r-   r=   )rJ   r   r   r  r   r
  r   r   s           rL   add_seasonalityzProphet.add_seasonality  s    H <<#CE E44%%d%F--B{#B7677A899<((D55JKK%%%n5*,$
4  rN   c                     | j                   t        d      t        |      D ]  }| j                  |d        | j                  0t
        j                  dj                  | j                  |             || _        | S )aP  Add in built-in holidays for the specified country.

        These holidays will be included in addition to any specified on model
        initialization.

        Holidays will be calculated for arbitrary date ranges in the history
        and future. See the online documentation for the list of countries with
        built-in holidays.

        Built-in country holidays can only be set for a single country.

        Parameters
        ----------
        country_name: Name of the country, like 'UnitedStates' or 'US'

        Returns
        -------
        The prophet object.
        z6Country holidays must be added prior to model fitting.Fr_   zHChanging country holidays from {country_holidays!r} to {country_name!r}.)r?   country_name)rB   rR   r   rl   r?   rP   warningr   )rJ   r  r   s      rL   add_country_holidayszProphet.add_country_holidays  s    ( <<#H  &l3 	BD%%d5%A	B   ,NN$%)%:%:!-   !-rN   c           	      Z   g }g }g g d}| j                   j                         D ]  \  }}| j                  |d   |d   |d   |      }|d   d|||d       <   |j                  |       |j	                  |d   g|j
                  d   z         ||d	      j                  |        | j                  |d         }t        |      dkD  rY| j                  |d   |      \  }}	}
|j                  |       |j	                  |	       || j                     j	                  |
       | j                  j                         D ]W  \  }}|j                  t        j                  ||                |j                  |d          ||d	      j                  |       Y t        |      dk(  rW|j                  t        j                  d
t        j                  |j
                  d         i             |j                  d       t        j                  |d      }| j!                  ||      \  }}||||fS )a  Dataframe with seasonality features.

        Includes seasonality features, holiday features, and added regressors.

        Parameters
        ----------
        df: pd.DataFrame with dates for computing seasonality features and any
            added regressors.

        Returns
        -------
        pd.DataFrame with regression features.
        list of prior scales for each column of the features dataframe.
        Dataframe with indicators for which regression components correspond to
            which columns.
        Dictionary with keys 'additive' and 'multiplicative' listing the
            component names for each mode of seasonality.
        ra   r   r   r  r   r   r   r[   r
  rw   r   axis)r=   r   r   appendr   r   r   r%   r  r.   r>   r"   rf   r   rw   r   regressor_column_matrix)rJ   r   seasonal_featuresr   modesr   r   r   r,   holiday_priorsr  component_colss               rL   make_all_seasonality_featuresz%Prophet.make_all_seasonality_features  sE   & 26  --335 	.KD%554ho&	H %&29:"U#34556$$X.}%&)::<%- ''-	. 33BtH=x=1**2d8X> 4Hnm $$X./$$$%,,];  00668 	.KD%$$R\\"T(%;<m 45%- ''-	.  !Q&$$grxx'<=>@#II&7a@ $ < <u!
 !,EErN   c           	      <   t        j                  t        j                  |j                  d         |j
                  D cg c]  }|j                  d      d    c}d      }| j                  +| j                  |d| j                  j                               }dD ]  }| j                  ||dz   ||         }| j                  j                         D cg c]  \  }}|d   |k(  r| }}}| j                  |d	|z   |      }||   j                  |dz          ||   j                  d	|z           || j                     j                  d       t        j                  |d
   |d         j                  d
      }	dD ]  }
|
|	vsd|	|
<    |	j!                  dddd       t#        |	d   |	d   z         dkD  rt%        d      | j&                  ?|	| j&                  j
                     }	|	j)                  | j&                        st%        d      |	|fS c c}w c c}}w )a#  Dataframe indicating which columns of the feature matrix correspond
        to which seasonality/regressor components.

        Includes combination components, like 'additive_terms'. These
        combination components will be added to the 'modes' input.

        Parameters
        ----------
        seasonal_features: Constructed seasonal features dataframe
        modes: Dictionary with keys 'additive' and 'multiplicative' listing the
            component names for each mode of seasonality.

        Returns
        -------
        component_cols: A binary indicator dataframe with columns seasonal
            components and rows columns in seasonal_features. Entry is 1 if
            that columns is used in that component.
        modes: Updated input with combination components.
        r[   rq   r   col	componentr,   ra   _termsr
  extra_regressors_r   r!  )level)rs   r{   rw   Tignore)r  r   errorsrs   r{   z&A bug occurred in seasonal components.z*A bug occurred in constructing regressors.)r"   rf   r   aranger   r   r   rF   add_group_componentrk   r>   r   r  r.   crosstab
sort_indexr   ri   rR   rD   equals)rJ   r  r  r   
componentsr
  rr   regressors_by_moder  r   s              rL   r  zProphet.regressor_column_matrixS  sX   ( \\99.44Q78/@/H/H*+	"1%#
 
 ##/11J(@(@(G(G(IKJ 3 	;D11D8OU4[J #'"7"7"="="?"a=D( " " 11/$68JLJ $Kth/$K2T9:	; 	d  !((4uz+6

*5*
! 	 ? 	)D>)'(t$	) 	G!T(K/0345 689:DEE$$0+D,E,E,M,MNN!(()B)BC LMMu$$W"s   H
Hc                    ||d   j                  t        |               j                         }|d   j                         }t	        |      dkD  r/t        j                  ||d      }t        j                  ||g      }|S )a[  Adds a component with given name that contains all of the components
        in group.

        Parameters
        ----------
        components: Dataframe with components.
        name: Name of new group component.
        group: List of components that form the group.

        Returns
        -------
        Dataframe with components.
        r!  r   r   r  )r   r   r   rk   r%   r"   rf   r   )rJ   r,  r   groupnew_comp
group_colss         rL   r(  zProphet.add_group_component  su     j5::3u:FGLLNe_++-
z?Q||JT$JKHJ#9:JrN   c                    |dk(  rdd}|| j                   v r't        j                  dj                  |             |S |r't        j                  dj                  |             |S |}|S |du r|}|S |du rd}|S t	        |      }|S )a  Get number of fourier components for built-in seasonalities.

        Parameters
        ----------
        name: string name of the seasonality component.
        arg: 'auto', True, False, or number of fourier components as provided.
        auto_disable: bool if seasonality should be disabled when 'auto'.
        default_order: int default fourier order

        Returns
        -------
        Number of fourier components, or 0 for disabled.
        r   r   zQFound custom seasonality named {name!r}, disabling built-in {name!r} seasonality.r   zXDisabling {name} seasonality. Run prophet with {name}_seasonality=True to override this.TF)r=   rP   r   r   re   )rJ   r   argauto_disabledefault_orderr  s         rL   parse_seasonality_argszProphet.parse_seasonality_args  s     &=Mt)))55;VV5F$  @VV&  !.  D[)M
 	 E\M   HMrN   c                     | j                   d   j                         }| j                   d   j                         }| j                   d   j                         }|j                  |j
                  j                         d      j                         }||z
  t        j                  d      k  }| j                  d| j                  |d      }|dkD  r)d|| j                  | j                  dd	| j                  d<   ||z
  t        j                  d
      k  xs |t        j                  d      k\  }| j                  d| j                  |d      }|dkD  r)d|| j                  | j                  dd	| j                  d<   ||z
  t        j                  d
      k  xs |t        j                  d      k\  }| j                  d| j                  |d      }|dkD  r*d|| j                  | j                  dd	| j                  d<   yy)a  Set seasonalities that were left on auto.

        Turns on yearly seasonality if there is >=2 years of history.
        Turns on weekly seasonality if there is >=2 weeks of history, and the
        spacing between dates in the history is <7 days.
        Turns on daily seasonality if there is >=2 days of history, and the
        spacing between dates in the history is <1 day.
        r   r   i  r   rv   
   g     v@Nr  r   )weeksr[   ru         rt      )rB   rj   ri   diffr   r   nonzeror"   	Timedeltar7  r)   r0   r-   r=   r*   r+   )	rJ   firstlastr   min_dtyearly_disabler  weekly_disabledaily_disables	            rL   set_auto_seasonalitieszProphet.set_auto_seasonalities  s    T"&&(||D!%%'\\$$$&**,Q/0446 #(>>33d--~rC1 !.#;;--"&,Dx(  %<",,Q*?? <!R\\%:: 	33d--~qB1!.#;;--"&,Dx( ,1)== : BLLa$88 	33T++]A?1!.#;;--"&+Dw' rN   c                 @   | d   j                         | d   j                         }}| d   j                  |   | d   j                  |   z
  }| d   j                  |   | d   j                  |   z
  |z  }| d   j                  |   || d   j                  |   z  z
  }||fS )a  Initialize linear growth.

        Provides a strong initialization for linear growth by calculating the
        growth and offset parameters that pass the function through the first
        and last points in the time series.

        Parameters
        ----------
        df: pd.DataFrame with columns ds (date), y_scaled (scaled time series),
            and t (scaled time).

        Returns
        -------
        A tuple (k, m) with the rate (k) and offset (m) of the linear growth
        function.
        r   r   r   )idxminidxmaxr   )r   i0i1Tkms         rL   linear_growth_initzProphet.linear_growth_init  s    $ D"BtHOO$5BsGLLr#w||B//
^  $r*~':':2'>>!CzN#a"S',,r*:&::1vrN   c                 ^   | d   j                         | d   j                         }}| d   j                  |   | d   j                  |   z
  }| d   j                  |   }| d   j                  |   }t        d|z  t	        d|z  | d   j                  |               }t        d|z  t	        d|z  | d   j                  |               }||z  }||z  }	t        ||	z
        dk  rd|z  }t        j                  |dz
        }
t        j                  |	dz
        }|
|z  |
|z
  z  }|
|z
  |z  }||fS )	a'  Initialize logistic growth.

        Provides a strong initialization for logistic growth by calculating the
        growth and offset parameters that pass the function through the first
        and last points in the time series.

        Parameters
        ----------
        df: pd.DataFrame with columns ds (date), cap_scaled (scaled capacity),
            y_scaled (scaled time series), and t (scaled time).

        Returns
        -------
        A tuple (k, m) with the rate (k) and offset (m) of the logistic growth
        function.
        r   r   r   g{Gz?gGz?r   g?r[   )rI  rJ  r   ri   rj   r   r   log)r   rK  rL  rM  C0C1y0y1r0r1L0L1rO  rN  s                 rL   logistic_growth_initzProphet.logistic_growth_init  s>   $ D"BtHOO$5BsGLLr#w||B// ""2&""2&Cr	2j>+>+>r+BCDCr	2j>+>+>r+BCD"W"WrBw<4BVVBF^VVBF^ Fb2g"WM1vrN   c                 4    d}| d   j                         }||fS )a  Initialize flat growth.

        Provides a strong initialization for flat growth. Sets the growth to 0
        and offset parameter as mean of history y_scaled values.

        Parameters
        ----------
        df: pd.DataFrame with columns ds (date), y_scaled (scaled time series),
            and t (scaled time).

        Returns
        -------
        A tuple (k, m) with the rate (k) and offset (m) of the linear growth
        function.
        r   r   )r   )r   rN  rO  s      rL   flat_growth_initzProphet.flat_growth_initI  s$    " zN!!trN   r   c                    d|vsd|vrt        d      ||d   j                            j                         }|j                  d   dk  rt        d      t	        j
                  t	        j                  |d   j                         d            j                         | _	        | j                  |d	      | _        | j                          | j                  | j                        \  }}}}|| _        || _        t!        |      | _        | j%                          | j&                  d
v r-t)        j*                  | j                  j                  d         }n| j                  d   }t-        | j                  j                  d   t/        | j0                        |j                  d   | j2                  t4        | j&                  j7                            j8                  | j                  d   | j                  d   | j0                  |||d   |d   |      S )a  
        Reformats historical data, standardizes y and extra regressors, sets seasonalities and changepoints.

        Saves the preprocessed data to the instantiated object, and also returns the relevant components
        as a ModelInputData object.
        r   r~   zPDataframe must have columns "ds" and "y" with the dates and values respectively.r   r   z'Dataframe has less than 2 non-NaN rows.r   T)r   )rX   rZ   r   r[   r   r   rs   r{   )rM  SKtautrend_indicatorr~   r   t_changeXsigmass_as_mr   )r6   notnullr   r   r"   r$   r#   rk   r   rC   r   rB   rG  r  rD   rE   r   rG   r   r    r   rw   r   r%   r<   r1   r   uppervalue)	rJ   r   kwargsrB   r  r   r  r  r   s	            rL   
preprocesszProphet.preprocess^  s    N2'  RW__&',,.==aFGG^^BIIbhoo6Gd,ST``b++Gt+L##%..t||< 	?<$2!$"6*;;,,((4<<--a01C,,|,Cll  #$%%&%%a(,,*4;;+<+<+>?EEll:&ll3((/056
 	
rN   num_total_regressorsc                    | j                   dk(  r| j                  | j                        \  }}n[| j                   dk(  r| j                  | j                        \  }}n-| j                   dk(  r| j	                  | j                        \  }}t        t        j                  | j                        t        j                  |      d      S )z
        Calculates initial parameters for the model based on the preprocessed history.

        Parameters
        ----------
        num_total_regressors: the count of seasonality fourier components plus holidays plus extra regressors.
        rX   rZ   rY   r   )rN  rO  deltabeta	sigma_obs)
r    rP  rB   r]  r[  r   r   
zeros_liker<   rw   )rJ   rm  rN  rO  s       rL   calculate_initial_paramsz Prophet.calculate_initial_params  s     ;;("**4<<8DAq[[F"((6DAq[[J&,,T\\:DAq-- 3 34./
 	
rN   c                 t   | j                   t        d       | j                  |fi |}| j                  |j                        }t        j                  |      }t        j                  |      }| j                   d   j                         | j                   d   j                         k(  rv| j                  dk(  s| j                  dk(  rX|| _
        d| j                  d<   | j                  D ]2  }t        j                  | j                  |   g      | j                  |<   4 na| j                  dkD  r/ | j                  j                  ||| j                  fi || _
        n# | j                  j                   ||fi || _
        | j                  j"                  | _        t%        | j&                        dk(  r| j                  d   | j                  d	   j)                  d
      z   | j                  d<   t        j*                  | j                  d	   j,                        j)                  d      | j                  d	<   | S )a  Fit the Prophet model.

        This sets self.params to contain the fitted model parameters. It is a
        dictionary parameter names as keys and the following items:
            k (Mx1 array): M posterior samples of the initial slope.
            m (Mx1 array): The initial intercept.
            delta (MxN array): The slope change at each of N changepoints.
            beta (MxK matrix): Coefficients for K seasonality features.
            sigma_obs (Mx1 array): Noise level.
        Note that M=1 if MAP estimation.

        Parameters
        ----------
        df: pd.DataFrame containing the history. Must have columns ds (date
            type) and y, the time series. If self.growth is 'logistic', then
            df must also have a column cap that specifies the capacity at
            each ds.
        kwargs: Additional arguments passed to the optimizing or sampling
            functions in Stan.

        Returns
        -------
        The fitted Prophet object.
        z>Prophet object can only be fit once. Instantiate a new object.r~   rX   rZ   g&.>rq  r   rN  ro  r   )r   r[   )rB   rR   rl  rs  r`  dataclassesasdictrj   ri   r    rA   r   r   r3   rK   samplingfitr@   r%   r!   reshaperw   r   )rJ   r   rk  model_inputsinitial_paramsdat	stan_initpars           rL   rx  zProphet.fit  s   2 <<# 8 9 9 'tr4V466|~~F  .&&~6	<<  "dll3&7&;&;&==(DKK6,A#DK'+DKK${{ @#%88T[[-=,>#?C @"4$++44YTEVEVaZ`aDK/$++//	3I&IDK))22t  !Q& C 4;;w#7#?#?#CC KK %'HHT[[-A-G-G$H'.ww'7 KK  rN   
vectorizedc                 F   | j                   t        d      || j                   j                         }n<|j                  d   dk(  rt	        d      | j                  |j                               }| j                  |      |d<   | j                  |      }| j                  r| j                  ||      }nd}ddg}d|v r|j                  d       | j                  r|j                  d       t        j                  ||   ||fd	
      }|d   d	|d   z   z  |d   z   |d<   |S )aU  Predict using the prophet model.

        Parameters
        ----------
        df: pd.DataFrame with dates for predictions (column ds), and capacity
            (column cap) if logistic growth. If not provided, predictions are
            made on the history.
        vectorized: Whether to use a vectorized method to compute uncertainty intervals. Suggest using
            True (the default) for much faster runtimes in most cases,
            except when (growth = 'logistic' and mcmc_samples > 0).

        Returns
        -------
        A pd.DataFrame with the forecast components.
        NModel has not been fit.r   zDataframe has no rows.rr   r   r   r   r[   r  r{   rs   ry   )rB   rR   r   r   r6   r   predict_trendpredict_seasonal_componentsr5   predict_uncertaintyr  r:   r"   r   )rJ   r   r  seasonal_components	intervalscolsdf2s          rL   predictzProphet.predict  s,     <<566:""$Bxx{a !9::%%bggi0B((,7">>rB##00Z@II gB;KKKK iiD9.ABKGC(>$? ?@&'( 	F 
rN   c                     |dddf   | d   k  |z  }|j                  d      |z   }|| z  j                  d      |z   }|| z  |z   S )a  Evaluate the piecewise linear function.

        Parameters
        ----------
        t: np.array of times on which the function is evaluated.
        deltas: np.array of rate changes at each changepoint.
        k: Float initial rate.
        m: Float initial offset.
        changepoint_ts: np.array of changepoint times.

        Returns
        -------
        Vector y(t).
        N).Nr[   r  )sum)r   deltasrN  rO  changepoint_tsdeltas_tk_tm_ts           rL   piecewise_linearzProphet.piecewise_linear  sb      #47+q|;vElll"Q&>/)..A.6:Qw}rN   c                 X   t        j                  t        j                  |      t        j                  |      |z   f      }t        j                  t        |            }t        |      D ]5  \  }}	|	|z
  t        j                  |      z
  d||   ||dz      z  z
  z  ||<   7 |t        j                  |       z  }
|t        j                  |       z  }t        |      D ]*  \  }}	| |	k\  }|
|xx   ||   z  cc<   ||xx   ||   z  cc<   , |dt        j                  |
 | |z
  z        z   z  S )a  Evaluate the piecewise logistic function.

        Parameters
        ----------
        t: np.array of times on which the function is evaluated.
        cap: np.array of capacities at each t.
        deltas: np.array of rate changes at each changepoint.
        k: Float initial rate.
        m: Float initial offset.
        changepoint_ts: np.array of changepoint times.

        Returns
        -------
        Vector y(t).
        r[   )
r   concatenate
atleast_1dcumsumrw   r%   	enumerater  	ones_likeexp)r   r   r  rN  rO  r  k_cumgammasrU   t_sr  r  sindxs                 rL   piecewise_logisticzProphet.piecewise_logistic"  s%   $ a 0"))F2Ca2GHI#n-./ 	FAs1Wrvvf~-58eAEl224 1I	 ",,q/!",,q/!/ 	#FAs8DI"II"I	# a"&&#S!12233rN   c                 6    |t        j                  |       z  }|S )zEvaluate the flat trend function.

        Parameters
        ----------
        t: np.array of times on which the function is evaluated.
        m: Float initial offset.

        Returns
        -------
        Vector y(t).
        )r   r  )r   rO  r  s      rL   
flat_trendzProphet.flat_trendD  s     ",,q/!
rN   c                 6   t        j                  | j                  d         }t        j                  | j                  d         }t        j                  | j                  d   d      }t        j                  |d         }| j                  dk(  r | j                  ||||| j                        }nV| j                  dk(  r&|d	   }| j                  |||||| j                        }n!| j                  d
k(  r| j                  ||      }| j                  z  |d   z   S )zPredict trend using the prophet model.

        Parameters
        ----------
        df: Prediction dataframe.

        Returns
        -------
        Vector with trend on prediction dates.
        rN  rO  ro  r   r  r   rX   rY   r   rZ   r   )
r   nanmeanrA   r   r    r  r<   r  r  r9   )rJ   r   rN  rO  r  r   rr   r   s           rL   r  zProphet.predict_trendT  s     JJt{{3'(JJt{{3'(DKK0q9HHRW;;("))!VQ4;N;NOE[[J&\"C++31d&9&9;E[[F"OOAq)Et||#bk11rN   c                 ~   | j                  |      \  }}}}| j                  r*dd| j                  z
  z  dz  }dd| j                  z   z  dz  }|j                  }i }|j                  D ]  }	| j
                  d   ||	   j                  z  }
t        j                  ||
j                               }|	| j                  d   v r|| j                  z  }t        j                  |d      ||	<   | j                  s| j                  |d      ||	dz   <   | j                  |d      ||	d	z   <    t        j                  |      S )
zPredict seasonality components, holidays, and added regressors.

        Parameters
        ----------
        df: Prediction dataframe.

        Returns
        -------
        Dataframe with seasonal components.
        d   r   r   rp  rb   r[   r  r|   r}   )r  r5   r4   r   r   rA   r   matmul	transposerE   r9   r  
percentiler"   rf   )rJ   r   r  _r  lower_pupper_prd  datar!  beta_ccomps               rL   r  z#Prophet.predict_seasonal_componentsp  sT    ..r2 	01na ##S4#6#667!;GS4#6#667!;G$$'// 	I[[(>)+D+K+KKF99Q 0 0 23DD00<<$ jjA6DO''-1__' .= .Y)* .2__' .= .Y)*	 ||D!!rN   c                 Z   | j                  ||      }dd| j                  z
  z  dz  }dd| j                  z   z  dz  }i }dD ]T  }| j                  ||   |d      |dj                  |      <   | j                  ||   |d      |dj                  |      <   V t	        j
                  |      S )	a  Prediction intervals for yhat and trend.

        Parameters
        ----------
        df: Prediction dataframe.
        vectorized: Whether to use a vectorized method for generating future draws.

        Returns
        -------
        Dataframe with uncertainty intervals.
        r  r   r   ry   rr   r[   r  z{}_lowerz{}_upper)sample_posterior_predictiver4   r  r   r"   rf   )rJ   r   r  
sim_valuesr  r  seriesr  s           rL   r  zProphet.predict_uncertainty  s     55b*E
t2223a7t2223a7$ 	2C-1__3q .= .2F:$$S)*-1__3q .= .2F:$$S)*	2 ||F##rN   c                 h   | j                   d   j                  d   }t        dt        t	        j
                  | j                  t        |      z                    }| j                  |      \  }}}}g g d}t        |      D ]y  }	|r| j                  |||	|d   |d   |      }
n2t        |      D cg c]  }| j                  |||	|d   |d           }
}|D ]   }|
D ]  }||   j                  ||           " { |j                         D ]  \  }}t	        j                  |      ||<    |S c c}w )	aY  Prophet posterior predictive samples.

        Parameters
        ----------
        df: Prediction dataframe.
        vectorized: Whether to use a vectorized method to generate future draws.

        Returns
        -------
        Dictionary with posterior predictive samples for the forecast yhat and
        for the trend component.
        rN  r   r[   r  rs   r{   )r   r  	iterationrf  rg  	n_samples)r   r  r  rf  rg  )rA   r   ri   re   r   ceilr5   r/   r  r   sample_model_vectorizedsample_modelr  r   column_stack)rJ   r   r  n_iterationssamp_per_iterr  r  r  r  rU   simsr  simrN  vs                  rL   r  z#Prophet.sample_posterior_predictive  s    {{3'--a0As277$$u\'::$
   
 ..r2 	01na !2.
|$ 	5A33&7&'78&'=>+ 4    %]3  %%*;"#*+;<*+AB &   " 5 5CsO**3s8455)	5. $$& 	/DAqOOA.JqM	/s   1#D/c                    | j                  ||      }| j                  d   |   }t        j                  |j                  ||j                  z        | j
                  z  }t        j                  |j                  ||j                  z        }	| j                  d   |   }
t        j                  j                  d|
|j                  d         | j
                  z  }|d|	z   z  |z   |z   |dS )a  Simulate observations from the extrapolated generative model.

        Parameters
        ----------
        df: Prediction dataframe.
        seasonal_features: pd.DataFrame of seasonal features.
        iteration: Int sampling iteration to use parameters from.
        s_a: Indicator vector for additive components
        s_m: Indicator vector for multiplicative components

        Returns
        -------
        Dictionary with `yhat` and `trend`, each like df['t'].
        rp  rq  r   r[   r  )	sample_predictive_trendrA   r   r  r   r9   randomnormalr   )rJ   r   r  r  rf  rg  rr   rp  Xb_aXb_msigmanoises               rL   r  zProphet.sample_model  s     ,,R;{{6"9-yy*11

*,.2ll;yy*114#**3DEK(3		  E288A;7$,,F QX&-5
 	
rN   r  r  rf  rg  r  c                    | j                   d   |   }t        j                  |j                  ||j                  z        | j                  z  }t        j                  |j                  ||j                  z        }	| j                  |||      }
| j                   d   |   }t        j                  j                  d||
j                        | j                  z  }g }t        |
|      D ]%  \  }}|j                  |d|	z   z  |z   |z   |d       ' |S )zSimulate observations from the extrapolated generative model. Vectorized version of sample_model().

        Returns
        -------
        List (length n_samples) of dictionaries with arrays for trend and yhat, each ordered like df['t'].
        rp  rq  r   r[   r  )rA   r   r  r   r9   "sample_predictive_trend_vectorizedr  r  r   zipr  )rJ   r   r  r  rf  rg  r  rp  r  r  trendsr  noise_termssimulationsrr   r  s                   rL   r  zProphet.sample_model_vectorized  s     {{6"9-yy*11szz)+-1\\:yy*114#**3DE88Y	RK(3ii&&q%>M4 	LE5T*T1E9  	
 rN   c                    | j                   d   |   }| j                   d   |   }| j                   d   |   }t        j                  |d         }|j                         }|dkD  r;t	        | j
                        }t        j                  j                  ||dz
  z        }	nd}	|	dkD  r9dt        j                  j                  |	      |dz
  z  z   }
|
j                          ng }
t        j                  t        j                  |            dz   }t        j                  j                  d||	      }t        j                  | j
                  |
f      }t        j                  ||f      }| j                  dk(  r| j                  |||||      }nL| j                  d	k(  r|d
   }| j!                  ||||||      }n!| j                  dk(  r| j#                  ||      }| j$                  z  |d   z   S )a"  Simulate the trend using the extrapolated generative model.

        Parameters
        ----------
        df: Prediction dataframe.
        iteration: Int sampling iteration to use parameters from.

        Returns
        -------
        np.array of simulated trend over df['t'].
        rN  rO  ro  r   r[   r   :0yE>rX   rY   r   rZ   r   )rA   r   r   ri   r%   r<   r  poissonrandr   r   r   laplacer  r    r  r  r  r9   )rJ   r   r  rN  rO  r  r   rM  r_  	n_changeschangepoint_ts_newlambda_
deltas_newr  rr   r   s                   rL   r  zProphet.sample_predictive_trend  s    KKY'KKY'W%i0HHRWEEG q5D''(A		))!q1u+6IIq=!"RYY^^I%>!a%%H!H##%!# ''"&&.)D0 YY&&q'9=
 )<)<);)= > 45;;("))!VQ>JE[[J&\"C++AsFAq,:<E[[F"OOAq)Et||#bk11rN   c                    | j                   d   |   }| j                   d   |   }| j                   d   |   }| j                  dk(  r-| j                  |d   j                  |||| j                        }n| j                  dk(  r;| j                  |d   j                  |d   j                  |||| j                        }n5| j                  dk(  r | j                  |d   j                  |      }nt        | j                  |||      }t        j                  ||d	f      |z   | j                  z  t        j                  |d
   j                  |d	f      z   S )zSample draws of the future trend values. Vectorized version of sample_predictive_trend().

        Returns
        -------
        Draws of the trend values with shape (n_samples, len(df)). Values are on the scale of the original data.
        ro  rO  rN  rX   r   rY   r   rZ   r[   r   )rA   r    r  r   r<   r  r  NotImplementedError_sample_uncertaintyr   tiler9   )	rJ   r   r  r  r  rO  rN  expecteduncertaintys	            rL   r  z*Prophet.sample_predictive_trend_vectorizedS  s7    W%i0KKY'KKY';;(",,RW^^VQ4K^K^_H[[J&..3< 0 7 7AtGZGZH [[F"r#w~~q9H%%..r9iHWWX	1~.<LGGBwK&&A78	
rN   c           
         |d   j                         dk  r"t        j                  |t        |      f      }|S |j                  |d   dkD     }t        |      }|dkD  r't        j
                  |d         j                         }n0t        j
                  | j                  d         j                         }t        | j                        |z  }| j                  d   |   }	| j                  d   |   }
| j                  d   |   }t        j                  t        j                  |	            dz   }| j                  dk(  r=| j                  ||||      }|j                  d	      j                  d	      }||z  }n| j                  d
k(  rI| j                  ||||      }| j                  ||	||
|d   j                  |d   j                  ||      }n-| j                  dk(  rt        j                  ||f      }nt         |d   j#                         dk  rIt        j                  |t        j$                  |d   dk        f      }t        j&                  ||gd	      }|S )a  Sample draws of future trend changes, vectorizing as much as possible.

        Parameters
        ----------
        df: DataFrame with columns `t` (time scaled to the model context), trend, and cap.
        n_samples: Number of future paths of the trend to simulate
        iteration: The iteration of the parameter set to use. Default 0, the first iteration.

        Returns
        -------
        Draws of the trend changes with shape (n_samples, len(df)). Values are standardized.
        r   r[   ro  rO  rN  r  rX   )r  r  rY   r   )matr  rN  rO  r   t_timen_lengthsingle_diffrZ   )ri   r   rw   r%   r  r>  r   rB   r<   rA   r   r    _make_trend_shift_matrixr  _logistic_uncertaintyr   r  rj   r  r  )rJ   r   r  r  uncertainties	future_dfr  r  change_likelihoodr  rO  rN  
mean_deltar  past_uncertaintys                  rL   r  zProphet._sample_uncertaintym  s9    c7;;=AHHiR%9:MN K r#w{+I9~H!| ggin5::< ggdll3&78==? #D$7$7 8; F[[))4FC +AC +A047J{{h&33J@QS[gp3q #


 2 9 9q 9 A,
*33J@QS[gp3q $ : :!!,/66$S>00% + !; 	! & ")X)> ?))#w{{}!#%88Yr#w!|8L,M#N  "0@-/PWX YrN   r  
likelihoodfuture_lengthc                 >   t         j                  j                  ||f      |k  }t         j                  j                  d| |j                        }||z  }t        j
                  t        j                  t        |      df      |g      ddddf   }||z   dz  }|S )a!  
        Creates a matrix of random trend shifts based on historical likelihood and size of shifts.
        Can be used for either linear or logistic trend shifts.
        Each row represents a different sample of a possible future, and each column is a time step into the future.
        )sizer   r[   Nr   r   )r   r  uniformr  r   hstackrw   r%   )r  r  r  r  bool_slope_changeshift_valuesr  n_mats           rL   r  z Prophet._make_trend_shift_matrix  s     II--I}3M-NQ[[yy((J=N=T=T(U..		288SXqM2C89!SbS&As{a
rN   c                    |#t        j                  |      j                         }t        j                  dd|z   |      }g }|D ]/  }|j	                  t        j
                  ||kD        d   d          1 t        j                  t        |            }| ||<   t        j                  |j                  dd      |d      }||fS )z
        Creates a matrix of slope-deltas where these changes occured in training data according to the trained prophet obj
        r   r[   r   r  )
r   r>  r   r'  r  whererw   r%   repeatry  )	r  r<   r  n_rowr  	prev_timeidxschangepointprev_deltass	            rL   _make_historical_mat_timez!Prophet._make_historical_mat_time  s    
 ''&/..0KIIa[+>	) 	AKKK[!89!<Q?@	Ahhs9~."Dii 3 3Ar :EJI%%rN   r  r  rN  rO  r   r  r  r  c	           
         d }	| j                  || j                  |t        |      |      \  }
}t        j                  |
|gd      }t        j                  ||g      }t        j                  t        j
                  |j                  d   df      |z  t        j                  |t        j                  |d      |z   d      fd      } |	|      }t        j                  |      }t        |j                  d         D ]P  }||   |z
  t        j                  |ddd|f   d      z
  }d|dd|f   |dd|dz   f   z  z
  }||z  |dd|f<   R |j                  d      |z   dd| df   }|j                  d      |z   dd| df   }|dt        j                  | ||z
  z        z   z  }||j                  d      z
  S )a  
        Vectorizes prophet's logistic uncertainty by creating a matrix of future possible trends.

        Parameters
        ----------
        mat: A trend shift matrix returned by _make_trend_shift_matrix()
        deltas: The size of the trend changes at each changepoint, estimated by the model
        k: Float initial rate.
        m: Float initial offset.
        cap: np.array of capacities at each t.
        t_time: The values of t in the model context (i.e. scaled so that anything > 1 represents the future)
        n_length: For each path, the number of future steps to simulate
        single_diff: The difference between each t step in the model context. Default None, inferred
            from t_time.

        Returns
        -------
        A numpy array with shape (n_samples, n_length), representing the width of the uncertainty interval
        (standardized, not on the same scale as the actual data values) around 0.
        c                    | dk(  }t        j                  | t        j                  |j                  d         d      }t         j                  j                  |d|       | t        j                  |j                  d         d d d f   |f   S )Nr   r[   )r  out)r   r  r'  r   maximum
accumulate)arrmaskidxs      rL   ffillz,Prophet._logistic_uncertainty.<locals>.ffill  ss    !8D((D5"))DJJqM":A>CJJ!!#A3!7ryy1.q$w7<==rN   r[   r  r   N)r  r<   r%   r   r  onesr   r  r  rr  r   r  r  r   )rJ   r  r  rN  rO  r   r  r  r  r  historical_mathistorical_timefull_t_timer  k_cum_br  rU   r   ksr  r  sample_trendss                         rL   r  zProphet._logistic_uncertainty  s   @	> +/*H*HQUQdQdflnqrunv  yD  +E'nnnc2;nnov%>? 1q(9 :Q >biiX[bcNdghNhjk@lmtuv,s#syy|$ 	"AA"RVVF1bqb5M%BBAWQT]WQAX%666Br6F1a4L	"
 zzqz!A%q8)*}5}}!}$q(!hYZ-8q2663$&3,*?#@@A }11q1999rN   c                 d    | j                  |j                               }| j                  ||      S )a  Sample from the posterior predictive distribution. Returns samples
        for the main estimate yhat, and for the trend component. The shape of
        each output will be (nforecast x nsamples), where nforecast is the
        number of points being forecasted (the number of rows in the input
        dataframe) and nsamples is the number of posterior samples drawn.
        This is the argument `uncertainty_samples` in the Prophet constructor,
        which defaults to 1000.

        Parameters
        ----------
        df: Dataframe with dates for predictions (column ds), and capacity
            (column cap) if logistic growth.
        vectorized: Whether to use a vectorized method to compute possible draws. Suggest using
            True (the default) for much faster runtimes in most cases,
            except when (growth = 'logistic' and mcmc_samples > 0).

        Returns
        -------
        Dictionary with keys "trend" and "yhat" containing
        posterior predictive samples for that component.
        )r   r   r  )rJ   r   r  s      rL   predictive_sampleszProphet.predictive_samples  s-    , !!"''),//J??rN   c                     t        j                  |      j                         rt         j                  nt         j                  } ||g|i |S )aj  
        We rely on np.nanpercentile in the rare instances where there
        are a small number of bad samples with MCMC that contain NaNs.
        However, since np.nanpercentile is far slower than np.percentile,
        we only fall back to it if the array contains NaNs. See
        https://github.com/facebook/prophet/issues/1310 for more details.
        )r   r   rh   nanpercentiler  )rJ   aargsrk  fns        rL   r  zProphet.percentile  s;     "$!!2R!%d%f%%rN   c                    | j                   t        d      |;t        j                  | j                   j	                  d            }|t        d      | j                   j                         }t        j                  ||dz   |      }|||kD     }|d| }|r4t        j                  t        j                  | j                         |f      }t        j                  d|i      S )a  Simulate the trend using the extrapolated generative model.

        Parameters
        ----------
        periods: Int number of periods to forecast forward.
        freq: Any valid frequency for pd.date_range, such as 'D' or 'M'.
        include_history: Boolean to include the historical dates in the data
            frame for predictions.

        Returns
        -------
        pd.Dataframe that extends forward from the end of self.history for the
        requested number of periods.
        Nr     zUnable to infer `freq`r[   )r7   periodsfreqr   )rC   rR   r"   
infer_freqr   ri   
date_ranger   r  r   rf   )rJ   r  r  include_history	last_dater   s         rL   make_future_dataframezProphet.make_future_dataframe&  s     %566<==!3!3!8!8!;<D| 899&&**,	aK ei'(hwNNBHHT-?-?$@%#HIE||T5M**rN   c	                 *    t        | ||||||||	      S )a  Plot the Prophet forecast.

        Parameters
        ----------
        fcst: pd.DataFrame output of self.predict.
        ax: Optional matplotlib axes on which to plot.
        uncertainty: Optional boolean to plot uncertainty intervals.
        plot_cap: Optional boolean indicating if the capacity should be shown
            in the figure, if available.
        xlabel: Optional label name on X-axis
        ylabel: Optional label name on Y-axis
        figsize: Optional tuple width, height in inches.
        include_legend: Optional boolean to add legend to the plot.

        Returns
        -------
        A matplotlib figure.
        )	rO  fcstaxr  plot_capxlabelylabelfigsizeinclude_legend)r   )	rJ   r  r  r  r  r  r  r   r!  s	            rL   r   zProphet.plotJ  s&    ( "+fVN
 	
rN   c           	      &    t        | ||||||      S )a  Plot the Prophet forecast components.

        Will plot whichever are available of: trend, holidays, weekly
        seasonality, and yearly seasonality.

        Parameters
        ----------
        fcst: pd.DataFrame output of self.predict.
        uncertainty: Optional boolean to plot uncertainty intervals.
        plot_cap: Optional boolean indicating if the capacity should be shown
            in the figure, if available.
        weekly_start: Optional int specifying the start day of the weekly
            seasonality plot. 0 (default) starts the week on Sunday. 1 shifts
            by 1 day to Monday, and so on.
        yearly_start: Optional int specifying the start day of the yearly
            seasonality plot. 0 (default) starts the year on Jan 1. 1 shifts
            by 1 day to Jan 2, and so on.
        figsize: Optional tuple width, height in inches.

        Returns
        -------
        A matplotlib figure.
        )rO  r  r  r  weekly_startyearly_startr   )r   )rJ   r  r  r  r#  r$  r   s          rL   r   zProphet.plot_componentsd  s"    2 ;%L
 	
rN   )rX   N   皙?r   r   r   Nrb         $@r'  g?r   r&  i  Nr   N)TTT)F)Nr   N)NNN)NT)r   )r[   N)N)T)DT)NTTr   r~   )r9     F)TTr   r   N)D__name__
__module____qualname____doc__r   rM   rI   rH   rl   r   r   r   staticmethodr"   r#   r   re   r/   r   r   float64r   classmethodr   r   r  r  r  r  r  r  r(  r7  rG  rP  r[  r]  rf   r   rl  r   rs  rx  r   r  r  r  r  r  r  r  r
   ndarrayr  r  r   r  r  r  r  r  r  r  r  r  r  r   r    rN   rL   r   r      sX   3n !%%$'$(!%$( $#'I.$ %I.VN*X 9=HL0dZx/9b/0b "yy"c5j!" " 
		" "@ 7 7,-^EAN AG1f HL26?B'R@FDA%F*#J5n  . ' 'R  (.
R\\ .
 .
`
S 
[ 
,8t-",, -4 -2<< -^  ( 4 4B  28""H$bll $ $ $4/bll / /QUVY[][e[eVeQf /b
$sTVT^T^J_ 
<LL << 	
 ZZ ZZ  
d3

?#	$B32j
R\\ 
c 
^a 
jljtjt 
47bll 7s 7s 7[][e[e 7r ',=BOR	   & &0 "9:ZZ9: 

9: 	9:
 9: ZZ9: 

9: 9: 9: 
9:v@R\\ @t @2	&"+H >BFK
4 @D@D
rN   r   ))
__future__r   r   r   ru  loggingcollectionsr   r   r   r   datetimer	   typingr
   r   r   numpyr   pandasr"   numpy.typingr   prophet.make_holidaysr   r   prophet.modelsr   r   r   r   prophet.plotr   r   	getLoggerrP   setLevelINFOr   objectr   r2  rN   rL   <module>rB     sn    A @   0   $ $     E W W 0			9	%  + e
f e
rN   