
    %gb                        d dl mZmZmZ d dlZd dlZd dlZd dl	m
Z
  ej                  d      Z	 d dlmZ d dlmZmZmZmZ d dlmZ d dlmZ  e        	 d dlmZ d d
lmZ 	 	 ddZ 	 	 ddZ!	 ddZ"d Z#ddZ$d dZ%d!dZ&d Z'	 d"dZ(	 	 d#dZ)	 	 d$dZ*	 d%dZ+d&dZ,d'dZ-d(dZ.d)dZ/y# e$ r ej5                  d	       Y ow xY w# e$ r ej5                  d       Y ~w xY w)*    )absolute_importdivisionprint_functionN)performance_metricszprophet.plot)pyplot)MonthLocatornum2dateAutoDateLocatorAutoDateFormatter)FuncFormatter) deregister_matplotlib_convertersz4Importing matplotlib failed. Plotting will not work.)make_subplotsz9Importing plotly failed. Interactive plots will not work.c	                 `   |dnd}	|)t        j                  d|      }
|
j                  d      }n|j                         }
|d   }|j	                  | j
                  d   | j
                  d   dd	
       |j	                  ||d   ddd       d|v r|r|j	                  ||d   ddd       | j                  rd|v r|r|j	                  ||d   ddd       |r)| j                  r|j                  ||d   |d   ddd       t        d      }t        |      }|j                  j                  |       |j                  j                  |       |j                  dddddd       |j                  |       |j!                  |       |r|j#                          |	s|
j%                          |
S ) a  Plot the Prophet forecast.

    Parameters
    ----------
    m: Prophet model.
    fcst: pd.DataFrame output of m.predict.
    ax: Optional matplotlib axes on which to plot.
    uncertainty: Optional boolean to plot uncertainty intervals, which will
        only be done if m.uncertainty_samples > 0.
    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.
    FTw	facecolorfigsizeo   dsyzk.zObserved data points)labelyhat-#0072B2Forecast)lscr   cap--kzMaximum capacityfloorzMinimum capacity
yhat_lower
yhat_upper皙?zUncertainty interval)coloralphar   interval_multiplesmajorgray   whichr   r   lwr&   )pltfigureadd_subplot
get_figureplothistorylogistic_flooruncertainty_samplesfill_betweenr
   r   xaxisset_major_locatorset_major_formattergrid
set_xlabel
set_ylabellegendtight_layout)mfcstaxuncertaintyplot_capxlabelylabelr   include_legenduser_provided_axfigfcst_tlocator	formatters                 I/var/www/dash_apps/app1/venv/lib/python3.12/site-packages/prophet/plot.pyr3   r3   *   s   0 !#
u	zjj38__S!mmo$ZFGGAIIdOQYYs^T(  *GGFDLSIZGH}
U;MNGtO
W$#=OPq,,
\ 2D4F's:P 	 	R 7G!'*IHHw'HH  +GGD6casGCMM&MM&
		J    c           	      ~   dg}| j                   d|v r|j                  d       d| j                  v rd|v r|j                  d       d| j                  v rd|v r|j                  d       |j                  t	        | j                        D cg c]  }||v r|dvr| c}       ddd}	| j
                  j                         D ]  \  }}
d|	|
d	   <    dD ]<  }|	|   s	d
j                  |      |v s|j                  d
j                  |             > t        |      }|r|ndd|z  f}t        j                  |dd|      \  }}|dk(  r|g}g }| j                  d   j                         }|j                  |j                  j                         d      j!                         }t#        ||      D ]  \  }}|dk(  rt%        | |d|||       n|| j                  v r|dk(  s| j                  |   d   dk(  r*|t'        j(                  d      k(  rt+        | ||||       nP|dk(  s| j                  |   d   dk(  rt-        | ||||       n%t/        | |||       n|dv rt%        | ||||d       || j0                  d   v s|j                  |        |j3                          |D ]  }t5        |      } |S c c}w )a  Plot the Prophet forecast components.

    Will plot whichever are available of: trend, holidays, weekly
    seasonality, yearly seasonality, and additive and multiplicative extra
    regressors.

    Parameters
    ----------
    m: Prophet model.
    fcst: pd.DataFrame output of m.predict.
    uncertainty: Optional boolean to plot uncertainty intervals, which will
        only be done if m.uncertainty_samples > 0.
    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.
    trendholidaysweeklyyearly)rR   rS   FadditivemultiplicativeTmodeextra_regressors_{}	      r+   r   r   r   r   )r@   rA   namerB   rC   rD   period   days)r@   r[   rB   rC   weekly_startg     v@)r@   r[   rB   rC   yearly_start)r@   r[   rB   rC   )rQ   extra_regressors_additiveextra_regressors_multiplicativerV   )train_holiday_namesappendseasonalitiesextendsortedextra_regressorsitemsformatlenr/   subplotsr4   diffilocvaluesnonzerominzipplot_forecast_componentpd	Timedeltaplot_weeklyplot_yearlyplot_seasonalitycomponent_modesr?   set_y_as_percent)r@   rA   rC   rD   r`   ra   r   
componentsr[   
regressorspropsrW   npanelrI   axesmultiplicative_axesdtmin_dtrB   	plot_names                       rM   plot_componentsr   b   s   > J(Z4-?*%1??"x4'7(#1??"x4'7(#04<D(<< 	  $u=J))//1 )e$(
5=!). Bd 5 < <T Bd J3::4@AB _F gq!f*oGVQ#wGIC{v	
4			BWWRYY&&(+,002FT:.  +I#$W! !//)h&!//)*DX*NRS*Sr||33iBKVb h&!//)*DX*NRX*XiBKVb !iBK  
 

 $$Y2; ))*:;;&&r*A +D ! "b!"J{s   J:c                    g }|s(t        j                  d|      }|j                  d      }|d   }	||j                  |	||   dd      z  }d|v r|r||j                  |	|d   d	d
      z  }| j                  rd|v r|r|j                  |	|d   d	d
       |r2| j
                  r&||j                  |	||dz      ||dz      dd      gz  }t        d      }
t        |
      }|j                  j                  |
       |j                  j                  |       |j                  dddddd       |j                  d       |j                  |       || j                  d   v rt!        |      }|S )aE  Plot a particular component of the forecast.

    Parameters
    ----------
    m: Prophet model.
    fcst: pd.DataFrame output of m.predict.
    name: Name of the component to plot.
    ax: Optional matplotlib Axes to plot on.
    uncertainty: Optional boolean to plot uncertainty intervals, which will
        only be done if m.uncertainty_samples > 0.
    plot_cap: Optional boolean indicating if the capacity should be shown
        in the figure, if available.
    figsize: Optional tuple width, height in inches.

    Returns
    -------
    a list of matplotlib artists
    r   r   r   r   r   r   r   r   r   r   r    r!   _lower_upperr$   r%   r&   Fr'   Tr)   r*   r+   r,   rV   )r/   r0   r1   r3   r5   r6   r7   r
   r   r8   r9   r:   r;   r<   r=   rz   r{   )r@   rA   r[   rB   rC   rD   r   artistsrI   rJ   rK   rL   s               rM   rt   rt      sx   * Gjj38__S!$ZFrwwvtDzcYw??G}27764;437??GtO
W$#6q,,BOOD)4x+@3 $ ( ) 	) 7G!'*IHHw'HH  +GGD6casGCMM$MM$q  !122b!NrN   c                     |ddd}| j                   D ]  }d||<   	 | j                  j                         D ]  }|d   	d||d   <    t        j                  |      }| j                  |      }|S )zPrepare dataframe for plotting seasonal components.

    Parameters
    ----------
    m: Prophet model.
    ds: List of dates for column ds.

    Returns
    -------
    A dataframe with seasonal components on ds.
          ?g        )r   r   r!   condition_nameT)ri   rf   rp   ru   	DataFramesetup_dataframe)r@   r   df_dictr[   r~   dfs         rM   seasonality_plot_dfr      s     R0G""  '') 4!"./3GE*+,4 
g	B	
		2	BIrN   c                    g }|s(t        j                  d|      }|j                  d      }t        j                  dd      t        j
                  |      z   }t        | |      }	| j                  |	      }
|j                         }||j                  t        t        |            |
|   dd	
      z  }|rD| j                  r8||j                  t        t        |            |
|dz      |
|dz      d	d      gz  }|j                  dddddd       |j                  t        t        |                   |j!                  |       |j#                  d       |j%                  |       | j&                  |   d   dk(  rt)        |      }|S )a  Plot the weekly component of the forecast.

    Parameters
    ----------
    m: Prophet model.
    ax: Optional matplotlib Axes to plot on. One will be created if this
        is not provided.
    uncertainty: Optional boolean to plot uncertainty intervals, which will
        only be done if m.uncertainty_samples > 0.
    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.
    figsize: Optional tuple width, height in inches.
    name: Name of seasonality component if changed from default 'weekly'.

    Returns
    -------
    a list of matplotlib artists
    r   r   r   
2017-01-01r]   startperiodsr^   r   r   r   r   r   r$   r   Tr)   r*   r+   r,   zDay of weekrW   rV   )r/   r0   r1   ru   
date_rangerv   r   predict_seasonal_componentsday_namer3   rangerl   r6   r7   r;   
set_xticksset_xticklabelsr<   r=   rf   r{   )r@   rB   rC   r`   r   r[   r   rI   r_   df_wseass              rM   rw   rw     sq   ( Gjj38__S!MMa8LLl+,Dq$'D((.D==?DrwwuSY'd  ! !Gq,,BOOE#d)$4$($94x;P*33 $ @ A 	A GGD6casGCMM%D	"#tMM- MM$tV$(88b!NrN   c                    g }|s(t        j                  d|      }|j                  d      }t        j                  dd      t        j
                  |      z   }t        | |      }	| j                  |	      }
||j                  |	d   |
|   d	d
      z  }|r5| j                  r)||j                  |	d   |
|dz      |
|dz      d
d      gz  }|j                  dddd	dd       t        t        dd      dd      }|j                  j                  t!        dd             |j                  j#                  |       |j%                  d       |j'                  |       | j(                  |   d   dk(  rt+        |      }|S )a  Plot the yearly component of the forecast.

    Parameters
    ----------
    m: Prophet model.
    ax: Optional matplotlib Axes to plot on. One will be created if
        this is not provided.
    uncertainty: Optional boolean to plot uncertainty intervals, which will
        only be done if m.uncertainty_samples > 0.
    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.
    name: Name of seasonality component if previously changed from default 'yearly'.

    Returns
    -------
    a list of matplotlib artists
    r   r   r   r   im  r   r^   r   r   r   r   r   r   r$   r   Tr)   r*   r+   r,         )
bymonthdayintervalc                 8    dj                  t        |             S Nz{dt:%B} {dt.day}r   rk   r	   xposs     rM   <lambda>zplot_yearly.<locals>.<lambda>g  s    .55!5E rN   Day of yearrW   rV   N)r/   r0   r1   ru   r   rv   r   r   r3   r6   r7   r;   r   r   r8   r:   r   r9   r<   r=   rf   r{   )r@   rB   rC   ra   r   r[   r   rI   r_   df_yr   monthss               rM   rx   rx   A  s|   ( Gjj38__S!MMc:LLl+,Dq$'D((.DrwwT
DJ3)  5 5Gq,,BOOJTH_-!# $ ? @ 	@ GGD6casGC%2,1qAFHH  E"G HHHv&MM- MM$tV$(88b!NrN   c                 ,   g }|s(t        j                  d|      }|j                  d      }t        j                  d      }| j
                  |   d   |t        j                        z   }d}	t        j                  t        j                  |j                  |j                  |	            }
t        | |
      }| j                  |      }||j                  |d   ||   d	d
      z  }|r5| j                  r)||j                  |d   ||dz      ||dz      d
d      gz  }|j                  dddd	dd       dt        j                  t        j                  |j                  |j                              j!                         }|j#                  |       |dk(  rt%        d&d      }|j'                  d       n|dk(  rt%        d&d      }|j'                  d       ni|dk(  rt%        d&d      }|j'                  d       nEdk  rt%        d&d       }|j'                  d!       n!t%        d&fd"	      }|j'                  d#       |j(                  j+                  |       |j-                  |       | j
                  |   d$   d%k(  rt/        |      }|S )'a  Plot a custom seasonal component.

    Parameters
    ----------
    m: Prophet model.
    name: Seasonality name, like 'daily', 'weekly'.
    ax: Optional matplotlib Axes to plot on. One will be created if
        this is not provided.
    uncertainty: Optional boolean to plot uncertainty intervals, which will
        only be done if m.uncertainty_samples > 0.
    figsize: Optional tuple width, height in inches.

    Returns
    -------
    a list of matplotlib artists
    r   r   r   2017-01-01 0000r\   r^      r   r   r   r   r   r   r$   r   Tr)   r*   r+   r,      rS   c                 8    dj                  t        |             S r   r   r   s     rM   r   z"plot_seasonality.<locals>.<lambda>  s     2 9 9Xa[ 9 I rN   r   rR   c                 8    dj                  t        |             S )Nz{dt:%A}r   r   r   s     rM   r   z"plot_seasonality.<locals>.<lambda>      	 0 0HQK 0 @ rN   zDay of Weekdailyc                 8    dj                  t        |             S Nz{dt:%T}r   r   r   s     rM   r   z"plot_seasonality.<locals>.<lambda>  r   rN   zHour of dayr   c                 8    dj                  t        |             S r   r   r   s     rM   r   z"plot_seasonality.<locals>.<lambda>  r   rN   Hoursc                 8    dj                  |z  dz
  z        S )Nz{:.0f}r+   )rk   )r   r   n_ticksr\   s     rM   r   z"plot_seasonality.<locals>.<lambda>  s    f!0L M rN   DaysrW   rV   r   )r/   r0   r1   ru   to_datetimerf   rv   nplinspacevaluer   r   r3   r6   r7   r;   to_pydatetimer   r   r<   r8   r:   r=   r{   )r@   r[   rB   rC   r   r   rI   r   endplot_pointsr_   r   r   xticksfmtr   r\   s                  @@rM   ry   ry   p  s[   " Gjj38__S!NN,-E__T"8,F
",,F+
+CK>>"++ekk399kJKDq$'D((.DrwwtDz4:##  % %Gq,,BOOJTH_-!# $ ? @ 	@ GGD6casGCG^^BKKSYYH 

-/ MM&xIK
m$		@B
m$	@B
m$	1@B
gMO
fHH  %MM$tV$(88b!NrN   c                     d| j                         z  }|D cg c]  }dj                  |       }}| j                  | j                         j                                | j	                  |       | S c c}w )Nd   z{0:.4g}%)
get_yticksrk   
set_ytickstolistset_yticklabels)rB   yticksr   yticklabelss       rM   r{   r{     sc    2==?"F178A:$$Q'8K8MM"--/((*+{#I 9s   A2c                 v   g }|r)|j                  | j                  |d   |d   |             t        |j                        dkD  rG|j                  t	        j
                  t	        j                  |j                  d   d            |k\     ng }|D ]%  }	|j                  | j                  |	||             ' |S )aK  Add markers for significant changepoints to prophet forecast plot.

    Example:
    fig = m.plot(forecast)
    add_changepoints_to_plot(fig.gca(), m, forecast)

    Parameters
    ----------
    ax: axis on which to overlay changepoint markers.
    m: Prophet model.
    fcst: Forecast output from m.predict.
    threshold: Threshold on trend change magnitude for significance.
    cp_color: Color of changepoint markers.
    cp_linestyle: Linestyle for changepoint markers.
    trend: If True, will also overlay the trend.

    Returns
    -------
    a list of matplotlib artists
    r   rP   r   r   deltaaxis)r   r   r   )	re   r3   rl   changepointsr   absnanmeanparamsaxvline)
rB   r@   rA   	thresholdcp_colorcp_linestylerP   r   signif_changepointscps
             rM   add_changepoints_to_plotr     s    . GrwwtDz4=HwEF 
Q^^	q	  ..
rzz!((7+!45B&(  " FrzzB(|zDEFNrN   c                    |)t        j                  d|      }|j                  d      }n|j                         }t	        | |gd      }t	        | |g|      }	t        |d   j                  d            dz  }
g d	}g d
}g d}t        |      D ]4  \  }}t        j                  d|      t        j                  |
d      k  s4 n |d   j                  d      j                  t        j                        t        |         z  }|	d   j                  d      j                  t        j                        t        ||         z  }|j                  |||   dd|       |j                  ||	|   d|       |j                  d       |j                  dj!                  ||                |j#                  |       |S )a$  Plot a performance metric vs. forecast horizon from cross validation.

    Cross validation produces a collection of out-of-sample model predictions
    that can be compared to actual values, at a range of different horizons
    (distance from the cutoff). This computes a specified performance metric
    for each prediction, and aggregated over a rolling window with horizon.

    This uses prophet.diagnostics.performance_metrics to compute the metrics.
    Valid values of metric are 'mse', 'rmse', 'mae', 'mape', and 'coverage'.

    rolling_window is the proportion of data included in the rolling window of
    aggregation. The default value of 0.1 means 10% of data are included in the
    aggregation for computing the metric.

    As a concrete example, if metric='mse', then this plot will show the
    squared error for each cross validation prediction, along with the MSE
    averaged over rolling windows of 10% of the data.

    Parameters
    ----------
    df_cv: The output from prophet.diagnostics.cross_validation.
    metric: Metric name, one of ['mse', 'rmse', 'mae', 'mape', 'coverage'].
    rolling_window: Proportion of data to use for rolling average of metric.
        In [0, 1]. Defaults to 0.1.
    ax: Optional matplotlib axis on which to plot. If not given, a new figure
        will be created.
    figsize: Optional tuple width, height in inches.
    color: Optional color for plot and error points, useful when plotting
        multiple model performances on one axis for comparison.

    Returns
    -------
    a matplotlib figure.
    r   r   r   )metricsrolling_windowhorizonztimedelta64[ns]g      $@)Dhr@   smsusns)r_   hoursminutessecondsmillisecondsmicrosecondsnanoseconds)l     "R: l     qal    Xp7 i ʚ;i@B i  r   r+   r   .皙?)r&   r   r   r   TzHorizon ({}))r/   r0   r1   r2   r   maxastype	enumerater   timedelta64viewint64floatr3   r;   r<   rk   r=   )df_cvmetricr   rB   r   r%   point_colorrI   df_nonedf_htick_wdtsdt_namesdt_conversionsir   x_pltx_plt_hs                     rM   plot_cross_validation_metricr    s   L 
zjj38__S!mmo!%&"MGuvh~VD #**+<=>DF
0CHN 3 2>>!R 2>>&$#?? I%%&78==bhhG%P^_`PaJbbE9o$$%67<<RXXF~^_O`IaaGGGE76?CskGBGGGT&\3%G0GGDMMM.''45MM&JrN   c
                    d}
d}d}d}d}d}d}g }|j                  t        j                  d| j                  d   | j                  d	   t	        ||
      d             |rE| j
                  r9|j                  t        j                  |d   |d   dt	        d      d             |j                  t        j                  d|d   |d   dt	        |
|      ||r| j
                  rdnd             |rG| j
                  r;|j                  t        j                  |d   |d   dt	        d      |dd             d|v r=|r;|j                  t        j                  d|d   |d   dt	        |d|                   | j                  rAd |v r=|r;|j                  t        j                  d!|d   |d    dt	        |d|                   |r:|j                  t        j                  d"|d   |d#   dt	        ||                   |rt        | j                        dkD  r| j                  t        j                  t        j                  | j                  d$   d%            |k\     }|j                  t        j                  ||j                  |d   j                  |      d#f   t	        d&d'|t	        |      (      dd)             t	        d*|	d   |	d+   t	        |,      t	        |d-t	        t        t	        d.d/d0d12      t	        d+d3d4d12      t	        d5d6d4d12      t	        d+d7d8d12      t	        d9:      g      ;      t	        d<=      >      ?      }t        j                   ||@      }|S )Aa  Plot the Prophet forecast with Plotly offline.

    Plotting in Jupyter Notebook requires initializing plotly.offline.init_notebook_mode():
    >>> import plotly.offline as py
    >>> py.init_notebook_mode()
    Then the figure can be displayed using plotly.offline.iplot(...):
    >>> fig = plot_plotly(m, fcst)
    >>> py.iplot(fig)
    see https://plot.ly/python/offline/ for details

    Parameters
    ----------
    m: Prophet model.
    fcst: pd.DataFrame output of m.predict.
    uncertainty: Optional boolean to plot uncertainty intervals.
    plot_cap: Optional boolean indicating if the capacity should be shown
        in the figure, if available.
    trend: Optional boolean to plot trend
    changepoints: Optional boolean to plot changepoints
    changepoints_threshold: Threshold on trend change magnitude for significance.
    xlabel: Optional label name on X-axis
    ylabel: Optional label name on Y-axis

    Returns
    -------
    A Plotly Figure.
    r   rgba(0, 114, 178, 0.2)blackz#B23B00r      Actualr   r   )r%   sizemarkers)r[   r   r   markerrW   r"   linesr   )widthskip)r   r   rW   line	hoverinfo	Predictedr   r%   r  tonextynoner[   r   r   rW   r  	fillcolorfillr#   )r   r   rW   r  r  r  r  r   Capdashr%   r  r  r[   r   r   rW   r  r!   FloorTrendrP   r   r   2   zline-ns-open)r  symbolr%   r  )r   r   r  rW   r  Fr+   )titledater]   1wdaybackward)countr   stepstepmode1mmonth   6m1yyearall)r+  )buttonsT)visible)r%  typerangeselectorrangeslider)
showlegendr  heightyaxisr8   datalayout)re   goScatterr4   dictr6   r5   rl   r   r   r   r   r   locisinlistFigure)r@   rA   rC   rD   rP   r   changepoints_thresholdrE   rF   r   prediction_colorerror_coloractual_color	cap_colortrend_color
line_widthmarker_sizer=  r   r>  rI   s                        rM   plot_plotlyrN  .  so   : !*KLIKJKDKK


))D/
))C.,[9  q,,BJJ4j< A
 	 	KK


t*
v,(
;%!*?*?YV  q,,BJJ4j< A!
 	 }BJJ4j5kIF*E
 	 	GtOBJJ4j7mIF*E
 	 BJJ4j7mKz:
 	 ANN+a/nnFF2::ahhw/a89=SS
 	BJJ!hhtDz':;WDERk!
35
 	 ajqz
 q##",. q#%",. q#%",. q#$",. e$# * 1
#FH ))f
-CJrN   c           
         i }t        | |d||      |d<   | j                  d|v rt        | |d|      |d<   ddd}| j                  j                         D ]  \  }}d||d   <    dD ]J  }	||	   s	dj	                  |	      |v st        | |dj	                  |	            |dj	                  |	      <   L | j
                  D ]  }
t        | |
      ||
<    t        t        |      dd	      }|d
   j                  t        j                  d|d   |d   t        |      z               t        |      D ]  \  }}|dk(  r|d
   d   }|d
   d   }n4|d
   dj	                  |dz            }|d
   dj	                  |dz            }|j                  ||   d          |j                  ||   d          ||   d   D ]  }|j                  ||dz   d         |S )a  Plot the Prophet forecast components using Plotly.
    See plot_plotly() for Plotly setup instructions

    Will plot whichever are available of: trend, holidays, weekly
    seasonality, yearly seasonality, and additive and multiplicative extra
    regressors.

    Parameters
    ----------
    m: Prophet model.
    fcst: pd.DataFrame output of m.predict.
    uncertainty: Optional boolean to plot uncertainty intervals, which will
        only be done if m.uncertainty_samples > 0.
    plot_cap: Optional boolean indicating if the capacity should be shown
        in the figure, if available.
    figsize: Set the size for the subplots (in px).

    Returns
    -------
    A Plotly Figure.
    rP   rQ   FrT   TrW   rX   r+   )rowscols
print_gridr>  r   )r9  r  r:  r8   r;  zxaxis{}zyaxis{}traces)#get_forecast_component_plotly_propsrd   ri   rj   rk   rf   get_seasonality_plotly_propsr   rl   updater?  Layoutr   append_trace)r@   rA   rC   rD   r   r|   r}   r[   r~   rW   seasonalityrI   r  r8   r;  traces                   rM   plot_components_plotlyr[    s.   2 J=	4+x1Jw(Z4-?!DtZ".
: $u=J))//1 )e$(
5=!). =d 5 < <T Bd J=`4.55d;>=J,33D9:=  O">q+"N
;O S_1
GCMajqzC
O+ 
 Z( 
.46M'*EM'*EM)"2"21q5"9:EM)"2"21q5"9:EZ%g./Z%g./%h/ 	.EUAE1-	.
. JrN   c                     t        | ||||      }t        j                  |d   |d   d|d   |d         }t        j                  |d   |      }|S )	a?  Plot an particular component of the forecast using Plotly.
    See plot_plotly() for Plotly setup instructions

    Parameters
    ----------
    m: Prophet model.
    fcst: pd.DataFrame output of m.predict.
    name: Name of the component to plot.
    uncertainty: Optional boolean to plot uncertainty intervals, which will
        only be done if m.uncertainty_samples > 0.
    plot_cap: Optional boolean indicating if the capacity should be shown
        in the figure, if available.
    figsize: The plot's size (in px).

    Returns
    -------
    A Plotly Figure.
    r   r+   Fr8   r;  r  r:  r9  r8   r;  rS  r<  )rT  r?  rW  rE  )	r@   rA   r[   rC   rD   r   r~   r>  rI   s	            rM   plot_forecast_component_plotlyr^  	  s^    & 04{HUEYYajqzGnGnF ))x
8CJrN   c                     t        | ||      }t        j                  |d   |d   d|d   |d         }t        j                  |d   |      }|S )	a  Plot a custom seasonal component using Plotly.
    See plot_plotly() for Plotly setup instructions

    Parameters
    ----------
    m: Prophet model.
    name: Seasonality name, like 'daily', 'weekly'.
    uncertainty: Optional boolean to plot uncertainty intervals, which will
        only be done if m.uncertainty_samples > 0.
    figsize: Set the plot's size (in px).

    Returns
    -------
    A Plotly Figure.
    r   r+   Fr8   r;  r]  rS  r<  )rU  r?  rW  rE  )r@   r[   rC   r   r~   r>  rI   s          rM   plot_seasonality_plotlyr`  (  sZ      )D+>EYYajqzGnGnF ))x
8CJrN   c                 D   d}d}d}d}d}	|d   j                         |d   j                         z
  dz  }
|d   j                         |
z
  |d   j                         |
z   g}d}d	}|d
k(  r| j                  |d         }| j                  |d   |      \  }}}|j                  j
                  j                  ddd      |_        |j                  j
                  j                  ddd      |_        t        j                  d|j                        }|j                         D ]K  \  }}||j                  t              |dk7  z  xx   dz  cc<   ||j                  t              xx   |z  cc<   M g }|j                  t        j                  ||d   ||   |t        j                   j#                  ||	      |             |r| j$                  r||dz      ||dz      k7  j'                         r|dk(  r1|d   j)                  t+        dd||dz      ||dz      d|             n|j                  t        j                  |dz   |d   ||dz      |t        j                   j#                  d|                   |j                  t        j                  |dz   |d   ||dz      |t        j                   j#                  d|      |d             d|v rQ|rO|j                  t        j                  d |d   |d   d	t        j                   j#                  |d!|	"                   | j,                  rUd#|v rQ|rO|j                  t        j                  d$|d   |d#   d	t        j                   j#                  |d!|	"                   t        j.                  j1                  d%|&      }t        j.                  j3                  |d'k(  rd(nd)t        j.                  j4                  j7                  |*      |+      }|| j8                  d,   v r|j)                  d-d./       |||d0S )1a  Prepares a dictionary for plotting the selected forecast component with Plotly

    Parameters
    ----------
    m: Prophet model.
    fcst: pd.DataFrame output of m.predict.
    name: Name of the component to plot.
    uncertainty: Optional boolean to plot uncertainty intervals, which will
        only be done if m.uncertainty_samples > 0.
    plot_cap: Optional boolean indicating if the capacity should be shown
        in the figure, if available.

    Returns
    -------
    A dictionary with Plotly traces, xaxis and yaxis
    r   r
  r  #AAAr   r   皙?Nr  rQ   _delim_ F)regexz+0)r=  indexz<br>r  )r[   r   r   rW   r  textr   r   r  r   r=  )r6  	symmetricarray
arrayminusr  r%   )error_yr  r%   r   r  r  r   r  r  r  r!   r!  r&  )r6  r   rP   normaltozerorh  )	rangemoder%  zerolinecolorrV   %.2%
tickformathoverformatrS  r8   r;  )r   rr   construct_holiday_dataframemake_holiday_featurescolumnsstrreplaceru   Seriesrg  rj   r   boolre   r?  r@  scatterLiner6   anyrV  rA  r5   r>  XAxisYAxisr;  Titlerz   )r@   rA   r[   rC   rD   rG  rH  rJ  zeroline_colorrL  range_marginrange_xrh  rW   rQ   holiday_features_holiday_featureidxsrS  r8   r;  s                         rM   rT  rT  D  s   " !*KINJJNN$tDz~~'774?LDz~~,.T
0@<0OPGDDz 00d<!"!8!8dX!N!Q#3#;#;#?#?#G#G	SU]b#G#c #3#;#;#?#?#G#GbX]#G#^ yyb(8(>(>?%5%;%;%= 	7!OTT"dbj12f<2T"#6#	7 F
MM"**
t*
t*ZZ__#3:_F  q,,$th2G4PTW_P_K`2`1e1e1g91I#th/#D8O4%  	 MM"**H_t*th'ZZ__1K_@  MM"**H_t*th'ZZ__1K_@%  }bjj4j5kyvZP
 	 	GtObjj4j7myvZP
 	 IIOO  E IIOO$'/hx"$))//"7"7T"7"B*8  :E q  !1227uu==rN   c                 ~   d}d}d}d}t        j                  d      }| j                  |   d   }|t        j                  |      z   }	| j                  d   j
                  j                  d	k(  j                         r)t        j                  |      j                  t              }
n| j                  d   j
                  j                  d	k(  j                         r,t        j                  |d
z        j                  t              }
n.t        j                  |d
z  dz        j                  t              }
t        j                  t        j                  |j                  |	j                  |
d            }t        | |      }| j!                  |      }g }|j#                  t%        j&                  ||d   ||   dt$        j(                  j+                  ||                   |r| j,                  r||dz      ||dz      k7  j/                         r|j#                  t%        j&                  |dz   |d   ||dz      dt$        j(                  j+                  d	|                   |j#                  t%        j&                  |dz   |d   ||dz      dt$        j(                  j+                  d	|      |d             |dk  rd}n|dk  rd}n
|dk  rd}nd}|d   j1                         |d   j3                         z
  dz  }t$        j4                  j7                  |d|d   j3                         |z
  |d   j1                         |z   g      }t$        j4                  j9                  t$        j4                  j:                  j=                  |      |       }| j                  |   d!   d"k(  r|j?                  d#d$%       |||d&S )'aw  Prepares a dictionary for plotting the selected seasonality with Plotly

    Parameters
    ----------
    m: Prophet model.
    name: Name of the component to plot.
    uncertainty: Optional boolean to plot uncertainty intervals, which will
        only be done if m.uncertainty_samples > 0.

    Returns
    -------
    A dictionary with Plotly traces, xaxis and yaxis
    r   r
  r   rb  r   r\   r^   r   r      <   F)endpointr  r  r   r   r   rm  r  r  z%H:%Mr]   z%A %H:%M   z%Az%B %erc  r&  )rv  r6  r   rp  )r%  rr  rW   rV   rs  rt  ru  rx  ) ru   r   rf   rv   r4   r   hourr3  r   r!   r   intminuter   r   r   r   re   r?  r@  r  r  r6   r  r   rr   r>  r  r  r;  r  rV  )r@   r[   rC   rG  rH  rL  r  r   r\   r   r   r_   r   r   rS  rv  r  r8   r;  s                      rM   rU  rU    s@    !*KJN NN,-E__T"8,F
",,F+
+C			$1$))+hhv&--c2
))D/


#
#q
(	-	-	/hhv{+2237hhv{R/077<>>"++ekk399kTYZ[Dq$'D((.DF
MM"**
t*
t*ZZ__#3:_F  q,,$th2G4PTW_P_K`2`1e1e1gbjj4j4(?#q<
 	 	bjj4j4(?#q<!
 	 {
	!
	"

JNN$tDz~~'774?LIIOODz~~,.T
0@<0OP  E IIOO"))//"7"7T"7"B*8  :EtV$(887uu==rN   )NTTr   r   
   r/  F)TTr   r   N)NTFr  )NTr   r  rR   )NTr   r  rS   )NTr  ){Gz?rr   T)r   Nr  br*   )TTFFr  r   r   )  iX  )TT)r  r   )TFr  i,  )Tr  )TF)T)0
__future__r   r   r   loggingnumpyr   pandasru   prophet.diagnosticsr   	getLoggerlogger
matplotlibr   r/   matplotlib.datesr   r	   r
   r   matplotlib.tickerr   pandas.plottingr   ImportErrorerrorplotly.graph_objs
graph_objsr?  plotly.subplotsr   r3   r   rt   r   rw   rx   ry   r{   r   r  rN  r[  r^  r`  rT  rU   rN   rM   <module>r     s6   A @    3			>	*I(  0@$&N"- LO$)5r LMfT GN-`0+\,^@F IMF HKNb UZNXYz ;E<~>8g>TQ>]  I
LLGHI  N
LLLMNs#   %B, C ,CCC! C!