
    ]h<                    0   S SK JrJrJr  S SKrS SKrS SKJrJr  S SK	J
r
  S SKJr  S SKJrJrJr  S SKrS SKrS SKJr  S SKJrJr  S S	KJrJrJrJrJr  S S
K J!r!J"r"  \RF                  " S5      r$\$RK                  \RL                  5        Sr' " S S\(5      r)g)    )absolute_importdivisionprint_functionN)OrderedDictdefaultdict)deepcopy)	timedelta)DictListUnion)NDArray)get_holiday_namesmake_holidays_df)StanBackendEnumModelInputDataModelParamsTrendIndicatorIStanBackend)plotplot_componentspropheti ʚ;c                   H   \ rS rSr% \\S'                      SKS\4S jjrS rS r	  SLS jr
SMS	 jrS
 rS r\S\R                   S\\\4   S\S\\R,                     4S j5       r\S 5       rS rS r  SNS jr  SOS jrS rS rS r S r!S r"S r#\S 5       r$\S 5       r%\S 5       r&S\RN                  S\(4S  jr)S!\S\*4S" jr+S# r,SPS\RN                  S$\-S\RN                  4S% jjr.\S& 5       r/\S' 5       r0\S( 5       r1S) r2S* r3S\RN                  S$\-S\RN                  4S+ jr4S\RN                  S$\-S\5\\Rl                  4   4S, jr7S\5\\Rl                  4   4S- jr8S\RN                  S.\RN                  S/\S0\Rl                  S1\Rl                  S2\S\9\5\\Rl                  4      4S3 jr:S4 r;SQS\RN                  S2\S/\S\Rl                  4S5 jjr<SQS\RN                  S2\S/\S\Rl                  4S6 jjr=\S7\S8\S9\S2\S\Rl                  4
S: j5       r>\SRS; j5       r? SSS<\Rl                  S=\Rl                  S>\S?\S@\Rl                  SA\Rl                  SB\SC\S\Rl                  4SD jjr@STS\RN                  S$\-4SE jjrASF rBSUSG jrC  SVSH jrD  SWSI jrESJrFg)XProphet   stan_backendNscalingc                    Xl         X l        U R                  bZ  [        R                  " [        R                  " U R                  5      SS9U l        [        U R                  5      U l        SU l        OX0l        SU l        X@l        XPl	        X`l
        Xpl        Xl        Xl        UU l        Uc  U R                  U l        [        U
5      U l        [        U5      U l        [        U5      U l        Xl        Xl        Xl        US;  a  [-        S5      eUU l        S U l        S U l        S U l        SU l        S U l        S U l        [=        0 5      U l        [=        0 5      U l         S U l!        S U l"        0 U l#        S U l$        S U l%        S U l&        S U l'        S U l(        0 U l)        U RU                  5         U RW                  U5        g )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/   r0   r3   r5   r4   r6   r7   r8   r   r   r1   s                      eC:\Users\julio\OneDrive\Documentos\Trabajo\Ideas Frescas\venv\Lib\site-packages\prophet/forecaster.py__init__Prophet.__init__U   s   * (( "		"..9J9J*KRV WD"%d&7&7"8D*.D'"0*/D'!2"4"4!2  0* !%!6!6D',-D'E$',-D'E$$)*>$?!(,#6 ..JKK 

#"(_ +B $!$(!##' -    c                    UcJ  [          H?  n [        R                  SUR                  5        U R	                  UR                  5      s  $    O [         R                  " U5      " 5       U l        [        R                  SU R                  R                  5       5        g ! [
         a,  n[        R                  SUR                  U5         S nAM  S nAff = f)NzTrying to load backend: %sz3Unable to load backend %s (%s), trying the next onezLoaded stan backend: %s)	r   loggerdebugr    rL   	Exceptionget_backend_classr   get_type)rM   r   ies       rN   rL   Prophet._load_stan_backend   s    $cLL!=qvvF22166:: % !0 A A, O QD.0A0A0J0J0LM ! cLL!VXYX^X^`abbcs   :B
C'!CCc                    U R                   S;  a  [        S5      e[        U R                  [        [
        45      (       d  [        S5      eU R                  S:  d  U R                  S:  a  [        S5      eU R                  Gb  [        U R                  [        R                  5      (       a   SU R                  ;   a  S	U R                  ;   d  [        S
5      e[        R                  " U R                  S   5      U R                  S'   U R                  S   R                  5       R                  5       (       d0  U R                  S	   R                  5       R                  5       (       a  [        S5      eSU R                  ;   nSU R                  ;   nX-   S:X  a  [        S5      eU(       aX  U R                  S   R                  5       S:  a  [        S5      eU R                  S   R                  5       S:  a  [        S5      eU R                  S	   R                  5        H  nU R                  USS9  M     U R                   S;  a  [        S5      eU R"                  S;  a  [        S5      eg)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#   r9   
isinstancer+   intr2   r/   r%   	DataFramer'   isnullanymaxminuniquevalidate_column_namer0   r1   )rM   	has_lower	has_upperhs       rN   rK   Prophet.validate_inputs   s   ;;<<NP P$003,??LMM##a'T-C-Ca-GNOO==$4==",,77DMM).  "6 7 7"$..t1D"EDMM$d#**,0022==+22488:: !EFF&$--7I&$--7I$)  "< = ===0446:$%JKK==0446:$%JKK]]9-446))!E)B 7  (FFI  %CCF  DrQ   c                 &   SU;   a  [        S5      e/ SQnU Vs/ s H  ofS-   PM	     nnU Vs/ s H  ofS-   PM	     nnUR                  U5        UR                  U5        UR                  / SQ5        X;   a  [        SR                  US95      eU(       aE  U R                  b8  XR                  S
   R	                  5       ;   a  [        SR                  US95      eU(       aH  U R
                  b;  U[        U R
                  5      ;   a"  [        SR                  XR
                  S95      eU(       a'  XR                  ;   a  [        SR                  US95      eU(       a(  XR                  ;   a  [        SR                  US95      eg	g	s  snf s  snf )a!  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    rB   z-Name {name!r} already used for a seasonality.z2Name {name!r} already used for an added regressor.)	r9   extendformatr/   ro   rB   r   r@   rA   )	rM   r    rd   check_seasonalitiescheck_regressorsreserved_namesnrn_lrn_us	            rN   rp   Prophet.validate_column_name   s    <==

 '55nHn5&45nHn5d#d# A 	B!,333>  t}}8i07799;BBBM  t44@)$*?*?@@HT4I4IJ  4+=+=#=?T"  (=(= =DT"  !>5 65s
   F	Fc                    SU;   a]  [         R                  " US   5      US'   [        R                  " US   R                  5      R                  5       (       a  [        S5      eUS   R                  [        R                  :X  a  US   R                  [        5      US'   [         R                  " US   5      US'   US   R                  R                  b  [        S5      eUS   R                  5       R                  5       (       a  [        S5      eU R                   Hw  nX1;  a  [        SR!                  US95      e[         R                  " X   5      X'   X   R                  5       R                  5       (       d  Ma  [        S	R!                  US95      e   U R"                  R	                  5        H  nUS
   nUc  M  XQ;  a  [        SR!                  US95      eX   R%                  SS/5      R'                  5       (       d  [        SR!                  US95      eX   R                  S5      X'   M     UR(                  R*                  S:X  a  SUR(                  l        UR-                  SSS9nUR/                  SS9nU R1                  X!5        U R2                  (       a  SU;  a  [        S5      eO5U R4                  S:X  a  SUS'   OU R4                  S:X  a  U R6                  US'   U R8                  S:X  aU  SU;  a  [        S5      eUS   US   :*  R                  5       (       a  [        S5      eUS   US   -
  U R:                  -  US'   US   U R<                  -
  U R>                  -  US'   SU;   a  US   US   -
  U R:                  -  US'   U R                  RA                  5        H  u  p4X   US    -
  US!   -  X'   M     U$ )"a  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"   r]   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valuesrl   r9   dtypeint64astypestrr'   dttzrk   rA   r   r@   isinallindexr    sort_valuesreset_indexinitialize_scalesr=   r   r;   r#   r<   r:   r>   items)rM   dfr   r    propsr   s         rN   setup_dataframeProphet.setup_dataframe  s   " "9mmBsG,BsGxx3'++-- !>??d8>>RXX%$xs+BtH>>"T(+4d8;;>>%#  d8??  ""677))D~ ?VV&  }}RX.BHx $$&& 299t9D  * ''..0E"#34N)!+$M~>  )..e}=AACC$H~>  &(%7%>%>v%F" 1 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8KDE$K/5<?BH 9	rQ   c                    U(       d  gU R                   S:X  a  SU;   a  SU l        U R                  S:X  ak  [        US   US   -
  R	                  5       R                  5       5      U l        [        US   US   -
  R	                  5       R                  5       5      U l        OU R                  S:X  aF  US   R                  5       U l        [        US   R                  5       U R                  -
  5      U l        OU R                  S:X  a7  S	U l        [        US   R	                  5       R                  5       5      U l        OVU R                  S:X  aF  US   R                  5       U l        [        US   R                  5       U R                  -
  5      U l        U R                  S
:X  a  SU l        US   R                  5       U l	        US   R                  5       U R                  -
  U l
        U R                  R                  5        H  u  p4US   n[        X#   R                  5       5      nUS:  a  SnUS:X  a&  [        X#   R                  5       5      SS
1:X  a  SnOSnU(       d  Mb  [        X#   R!                  5       5      n[        X#   R#                  5       5      nXpR                  U   S'   XR                  U   S'   M     g)zInitialize model scales.

Sets model scaling factors using df.

Parameters
----------
initialize_scales: Boolean set the scales or not.
df: pd.DataFrame for setting scales.
Nr]   r   Tr!   r   r"   r   r   r         ?r   standardize   Fautor_   r   r   )r#   r=   r   r2   absrn   r;   rm   r<   r:   r>   rA   r   r(   ro   setmeanr   )	rM   r   r   r    r   r   n_valsr   r   s	            rN   r   Prophet.initialize_scalesg  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8KD.K*+Fz#f$rx()aV3"'K"&K{28==?+BHLLN+46%%d+D158%%d+E2 9rQ   c                    U R                   b  [        U R                   5      S:X  a  GO[        U R                   5      U R                  S   R                  5       :  n[	        U R                   5      U R                  S   R	                  5       :  nU(       d  U(       a  [        S5      eGOD[        [        R                  " U R                  R                  S   U R                  -  5      5      nU R                  S-   U:  a6  US-
  U l        [        R                  SR                  U R                  S95        U R                  S:  az  [        R                  " SUS-
  U R                  S-   5      R!                  5       R#                  [        5      nU R                  R$                  U   S   R'                  S5      U l         O.[(        R*                  " [(        R,                  " / 5      SS	9U l         [        U R                   5      S:  aT  [        R.                  " [        R0                  " U R                   U R2                  -
  U R4                  -  5      5      U l        g[        R0                  " S/5      U l        g)
a  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(   rn   rE   rm   r9   ri   r   r   shaper+   r)   rS   infor   linspaceroundr   iloctailr%   r&   r'   sortarrayr:   r>   r?   )rM   too_lowtoo_high	hist_size
cp_indexess        rN   set_changepoints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rQ   datesperiodseries_orderreturnc                    US:  d  [        S5      eU R                  [        R                  S9[        -  S-  nU[        R
                  -  S-  n[        R                  " U R                  S   SU-  45      n[        U5       HP  nXFS-   -  U-  n[        R                  " U5      USS2SU-  4'   [        R                  " U5      USS2SU-  S-   4'   MR     U$ )a  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)r9   to_numpyr   r   NANOSECONDS_TO_SECONDSpiemptyr   rangesincos)r   r   r   r   x_Tfourier_componentsrX   cs           rN   fourier_seriesProphet.fourier_series  s    & !899 NNN*.DD
S"%%i!mXXu{{1~q<7G&HI|$A1u&A+-66!9q!a%x(13q1q5A+~. % "!rQ   c                     U R                  XU5      n[        UR                  S   5       Vs/ s H  nSR                  XFS-   5      PM     nn[        R
                  " XWS9$ s  snf )a  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%   rj   )clsr   r   r   prefixfeaturesrX   r   s           rN   make_seasonality_features!Prophet.make_seasonality_features  sk      %%e\B 8>>!,-
-   Q/- 	 
 ||H66	
s   A!c           	      *   [         R                  " 5       nU R                  b  U R                  R                  5       nU R                  b^  [        U Vs1 s H  o3R                  iM     sn5      n[        X@R                  S9n[         R                  " X%4SS9nUR                  SSS9  U R                  b  UR                  [        R                  " UR                  R                  U R                  5      5         nUR!                  U5      n[         R                  " SU R                  [        R                  " U R                  R                  UR                  5      5         05      n[         R                  " X'4SS9nUR                  SSS9  U$ s  snf )ae  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%   rj   r/   copyrB   listyearr   concatr   rI   r   r   logical_notr`   r   r   )rM   r   all_holidaysxr   country_holidays_dfindex_to_dropholidays_to_adds           rN   construct_holiday_dataframe#Prophet.construct_holiday_dataframe  sc    ||~==$==--/L  ,e4effe45I"2#-B-B# 99l%H*/1L$$$$=##/(.. ((--d.F.FGM
 (,,];L ll433NN4#;#;(,\-A-A(BD, O 99l%D*/1L$$$$=5 5s   Fc           	      j  ^ [        U4S j5      n0 n[        R                  " TR                  R                  5      nUR                  5        GH  nUR                  R	                  5       n [        [        USS5      5      n[        [        USS5      5      n	[        [        USU R                  5      5      n
[        R                  " U
5      (       a  [        U R                  5      n
UR                  U;   a4  XFR                     U
:w  a"  [        SR                  UR                  S95      eU
S::  a  [        S5      eXUR                  '   [!        XS	-   5       Hs  n[        R"                  " U[%        US
9-   5      n UR'                  U5      nSR                  UR                  US:  a  SOS[+        U5      5      nUb	  SX>   U'   Mo  X>     Mu     GM     [        R,                  " U5      nU[/        UR0                  R3                  5       5         nUR0                   Vs/ s H  nUUR5                  S5      S      PM     nn[7        UR9                  5       5      nU R:                  c  [        R<                  " U5      U l        UUU4$ ! [         a    SnSn	 GNf = f! [(         a    Sn GNf = fs  snf )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                  J   > [         R                  " T R                  S   5      $ )Nr   )r   r|   r   )r   s   rN   <lambda>/Prophet.make_holiday_features.<locals>.<lambda>@  s    Q0HrQ   ra   r   rb   prior_scalezGHoliday {holiday!r} does not have consistent prior scale specification.)r`   Prior scale must be > 0r_   daysNz{}_delim_{}{}+-r   rv   )r   r%   DatetimeIndexr   date
itertuplesr   ri   getattrr9   r2   r5   r   isnanr`   r   r   r'   r	   get_locKeyErrorr   rj   sortedr   tolistsplitr   keysrI   r&   )rM   r   r/   expanded_holidaysprior_scales	row_indexrowr   lwuwpsoffset
occurrencelockeyholiday_featuresrs   prior_scale_listholiday_namess    `                 rN   make_holiday_featuresProphet.make_holiday_features0  s     ((HI $$UXX]]3	&&(CBna89na89 wsM43L3LMNBxx||4445{{l*|KK/HB/N ++16#++6+F  Qw !:;;(*%F+^^B1G,GH
#++J7C &,,KK!Q;CCK
 ?24%*3/%* ,) )F <<(9:+F3C3K3KDJFH-N O &--
- +A./- 	 
 \..01##+')yy'?D$!1=@@U  &   C
s*   ,,J=J!J0JJJ-,J-c                    U R                   b  [        S5      eU R                  USS9  Uc  [        U R                  5      nUc  U R
                  nUS::  a  [        S5      eUS;  a  [        S5      eUUSS	US
.U R                  U'   U $ )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   re   z+mode must be 'additive' or 'multiplicative'r   r   )r   r   r   r   mode)rE   rU   rp   r2   r5   r0   r9   rA   )rM   r    r   r   r  s        rN   add_regressorProphet.add_regressorw  s    < <<#BD D!!$!? 9 9:K<((D!67755JKK&&'
d# rQ   c                 n   U R                   b  [        S5      eUS;  a  U R                  USS9  Uc  U R                  nO[	        U5      nUS::  a  [        S5      eUS::  a  [        S5      eUc  U R                  nUS;  a  [        S	5      eUb  U R                  U5        UUUUUS
.U R                  U'   U $ )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.)ry   rz   r{   F)r   r   r   zFourier Order must be > 0re   z+mode must be "additive" or "multiplicative"r   fourier_orderr   r  r   )rE   rU   rp   r3   r2   r9   r0   r@   )rM   r    r   r  r   r  r   r  s           rN   add_seasonality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  rQ   c                     U R                   b  [        S5      e[        U5       H  nU R                  USS9  M     U R                  b-  [
        R                  SR                  U R                  US95        Xl        U $ )a  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.Frc   zHChanging country holidays from {country_holidays!r} to {country_name!r}.)rB   country_name)rE   rU   r   rp   rB   rS   warningr   )rM   r!  r    s      rN   add_country_holidaysProphet.add_country_holidays  s    ( <<#H  &l3D%%d5%A 4   ,NN$%)%:%:!-   !-rQ   c           	      R   / n/ n/ / S.nU R                   R                  5        H  u  pVU R                  US   US   US   U5      nUS   b  SXqUS      ) '   UR                  U5        UR	                  US   /UR
                  S   -  5        XFS	      R                  U5        M     U R                  US   5      n[        U5      S:  aW  U R                  US   U5      u  pyn
UR                  U5        UR	                  U	5        X@R                     R	                  U
5        U R                  R                  5        HV  u  pVUR                  [        R                  " X   5      5        UR                  US   5        XFS	      R                  U5        MX     [        U5      S:X  aY  UR                  [        R                  " S
[        R                  " UR
                  S   5      05      5        UR                  S5        [        R                  " USS9nU R!                  X$5      u  pX#X4$ )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.
re   r   r   r  r   r   r   r_   r  r|   r   axis)r@   r   r   appendr   r   r   r(   r  r1   rA   r%   rj   r   r|   r   regressor_column_matrix)rM   r   seasonal_featuresr  modesr    r   r   r/   holiday_priorsr  component_colss               rN   make_all_seasonality_features%Prophet.make_all_seasonality_features  s#   & 26  --335KD554ho&	H %&29:U#34556$$X.}%&)::<- ''- 6 33BtH=x=1**2d8X> 4Hm $$X./$$%,,];  00668KD$$R\\"(%;<m 45- ''- 9  !Q&$$grxx'<=>@#II&7a@ $ < <!
 !EErQ   c           	      P   [         R                  " [        R                  " UR                  S   5      UR
                   Vs/ s H  o3R                  S5      S   PM     snS.5      nU R                  b+  U R                  USU R                  R                  5       5      nS H  nU R                  XES-   X%   5      nU R                  R                  5        VVs/ s H  u  pgUS   U:X  d  M  UPM     nnnU R                  US	U-   U5      nX%   R                  US-   5        X%   R                  S	U-   5        M     X R                     R                  S5        [         R                  " US
   US   5      R                  S
S9n	S H  n
X;  d  M
  SX'   M     U	R!                  SSSSS9  [#        U	S   U	S   -   5      S:  a  [%        S5      eU R&                  bC  XR&                  R
                     n	U	R)                  U R&                  5      (       d  [%        S5      eX4$ s  snf s  snnf )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_   rv   r   col	componentr/   re   _termsr  extra_regressors_r2  r3  )level)rx   r   r|   Tignore)r'  r   errorsrx   r   z&A bug occurred in seasonal components.z*A bug occurred in constructing regressors.)r%   rj   r   aranger   r   r  rI   add_group_componentro   rA   r   r(  r1   crosstab
sort_indexr   rm   rU   rG   equals)rM   r*  r+  r   
componentsr  rr   regressors_by_moder-  r    s              rN   r)  Prophet.regressor_column_matrixV  sB   ( \\99.44Q78/@/H/H/H!	"1%/H#
 
 ##/11J(@(@(G(G(IKJ 3D118OU[J #'"7"7"="="?""?ha=D( "?  " 11/$68JLJ Kth/K2T9: 3 	  !((4uz+6

*5*
! 	 ?D)'($ ? 	G!T(K/0345 689:DEE$$0+,E,E,M,MNN!(()B)BCC LMM$$W"s   H
H"+H"c                    XS   R                  [        U5      5         R                  5       nUS   R                  5       n[	        U5      S:  a/  [
        R                  " XRS.5      n[
        R                  " X/5      nU$ )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.
r3  r2  r   r1  )r   r   r   ro   r(   r%   rj   r   )rM   r>  r    groupnew_comp
group_colss         rN   r:  Prophet.add_group_component  so     5::3u:FGLLNe_++-
z?Q||J$JKHJ#9:JrQ   c                    US:X  ae  SnXR                   ;   a$  [        R                  SR                  US95        U$ U(       a$  [        R                  SR                  US95        U$ Un U$ USL a  UnU$ USL a  SnU$ [	        U5      nU$ )ax  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@   rS   r   r   ri   )rM   r    argauto_disabledefault_orderr  s         rN   parse_seasonality_argsProphet.parse_seasonality_args  s     &=M)))55;VV5F$  @VV&  !.  D[)M
 	 E\M   HMrQ   c                     U R                   S   R                  5       nU R                   S   R                  5       nU R                   S   R                  5       nUR                  UR
                  R                  5       S      R                  5       nX!-
  [        R                  " SS9:  nU R                  SU R                  US5      nUS:  a)  SUU R                  U R                  SS	.U R                  S'   X!-
  [        R                  " S
S9:  =(       d    U[        R                  " SS9:  nU R                  SU R                  US5      nUS:  a)  SUU R                  U R                  SS	.U R                  S'   X!-
  [        R                  " S
S9:  =(       d    U[        R                  " SS9:  nU R                  SU R                  US5      nUS:  a*  SUU R                  U R                  SS	.U R                  S'   gg)aT  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   r{   
   g     v@Nr  r   )weeksr_   rz         ry      )rE   rn   rm   diffr   r   nonzeror%   	TimedeltarK  r,   r3   r0   r@   r-   r.   )	rM   firstlastr   min_dtyearly_disabler  weekly_disabledaily_disables	            rN   set_auto_seasonalities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' rQ   c                 :   U S   R                  5       U S   R                  5       p!U S   R                  U   U S   R                  U   -
  nU S   R                  U   U S   R                  U   -
  U-  nU S   R                  U   X@S   R                  U   -  -
  nXE4$ )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         rN   linear_growth_initProphet.linear_growth_init
  s    $ D"BtHOO$5BsGLLr#w||B//
^  $r*~':':2'>>!CzN#aS',,r*:&::vrQ   c                 T   U S   R                  5       U S   R                  5       p!U S   R                  U   U S   R                  U   -
  nU S   R                  U   nU S   R                  U   n[        SU-  [	        SU-  U S   R                  U   5      5      n[        SU-  [	        SU-  U S   R                  U   5      5      nXF-  nXW-  n	[        X-
  5      S::  a  SU-  n[        R                  " US-
  5      n
[        R                  " U	S-
  5      nX-  X-
  -  nX-
  U-  nX4$ )	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_   )r_  r`  r   rm   rn   r   r   log)r   ra  rb  rc  C0C1y0y1r0r1L0L1re  rd  s                 rN   logistic_growth_init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rw<4BVVBF^VVBF^ FbgWMvrQ   c                 2    SnU S   R                  5       nX4$ )aq  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   rd  re  s      rN   flat_growth_initProphet.flat_growth_initL  s"    " zN!trQ   r   c                    SU;  d  SU;  a  [        S5      eXS   R                  5          R                  5       nUR                  S   S:  a  [        S5      e[        R
                  " [        R                  " US   R                  5       SS95      R                  5       U l	        U R                  USS	9U l        U R                  5         U R                  U R                  5      u  pEpgX`l        Xpl        [!        U5      U l        U R%                  5         U R&                  S
;   a.  [(        R*                  " U R                  R                  S   5      nOU R                  S   n[-        U R                  R                  S   [/        U R0                  5      UR                  S   U R2                  [4        U R&                  R7                  5          R8                  U R                  S   U R                  S   U R0                  UUUS   US   US9$ )z
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   )r\   r^   r   r_   r   r   rx   r   )rc  SKtautrend_indicatorr   r   t_changeXsigmass_as_mr   )r9   notnullr   r   r%   r'   r&   ro   r   rF   r   rE   r\  r.  rG   rH   r   rJ   r   r#   r   r|   r   r(   r?   r4   r   uppervalue)	rM   r   kwargsrE   r*  r  r-  r+  r   s	            rN   
preprocessProphet.preprocessa  s    N2'  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
 	
rQ   num_total_regressorsc                    U R                   S:X  a  U R                  U R                  5      u  p#O[U R                   S:X  a  U R                  U R                  5      u  p#O-U R                   S:X  a  U R	                  U R                  5      u  p#[        WW[        R                  " U R                  5      [        R                  " U5      SS9$ )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.
r\   r^   r]   r   )rd  re  deltabeta	sigma_obs)
r#   rf  rE   ru  rr  r   r   
zeros_liker?   r|   )rM   r  rd  re  s       rN   calculate_initial_params Prophet.calculate_initial_params  s     ;;("**4<<8DAq[[F"((6DAq[[J&,,T\\:DA-- 3 34./
 	
rQ   c                    U R                   b  [        S5      eU R                  " U40 UD6nU R                  UR                  5      n[
        R                  " U5      n[
        R                  " U5      nU R                   S   R                  5       U R                   S   R                  5       :X  az  U R                  S:X  d  U R                  S:X  aZ  X`l
        SU R                  S'   U R                   H4  n[        R                  " U R                  U   /5      U R                  U'   M6     O`U R                  S:  a.  U R                  R                  " XeU R                  40 UD6U l
        O"U R                  R                   " Xe40 UD6U l
        U R                  R"                  U l        [%        U R&                  5      S:X  a  U R                  S   U R                  S	   R)                  S
5      -   U R                  S'   [        R*                  " U R                  S	   R,                  5      R)                  S5      U R                  S	'   U $ )aA  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   r\   r^   g&.>r  r   rd  r  r   )r   r_   )rE   rU   r  r  ry  dataclassesasdictrn   rm   r#   rD   r   r   r6   r   samplingfitrC   r(   r$   reshaper|   r   )rM   r   r  model_inputsinitial_paramsdat	stan_initpars           rN   r  Prophet.fit  s   2 <<# 8 9 9 r4V466|~~F  .&&~6	<<  "dll3&7&;&;&==(DKK6,A#K'+DKK${{#%88T[[-=,>#?C  #"++44YTEVEVaZ`aDK++//	I&IDK))22t  !Q& C 4;;w#7#?#?#CC KK %'HHT[[-A-G-G$H'.ww'7 KK  rQ   
vectorizedc                 Z   U R                   c  [        S5      eUc  U R                   R                  5       nO=UR                  S   S:X  a  [	        S5      eU R                  UR                  5       5      nU R                  U5      US'   U R                  U5      nU R                  (       a  U R                  X5      nOSnSS/nSU;   a  UR                  S5        U R                  (       a  UR                  S5        [        R                  " X   XC4S	S
9nUS   S	US   -   -  US   -   US'   U$ )a  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.rw   r   r   r   r_   r&  r   rx   r~   )rE   rU   r   r   r9   r   predict_trendpredict_seasonal_componentsr8   predict_uncertaintyr(  r=   r%   r   )rM   r   r  seasonal_components	intervalscolsdf2s          rN   predictProphet.predict  s%     <<566:""$Bxx{a !9::%%bggi0B((,7">>rB##00@II gB;KKKK ii9BKGC(>$? ?@&'( 	F 
rQ   c                     USSS24   U S   :*  U-  nUR                  SS9U-   nXT* -  R                  SS9U-   nX`-  U-   $ )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   deltasrd  re  changepoint_tsdeltas_tk_tm_ts           rN   piecewise_linearProphet.piecewise_linear  s^      #47+q|;vElll"Q&/)..A.6:w}rQ   c                 X   [         R                  " [         R                  " U5      [         R                  " U5      U-   45      n[         R                  " [        U5      5      n[        U5       H2  u  pX-
  [         R                  " U5      -
  SXh   XhS-      -  -
  -  Xx'   M4     U[         R                  " U 5      -  n
U[         R                  " U 5      -  n[        U5       H%  u  pX	:  nX==   X,   -  ss'   X==   X|   -  ss'   M'     US[         R                  " U
* X-
  -  5      -   -  $ )aT  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cumsumr|   r(   	enumerater  	ones_likeexp)r   r   r  rd  re  r  k_cumgammasrX   t_sr  r  sindxs                 rN   piecewise_logisticProphet.piecewise_logistic%  s   $ a 0"))F2Ca2GHI#n-./FAWrvvf~-58eEl224 I 0 ",,q/!",,q/!/FA8DI"II"I 0 a"&&#!12233rQ   c                 8    U[         R                  " U 5      -  nU$ )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   re  r  s      rN   
flat_trendProphet.flat_trendG  s     ",,q/!
rQ   c                 2   [         R                  " U R                  S   5      n[         R                  " U R                  S   5      n[         R                  " U R                  S   SS9n[         R                  " US   5      nU R                  S:X  a  U R                  XTX#U R                  5      nOTU R                  S:X  a#  US	   nU R                  XWXBX0R                  5      nO!U R                  S
:X  a  U R                  XS5      nWU R                  -  US   -   $ )zPredict trend using the prophet model.

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

Returns
-------
Vector with trend on prediction dates.
rd  re  r  r   r&  r   r\   r]   r   r^   r   )
r   nanmeanrD   r   r#   r  r?   r  r  r<   )rM   r   rd  re  r  r   rw   r   s           rN   r  Prophet.predict_trendW  s     JJt{{3'(JJt{{3'(DKK0q9HHRW;;("))!Q4;N;NOE[[J&\"C++1&9&9;E[[F"OOA)Et||#bk11rQ   c                 ~   U R                  U5      u  p#pCU R                  (       a*  SSU R                  -
  -  S-  nSSU R                  -   -  S-  nUR                  n0 nUR                   H  n	U R
                  S   XI   R                  -  n
[        R                  " XzR                  5       5      nXR                  S   ;   a  XR                  -  n[        R                  " USS9X'   U R                  (       d  M  U R                  UWSS9XS-   '   U R                  UWSS9XS	-   '   M     [        R                  " U5      $ )
zPredict seasonality components, holidays, and added regressors.

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

Returns
-------
Dataframe with seasonal components.
d   r   r   r  rf   r_   r&  r   r   )r.  r8   r7   r   r   rD   r   matmul	transposerH   r<   r  
percentiler%   rj   )rM   r   r*  _r-  lower_pupper_pr}  datar3  beta_ccomps               rN   r  #Prophet.predict_seasonal_componentss  s@    ..r2 	0n ##S4#6#667!;GS4#6#667!;G$$'//I[[(>+D+K+KKF99Q 0 0 23D00<<$ jjA6DO'''-1__' .= .)* .2__' .= .)* 0 ||D!!rQ   c                 N   U R                  X5      nSSU R                  -
  -  S-  nSSU R                  -   -  S-  n0 nS HM  nU R                  X7   USS9USR                  U5      '   U R                  X7   USS9USR                  U5      '   MO     [        R
                  " U5      $ )	zPrediction 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   r~   rw   r_   r&  z{}_lowerz{}_upper)sample_posterior_predictiver7   r  r   r%   rj   )rM   r   r  
sim_valuesr  r  seriesr  s           rN   r  Prophet.predict_uncertainty  s     55bE
t2223a7t2223a7$C-1__q .= .2F:$$S)*-1__q .= .2F:$$S)* % ||F##rQ   c                 t   U R                   S   R                  S   n[        S[        [        R
                  " U R                  [        U5      -  5      5      5      nU R                  U5      u  pVpv/ / S.n[        U5       H~  n	U(       a  U R                  UUU	US   US   US9n
O2[        U5       Vs/ s H  nU R                  UUU	US   US   S9PM     n
nU H!  nU
 H  nX   R                  X   5        M     M#     M     UR                  5        H  u  p[        R                  " U5      X'   M     U$ s  snf )	a  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.
rd  r   r_   r  rx   r   )r   r*  	iterationr  r  	n_samples)r   r*  r  r  r  )rD   r   rm   ri   r   ceilr8   r2   r.  r   sample_model_vectorizedsample_modelr(  r   column_stack)rM   r   r  n_iterationssamp_per_iterr*  r  r-  r  rX   simsr  simrd  vs                  rN   r  #Prophet.sample_posterior_predictive  si    {{3'--a0As277$$u\'::$
   
 ..r2 	0n !2.
|$A33&7&'78&'=>+ 4    %]3  4! %%*;"#*+;<*+AB &   4   "CO**384   ") %. $$&DAOOA.JM 's   2#D5c                    U R                  X5      nU R                  S   U   n[        R                  " UR                  XtR                  -  5      U R
                  -  n[        R                  " UR                  XuR                  -  5      n	U R                  S   U   n
[        R                  R                  SXR                  S   5      U R
                  -  nUSU	-   -  U-   U-   U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'].
r  r  r   r_   r  )	sample_predictive_trendrD   r   r  r   r<   randomnormalr   )rM   r   r*  r  r  r  rw   r  Xb_aXb_msigmanoises               rN   r  Prophet.sample_model  s     ,,R;{{6"9-yy*11

*,.2ll;yy*114**3DEK(3		  E88A;7$,,F QX&-5
 	
rQ   r*  r  r  r  r  c                    U R                   S   U   n[        R                  " UR                  XtR                  -  5      U R                  -  n[        R                  " UR                  XuR                  -  5      n	U R                  XU5      n
U R                   S   U   n[        R                  R                  SXR                  5      U R                  -  n/ n[        X5       H%  u  pUR                  USU	-   -  U-   U-   US.5        M'     U$ )a  Simulate observations from the extrapolated generative model. Vectorized version of sample_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.
n_samples: Number of future paths of the trend to simulate.

Returns
-------
List (length n_samples) of dictionaries with arrays for trend and yhat, each ordered like df['t'].
r  r  r   r_   r  )rD   r   r  r   r<   "sample_predictive_trend_vectorizedr  r  r   zipr(  )rM   r   r*  r  r  r  r  r  r  r  trendsr  noise_termssimulationsrw   r  s                   rN   r  Prophet.sample_model_vectorized   s    2 {{6"9-yy*11zz)+-1\\:yy*114**3DE88	RK(3ii&&q%>M4LET*T1E9   5
 rQ   c                    U R                   S   U   nU R                   S   U   nU R                   S   U   n[        R                  " US   5      nUR                  5       nUS:  a:  [	        U R
                  5      n[        R                  R                  XS-
  -  5      n	OSn	U	S:  a9  S[        R                  R                  U	5      US-
  -  -   n
U
R                  5         O/ n
[        R                  " [        R                  " U5      5      S-   n[        R                  R                  SX5      n[        R                  " U R
                  U
45      n[        R                  " X\45      nU R                  S:X  a  U R                  XeX4U5      nOKU R                  S	:X  a  US
   nU R!                  XoXSUU5      nO!U R                  S:X  a  U R#                  Xd5      nWU R$                  -  US   -   $ )zSimulate 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'].
rd  re  r  r   r_   r   :0yE>r\   r]   r   r^   r   )rD   r   r   rm   r(   r?   r  poissonrandr   r   r   laplacer  r#   r  r  r  r<   )rM   r   r  rd  re  r  r   rc  rx  	n_changeschangepoint_ts_newlambda_
deltas_newr  rw   r   s                   rN   r  Prophet.sample_predictive_trend*  s    KKY'KKY'W%i0HHRWEEG q5D''(A		))!1u+6IIq=!"RYY^^I%>!a%%H!H##%!# ''"&&.)D0 YY&&q'=
 )<)<);)= > 45;;("))!Q>JE[[J&\"C++AFq,:<E[[F"OOA)Et||#bk11rQ   c                    U R                   S   U   nU R                   S   U   nU R                   S   U   nU R                  S:X  a+  U R                  US   R                  XFXPR                  5      nOU R                  S:X  a9  U R                  US   R                  US   R                  XFXPR                  5      nO6U R                  S:X  a   U R                  US   R                  U5      nO[        eU R                  XU5      n[        R                  " XrS	45      U-   U R                  -  [        R                  " US
   R                  US	45      -   $ )a{  Sample draws of the future trend values. Vectorized version of sample_predictive_trend().

Parameters
----------
df: Prediction dataframe.
iteration: Int sampling iteration to use parameters from.
n_samples: Number of future paths of the trend to simulate.

Returns
-------
Draws of the trend values with shape (n_samples, len(df)). Values are on the scale of the original data.
r  re  rd  r\   r   r]   r   r^   r_   r   )rD   r#   r  r   r?   r  r  NotImplementedError_sample_uncertaintyr   tiler<   )	rM   r   r  r  r  re  rd  expecteduncertaintys	            rN   r  *Prophet.sample_predictive_trend_vectorized_  s+    W%i0KKY'KKY';;(",,RW^^VK^K^_H[[J&..3< 0 7 7AGZGZH [[F"r#w~~q9H%%..riHWWX1~.<LGGBwK&&A78	
rQ   c                    US   R                  5       S::  a#  [        R                  " U[        U5      45      nU$ UR                  US   S:     n[        U5      nUS:  a(  [        R
                  " US   5      R                  5       nO1[        R
                  " U R                  S   5      R                  5       n[        U R                  5      U-  nU R                  S   U   n	U R                  S   U   n
U R                  S   U   n[        R                  " [        R                  " U	5      5      S-   nU R                  S:X  a1  U R                  XXbS9nUR                  SS	9R                  SS	9nXG-  nOU R                  S
:X  aA  U R                  XXbS9nU R                  UU	UU
US   R                  US   R                  UUS9nO.U R                  S:X  a  [        R                  " X&45      nO[         eUS   R#                  5       S::  aH  [        R                  " U[        R$                  " US   S:*  5      45      n[        R&                  " X/SS	9nU$ )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_   r  re  rd  r  r\   )r  r&  r]   r   )matr  rd  re  r   t_timen_lengthsingle_diffr^   )rm   r   r|   r(   r  rS  r   rE   r?   rD   r   r#   _make_trend_shift_matrixr  _logistic_uncertaintyr   r  rn   r  r  )rM   r   r  r  uncertainties	future_dfr  r  change_likelihoodr  re  rd  
mean_deltar  past_uncertaintys                  rN   r  Prophet._sample_uncertainty  s'    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3JS[3q #


 2 9 9q 9 A,
*33JS[3q $ : :!!,/66$S>00% + !; 	! & "))> ?))#w{{}!#%88Yr#w!|8L,M#N  "0@/PWX YrQ   r  
likelihoodfuture_lengthc                 .   [         R                  R                  X24S9U:  n[         R                  R                  SXR                  S9nXT-  n[         R
                  " [         R                  " [        U5      S45      U/5      SS2SS24   nXv-   S-  nU$ )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   hstackr|   r(   )r  r  r  r  bool_slope_changeshift_valuesr  n_mats           rN   r	   Prophet._make_trend_shift_matrix  s     II--I3M-NQ[[yy((J=T=T(U.		288SXqM2C89!SbS&A{a
rQ   c                    Uc$  [         R                  " U5      R                  5       n[         R                  " SSU-   U5      n/ nU H0  nUR	                  [         R
                  " XW:  5      S   S   5        M2     [         R                  " [        U5      5      nXU'   [         R                  " UR                  SS5      USS9nX4$ )zt
Creates a matrix of slope-deltas where these changes occured in training data according to the trained prophet obj
r   r_   r   r&  )
r   rS  r   r9  r(  wherer|   r(   repeatr  )	r  r?   r  n_rowr  	prev_timeidxschangepointprev_deltass	            rN   _make_historical_mat_time!Prophet._make_historical_mat_time  s    
 ''&/..0KIIa[+>	)KKK!89!<Q?@ *hhs9~."Dii 3 3Ar :EJ%%rQ   r  r  rd  re  r   r  r  r  c	                 r   S n	U R                  X R                  U[        U5      U5      u  p[        R                  " X/SS9n[        R                  " X/5      n[        R                  " [        R
                  " UR                  S   S45      U-  [        R                  " U[        R                  " USS9U-   S5      4SS9nU	" U5      n[        R                  " U5      n[        UR                  S   5       HO  nUU   U-
  [        R                  " USS2SU24   SS9-
  nSUSS2U4   USS2US-   4   -  -
  nUU-  USS2U4'   MQ     UR                  SS9U-   SS2U* S24   nUR                  SS9U-   SS2U* S24   nUS[        R                  " U* UU-
  -  5      -   -  nUUR                  SS9-
  $ )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                    U S:H  n[         R                  " U) [         R                  " UR                  S   5      S5      n[         R                  R                  USUS9  U [         R                  " UR                  S   5      S S 2S 4   U4   $ )Nr   r_   )r'  out)r   r  r9  r   maximum
accumulate)arrmaskidxs      rN   ffill,Prophet._logistic_uncertainty.<locals>.ffill  ss    !8D((D5"))DJJqM":A>CJJ!!#A3!7ryy1.q$w7<==rQ   r_   r&  r   N)r#  r?   r(   r   r  onesr   r  r  r  r   r  r  r   )rM   r  r  rd  re  r   r  r  r  r-  historical_mathistorical_timefull_t_timer  k_cum_br  rX   r   ksr  r  sample_trendss                         rN   r
  Prophet._logistic_uncertainty  s   @	> +/*H*HQdQdflnqrunv  yD  +E'nnn2;nno%>? 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9rQ   c                 b    U R                  UR                  5       5      nU R                  X5      $ )aw  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  )rM   r   r  s      rN   predictive_samplesProphet.predictive_samples  s+    , !!"''),//??rQ   c                     [         R                  " U5      R                  5       (       a  [         R                  O[         R                  nU" U/UQ70 UD6$ )a:  
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   rl   nanpercentiler  )rM   aargsr  fns        rN   r  Prophet.percentile-  s>     "$!!2!2R!%d%f%%rQ   c                    U R                   c  [        S5      eUc=  [        R                  " U R                   R	                  S5      5      nUc  [        S5      eU R                   R                  5       n[        R                  " UUS-   US9nXUU:     nUSU nU(       a6  [        R                  " [        R                  " U R                   5      U45      n[        R                  " SU05      $ )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_   )r:   periodsfreqr   )rF   rU   r%   
infer_freqr   rm   
date_ranger   r  r   rj   )rM   rB  rC  include_history	last_dater   s         rN   make_future_dataframeProphet.make_future_dataframe8  s     %566<==!3!3!8!8!;<D| 899&&**,	aK i'(hwNNBHHT-?-?$@%#HIE||T5M**rQ   c	                     [        XX#XEUXxS9	$ )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.
)	re  fcstaxr  plot_capxlabelylabelfigsizeinclude_legend)r   )	rM   rK  rL  r  rM  rN  rO  rP  rQ  s	            rN   r   Prophet.plot\  s    ( "V
 	
rQ   c           
          [        XX#XEUS9$ )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.
)re  rK  r  rM  weekly_startyearly_startrP  )r   )rM   rK  r  rM  rT  rU  rP  s          rN   r   Prophet.plot_componentsv  s    2 ;%
 	
rQ   )$r4   r+   r$   r?   rH   rB   r.   rA   rJ   r#   rE   rF   r/   r1   r5   r7   r=   r6   r)   rD   r   r@   r0   r3   r*   r   rC   r:   r>   rG   rI   r8   r-   r;   r<   r,   )r\   N   皙?r   r   r   Nrf         $@rY  g?r   rX  i  Nr!   N)TTT)F)Nr   N)NNN)NT)r   )r_   N)N)T)DT)NTTr   r   )rN     F)TTr   r   N)G__name__
__module____qualname____firstlineno__r   __annotations__r   rO   rL   rK   rp   r   r   r   staticmethodr%   r&   r   ri   r2   r   r   float64r   classmethodr   r   r  r  r  r#  r.  r)  r:  rK  r\  rf  rr  ru  rj   r   r  r   r  r  r   r  r  r  r  r  r  r  r
   ndarrayr  r  r   r  r  r  r  r	  r#  r
  r8  r  rH  r   r   __static_attributes__ rQ   rN   r   r      s_   4p !%%$'$(!%$( $#'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

?#	$(T32j
R\\ 
c 
^a 
jljtjt 
@7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
rQ   r   )*
__future__r   r   r   r  loggingcollectionsr   r   r   r   datetimer	   typingr
   r   r   numpyr   pandasr%   numpy.typingr   prophet.make_holidaysr   r   prophet.modelsr   r   r   r   r   prophet.plotr   r   	getLoggerrS   setLevelINFOr   objectr   rf  rQ   rN   <module>rv     sl    A @   0   $ $     E e e 0			9	%  + w
f w
rQ   