
    %g$Z                         d dl mZmZmZ d dlZd dlmZ d dlmZ d dl	Z
d dlZd dlZ ej                  d      Zd ZddZd Zdd	Zdd
Zd Zd Zd Zd Zd Zd Zd Zd Zd Zy)    )absolute_importdivisionprint_functionN)tqdm)deepcopyprophetc                    | d   j                         |z
  }|| d   j                         k  rt        d      |g}|d   t        | d         |z   k\  r||z  }| d   |kD  | d   ||z   k  z  j                         s7|| d   j                         kD  r!| | d   |k     j                         d   }||z
  }|j	                  |       |d   t        | d         |z   k\  r|dd }t        |      dk(  rt        d      t        j                  dj                  t        |      |d   |d                t        t        |            S )aK  Generate cutoff dates

    Parameters
    ----------
    df: pd.DataFrame with historical data.
    horizon: pd.Timedelta forecast horizon.
    initial: pd.Timedelta window of the initial forecast period.
    period: pd.Timedelta simulated forecasts are done with this period.

    Returns
    -------
    list of pd.Timestamp
    dszLess data than horizon.Nr   zMLess data than horizon after initial window. Make horizon or initial shorter.z2Making {} forecasts with cutoffs between {} and {})maxmin
ValueErroranyappendlenloggerinfoformatlistreversed)dfhorizoninitialperiodcutoffresultclosest_dates          P/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/prophet/diagnostics.pygenerate_cutoffsr      sX    X\\^g%F4233XF
*BtH/
/&T(V#4FW4D(DEJJL4&!"T(f"4599;DA%/f *BtH/
/ CR[F
6{a/
 	
 KKDKKFVBZ   !!    c           
           j                   t        d       j                   j                         j                  d      t	        j
                        ddg j                  rj                  ddg       |7t        |t              r|g}j                  |D cg c]	  }|vs| c}       d	}	 j                  j                         D ]  }
t        |	|
d
         }	 t	        j
                  t        |	      dz         }|Q|dz  nt	        j
                  |      }|t        dz  |      nt	        j
                  |      }t        ||      }nrt        |      d   j                         k  rt        d      d   j                         z
  }t        |      |kD  rt        d      |d   d   j                         z
  }||k  r0dj!                  |	      }|dz  }|dz  }t"        j%                  |       |r
h d}|dk(  rt&        j(                  j+                         }n|dk(  rt&        j(                  j-                         }nd|dk(  r%	 ddlm}  |       }|j5                   g      \   n:t7        |d      r|}n+dj!                  dj9                  |            }t        |       fd|D        }t;        | }t"        j=                  d|        |j>                  t@        g| }|dk(  r;|jC                  |      }n)|stE        |      n|D cg c]  }tA         |       }}t	        jF                  |d      j                  d      S c c}w # t2        $ r}t3        d      |d}~ww xY wc c}w ) aO
  Cross-Validation for time series.

    Computes forecasts from historical cutoff points, which user can input.
    If not provided, begins from (end - horizon) and works backwards, making
    cutoffs with a spacing of period until initial is reached.

    When period is equal to the time interval of the data, this is the
    technique described in https://robjhyndman.com/hyndsight/tscv/ .

    Parameters
    ----------
    model: Prophet class object. Fitted Prophet model.
    horizon: string with pd.Timedelta compatible style, e.g., '5 days',
        '3 hours', '10 seconds'.
    period: string with pd.Timedelta compatible style. Simulated forecast will
        be done at every this period. If not provided, 0.5 * horizon is used.
    initial: string with pd.Timedelta compatible style. The first training
        period will include at least this much data. If not provided,
        3 * horizon is used.
    cutoffs: list of pd.Timestamp specifying cutoffs to be used during
        cross validation. If not provided, they are generated as described
        above.
    parallel : {None, 'processes', 'threads', 'dask', object}
        How to parallelize the forecast computation. By default no parallelism
        is used.

        * None : No parallelism.
        * 'processes' : Parallelize with concurrent.futures.ProcessPoolExectuor.
        * 'threads' : Parallelize with concurrent.futures.ThreadPoolExecutor.
            Note that some operations currently hold Python's Global Interpreter
            Lock, so parallelizing with threads may be slower than training
            sequentially.
        * 'dask': Parallelize with Dask.
           This requires that a dask.distributed Client be created.
        * object : Any instance with a `.map` method. This method will
          be called with :func:`single_cutoff_forecast` and a sequence of
          iterables where each element is the tuple of arguments to pass to
          :func:`single_cutoff_forecast`

          .. code-block::

             class MyBackend:
                 def map(self, func, *iterables):
                     results = [
                        func(*args)
                        for args in zip(*iterables)
                     ]
                     return results
                     
    disable_tqdm: if True it disables the progress bar that would otherwise show up when parallel=None
    extra_output_columns: A String or List of Strings e.g. 'trend' or ['trend'].
         Additional columns to 'yhat' and 'ds' to be returned in output.

    Returns
    -------
    A pd.DataFrame with the forecast, actual value and cutoff.
    Nz^Model has not been fit. Fitting the model provides contextual parameters for cross validation.Tdropr
   yhat
yhat_lower
yhat_upperg        r   z daysg      ?   zEMinimum cutoff value is not strictly greater than min date in historyzdMaximum cutoff value is greater than end date minus horizon, no value for cross-validation remainingr   z"Seasonality has period of {} days z%which is larger than initial window. zConsider increasing initial.>   daskthreads	processesr)   r*   r(   )
get_clientz6parallel='dask' requires the optional dependency dask.mapzB'parallel' should be one of {} for an instance with a 'map' methodz, c              3   ,   K   | ]  }|f  y wN ).0r   r   r   modelpredict_columnss     r   	<genexpr>z#cross_validation.<locals>.<genexpr>   s$      , %/B ,s   zApplying in parallel with %saxis)$history	Exceptioncopyreset_indexpd	Timedeltauncertainty_samplesextend
isinstancestrseasonalitiesvaluesr   r   r   r   r   r   warning
concurrentfuturesThreadPoolExecutorProcessPoolExecutordask.distributedr+   ImportErrorscatterhasattrjoinzipr   r,   single_cutoff_forecastgatherr   concat)r1   r   r   r   parallelcutoffsdisable_tqdmextra_output_columnsc
period_maxsseasonality_dtend_date_minus_horizonmsgvalidpoolr+   e	iterablespredictsr   r   r2   s   ``                   @@r   cross_validationr_   =   sy   v }}xyy					)	)t	)	4Bll7#GVnO  l;<'*C0$8#9 +?\a1OC[\] J  '') 2Qx[1
2\\#j/G";<N"(.wbll66J 18CG^,g& 	 #2w@ w<2d8<<>)dee!#D'!9w<00  D  E  E!*r$x||~-
 6==jIC::C11CNN30y %%88:D$%%99;D=7 <Db%[1IBXu%D""(&5)9": S/!,#*,	O	2D94882?Y?v{{8,H
 1=4='
 #2ufgO
 
 99XA&222==_  ]b  =! #5 6;<==0
s*   "	M,MM$  N$	M>-M99M>c                     t        ||      }| | d   |k     }|j                  d   dk  rt        d       |j                  |fi |j                   | d   |kD  | d   ||z   k  z  }dg}|j
                  dk(  r.|j                  d       |j                  r|j                  d       |j                  |j                  j                                |j                  |j                  j                         D 	cg c]  }	|	d   |	d    c}	       |j                  | |   |         }
t        j                  |
|   | |   d	g   j!                  d
      t        j"                  d|gt%        |
      z  i      gd      S c c}	w )a  Forecast for single cutoff. Used in cross validation function
    when evaluating for multiple cutoffs either sequentially or in parallel .

    Parameters
    ----------
    df: pd.DataFrame.
        DataFrame with history to be used for single
        cutoff forecast.
    model: Prophet model object.
    cutoff: pd.Timestamp cutoff date.
        Simulated Forecast will start from this date.
    horizon: pd.Timedelta forecast horizon.
    predict_columns: List of strings e.g. ['ds', 'yhat'].
        Columns with date and forecast to be returned in output.

    Returns
    -------
    A pd.DataFrame with the forecast, actual value and cutoff.

    r
   r      z@Less than two datapoints before cutoff. Increase initial window.logisticcapfloorcondition_nameyTr"   r      r4   )prophet_copyshaper7   fit
fit_kwargsgrowthr   logistic_floorr=   extra_regressorskeysr@   rA   predictr:   rO   r9   	DataFramer   )r   r1   r   r   r2   m	history_cindex_predictedcolumnspropsr$   s              r   rM   rM      s   . 	UF#A2d8v%&IqA'
 	
 
AEE)(u''($x&(RX'9I-IJOfGxx:uNN7#NN1%%**,-NN__++-0!". 	0 1 99R(12D 99_
?SE"..D.9
h3t9 456 	 0s   6E;c                    | j                   t        d      | j                  rB| j                  }|6t	        | j                   d   | j                   d   |k           }|||k     }nd}| j                  | j                  | j                  | j                  |ddd| j                  | j                  | j                  | j                  | j                  | j                  | j                  | j                   | j"                  | j$                  | j$                  j'                         nd      }t)        | j*                        |_        t)        | j,                        |_        t)        | j.                        |_        |S )aZ  Copy Prophet object

    Parameters
    ----------
    m: Prophet model.
    cutoff: pd.Timestamp or None, default None.
        cuttoff Timestamp for changepoints member variable.
        changepoints are only retained if 'changepoints <= cutoff'

    Returns
    -------
    Prophet class object with the same parameter with model variable
    Nz,This is for copying a fitted Prophet object.r
   F)rl   n_changepointschangepoint_rangechangepointsyearly_seasonalityweekly_seasonalitydaily_seasonalityholidaysholidays_modeseasonality_modeseasonality_prior_scalechangepoint_prior_scaleholidays_prior_scalemcmc_samplesinterval_widthr<   stan_backend)r6   r7   specified_changepointsrz   r   	__class__rl   rx   ry   r~   r   r   r   r   r   r   r   r<   r   get_typer   rn   r@   country_holidays)rr   r   rz   last_history_datem2s        r   rh   rh     sK    	yyFGG~~ #AIIdOAIIdOv4M$N O'7H(HIL 
xx''--!  oo++ ! 9 9 ! 9 933^^''11)*)CANN##%' 
 
B, #1#5#56B0B"1#5#56BIr    c                    g d}||}d| vsd| vrd|v r|j                  d       t        t        |            t        |      k7  rt        d      t        |      j	                  t        |            st        dj                  |            | j                         }|rg|d   j                  j                  d	      j                  t              |d
   j                  j                  d	      j                  t              z
  |d<   n|d   |d
   z
  |d<   |j                  dd       d|v rJ|d   j                         j                         dk  r&t        j                  d       |j                  d       t        |      dk(  ryt        ||j                   d   z        }|dk\  r%t#        |d      }t        ||j                   d         }i }|D ]  } t%        |      ||      ||<    ||d      }	t'        dt        |            D ]J  }
|||
      }t)        j*                  |	d   j,                  |d   j,                        sJ |||
      |	||
   <   L |	S )a  Compute performance metrics from cross-validation results.

    Computes a suite of performance metrics on the output of cross-validation.
    By default the following metrics are included:
    'mse': mean squared error
    'rmse': root mean squared error
    'mae': mean absolute error
    'mape': mean absolute percent error
    'mdape': median absolute percent error
    'smape': symmetric mean absolute percentage error
    'coverage': coverage of the upper and lower intervals

    A subset of these can be specified by passing a list of names as the
    `metrics` argument.

    Metrics are calculated over a rolling window of cross validation
    predictions, after sorting by horizon. Averaging is first done within each
    value of horizon, and then across horizons as needed to reach the window
    size. The size of that window (number of simulated forecast points) is
    determined by the rolling_window argument, which specifies a proportion of
    simulated forecast points to include in each window. rolling_window=0 will
    compute it separately for each horizon. The default of rolling_window=0.1
    will use 10% of the rows in df in each window. rolling_window=1 will
    compute the metric across all simulated forecast points. The results are
    set to the right edge of the window.

    If rolling_window < 0, then metrics are computed at each datapoint with no
    averaging (i.e., 'mse' will actually be squared error with no mean).

    The output is a dataframe containing column 'horizon' along with columns
    for each of the metrics computed.

    Parameters
    ----------
    df: The dataframe returned by cross_validation.
    metrics: A list of performance metrics to compute. If not provided, will
        use ['mse', 'rmse', 'mae', 'mape', 'mdape', 'smape', 'coverage'].
    rolling_window: Proportion of data to use in each rolling window for
        computing the metrics. Should be in [0, 1] to average.
    monthly: monthly=True will compute horizons as numbers of calendar months 
        from the cutoff date, starting from 0 for the cutoff month.

    Returns
    -------
    Dataframe with a column for each metric, and column 'horizon'
    )msermsemaemapemdapesmapecoverageNr%   r&   r   z-Input metrics must be a list of unique valuesz Valid values for metrics are: {}r
   Mr   r   T)inplacer   rf   g:0yE>z"Skipping MAPE because y close to 0r   rg   )remover   setr   issubsetr   r8   dt	to_periodastypeintsort_valuesabsr   r   r   ri   r   evalrangenparray_equalrA   )r   metricsrolling_windowmonthlyvalid_metricsdf_mwdfsmetricresires_ms               r   performance_metricsr   F  s<   ^ QMB,b"8zW?Tz"
3w<CL(HIIw<  ]!34.55mD
 	
 779Dt*--11#6==cBT(^EVEVE`E`adEeElElmpEqqYt*tH~5YY-T#Y]]_002T989v
7|qNTZZ]*+AAv1I4::a=!
C ,"d6l4+F,
gaj/C1c'l# ,GAJ~~c)n33U95E5L5LMMM
+GAJ, Jr    c                    t        j                  | |d      }|j                  d      j                  ddg      j	                         j                  d      }|d   d   j                  }|d   d   j                  }|j                  j                  }t        |      dz
  }	d}
d}t        j                  t        |            }t        t        |      dz
  dd      D ]Q  }|
||   z  }
|||   z  }||k\  s||z
  }|||   z  ||   z  }|
|z
  |z  ||	<   |
||	   z  }
|||	   z  }|	dz  }	||k\  r9S ||	dz   d	 }||	dz   d	 }t        j                  d
|||i      S )a  Compute a rolling mean of x, after first aggregating by h.

    Right-aligned. Computes a single mean for each unique value of h. Each
    mean is over at least w samples.

    Parameters
    ----------
    x: Array.
    h: Array of horizon for each value in x.
    w: Integer window size (number of elements).
    name: Name for metric in result dataframe

    Returns
    -------
    Dataframe with columns horizon and name, the rolling mean of x.
    xhr   sumcountr   rg   r   r   Nr   )r:   rq   groupbyaggr9   r   rA   r   r   r   emptyr   )r   r   r   namer   df2xsnshs
trailing_ix_sumn_sumres_xr   excess_nexcess_xres_hs                    r   rolling_mean_by_hr     s   $ 
AA&	'B


3UG,-99;GGL  
S%		B	S'		!	!B	BSAJEEHHSXE 3s8a<R( AAqj qyH"Q%'"Q%/H!&!1A 5E*R
^#ER
^#E!OJ qj 
Q !E:>#$E<<E4788r    c                 *   t        j                  | |d      }|j                  d      }|j                         j	                         j                  d      }|d   }g }g }	t        |      dz
  }
|
dk\  r||
   }|j                  |      j                  j                         }t        j                  ||k(        j                         dz
  }t        |      |k  r2|dk\  r-|j                  | |          |dz  }t        |      |k  r|dk\  r-t        |      |k  rnC|j                  ||
          |	j                  t        j                  |             |
dz  }
|
dk\  r|j                          |	j                          t        j                  d|||	i      S )a  Compute a rolling median of x, after first aggregating by h.

    Right-aligned. Computes a single median for each unique value of h. Each
    median is over at least w samples.

    For each h where there are fewer than w samples, we take samples from the previous h,
    moving backwards. (In other words, we ~ assume that the x's are shuffled within each h.)

    Parameters
    ----------
    x: Array.
    h: Array of horizon for each value in x.
    w: Integer window size (number of elements).
    name: Name for metric in result dataframe

    Returns
    -------
    Dataframe with columns horizon and name, the rolling median of x.
    r   r   rg   r   r   )r:   rq   r   sizer9   r   r   	get_groupr   tolistr   arrayargmaxr   medianreverse)r   r   r   r   r   groupedr   r   r   r   r   h_ir   next_idx_to_adds                 r   rolling_median_by_hr     si   * 
AA&	'BjjoG
,,.
$
$
&
2
23
7C	SBEEB!A
q&es#%%,,. ((18,33592w{A!5 IIa()q O	 2w{A!5
 r7Q;RURYYr]#	Q! q&" 
MMO	MMO<<E4788r    c                     | d   | d   z
  dz  }|dk  rt        j                  | d   |d      S t        |j                  | d   j                  |d      S )	zMean squared error

    Parameters
    ----------
    df: Cross-validation results dataframe.
    w: Aggregation window size.

    Returns
    -------
    Dataframe with columns horizon and mse.
    rf   r$   ra   r   r   )r   r   r   r   r   r   r   r:   rq   r   rA   )r   r   ses      r   r   r   	  s^     S'BvJ
1	$B1u||9bABB
))r)}++qu r    c                     t        | |      }t        j                  |d         |d<   |j                  ddidd       |S )zRoot mean squared error

    Parameters
    ----------
    df: Cross-validation results dataframe.
    w: Aggregation window size.

    Returns
    -------
    Dataframe with columns horizon and rmse.
    r   r   ru   T)r5   r   )r   r   sqrtrename)r   r   r   s      r   r   r     s@     b!*CU$CJJJvYJ=Jr    c                     t        j                  | d   | d   z
        }|dk  rt        j                  | d   |d      S t	        |j
                  | d   j
                  |d      S )zMean absolute error

    Parameters
    ----------
    df: Cross-validation results dataframe.
    w: Aggregation window size.

    Returns
    -------
    Dataframe with columns horizon and mae.
    rf   r$   r   r   )r   r   r   r   r   r   r:   rq   r   rA   )r   r   aes      r   r   r   /  sb     
3"V*$	%B1u||9bABB
))r)}++qu r    c                     t        j                  | d   | d   z
  | d   z        }|dk  rt        j                  | d   |d      S t	        |j
                  | d   j
                  |d      S )zMean absolute percent error

    Parameters
    ----------
    df: Cross-validation results dataframe.
    w: Aggregation window size.

    Returns
    -------
    Dataframe with columns horizon and mape.
    rf   r$   r   r   )r   r   r   r   r   r   r   apes      r   r   r   C  sk     &&"S'BvJ&"S'1
2C1u||9sCDD
**9,, r    c                     t        j                  | d   | d   z
  | d   z        }|dk  rt        j                  | d   |d      S t	        |j
                  | d   |d      S )zMedian absolute percent error

    Parameters
    ----------
    df: Cross-validation results dataframe.
    w: Aggregation window size.

    Returns
    -------
    Dataframe with columns horizon and mdape.
    rf   r$   r   r   )r   r   r   r   )r   r   r:   rq   r   rA   r   s      r   r   r   W  se     &&"S'BvJ&"S'1
2C1u||9DEE
**9 r    c                 V   t        j                  | d   | d   z
        t        j                  | d         t        j                  | d         z   dz  z  }|j                  d      }|dk  rt        j                  | d   |d      S t        |j                  | d   j                  |d      S )	a	  Symmetric mean absolute percentage error
    based on Chen and Yang (2004) formula

    Parameters
    ----------
    df: Cross-validation results dataframe.
    w: Aggregation window size.

    Returns
    -------
    Dataframe with columns horizon and smape.
    rf   r$   ra   r   r   )r   r   r   r   )r   r   fillnar:   rq   r   rA   )r   r   sapes      r   r   r   k  s     66"S'BvJ&'BFF2c7ObffRZ>P,PTU+UVD;;q>D1u||9EFF
++I-- r    c                     | d   | d   k\  | d   | d   k  z  }|dk  rt        j                  | d   |d      S t        |j                  | d   j                  |d      S )	zCoverage

    Parameters
    ----------
    df: Cross-validation results dataframe.
    w: Aggregation window size.

    Returns
    -------
    Dataframe with columns horizon and coverage.
    rf   r%   r&   r   r   )r   r   r   r   r   )r   r   
is_covereds      r   r   r     so     S'R--"S'R=M2MNJ1u||9:NOO


r)}33qz r    )NNNNFNr.   )Ng?F)
__future__r   r   r   logging	tqdm.autor   r8   r   concurrent.futuresrC   numpyr   pandasr:   	getLoggerr   r   r_   rM   rh   r   r   r   r   r   r   r   r   r   r   r/   r    r   <module>r      s    A @      			9	%&"RW>t4n5pRj19j19r($(((,r    