
    Be8                        d Z ddlmZ ddlmZmZmZmZmZm	Z	 ddl
ZddlZddlmZ ddlmZ ddlmZ dd	lmZmZ dd
lmZ ddlmZ erddlmZ ddlmZ ddlmZ  G d de          ZdS )zP
Defines a PlotlyPane which renders a plotly plot using PlotlyPlot
bokeh model.
    )annotations)TYPE_CHECKINGAnyClassVarListMappingOptionalN)ColumnDataSource)JupyterComm   )CDN_DIST)
isdatetime	lazy_load)
Layoutable   )	ModelPane)Document)Model)Commc                      e Zd ZU dZ ej        d          Z ej        d          Z ej        dd          Z ej        d          Z	 ej
        dd	
          Z ej        dd          Z ej        dd          Z ej        dd          Z ej        dd          Z ej        ddg d          Z ej        ddd          Z ej        dd
          ZdZded<   e dgZded<   dZded <   d!d!d"Zd#ed$<   edNd)            ZdO fd*	Zd+ Ze d,             Z!e dPd.            Z" ej#        d/d0d1          d2             Z$dOd3Z%dQd4Z& ej#        d5d1          d6             Z' ej#        d7d1          d8             Z(e d9             Z)	 dQd:Z*d; Z+d< Z,e d=             Z-d> Z. fd?Z/	 	 dRdS fdHZ0dTdMZ1 xZ2S )UPlotlya"  
    The `Plotly` pane renders Plotly plots inside a panel.

    Note that

    - the Panel `extension` has to be loaded with `plotly` as an argument to
    ensure that Plotly.js is initialized.
    - it supports click, hover and selection events.
    - it optimizes the plot rendering by using binary serialization for any
    array data found on the Plotly object.

    Reference: https://panel.holoviz.org/reference/panes/Plotly.html

    :Example:

    >>> pn.extension('plotly')
    >>> Plotly(some_plotly_figure, width=500, height=500)
    zClick callback data)doczClickannotation callback dataTzConfig data)nested_refsr   zHover callback datazc
       Attach callbacks to the Plotly figure to update output when it
       is modified in place.)defaultr   zRelayout callback datazRestyle callback datazSelected callback datazCurrent viewport statemouseupa  
        Policy by which the viewport parameter is updated during user interactions.

        * "mouseup": updates are synchronized when mouse button is
          released after panning
        * "continuous": updates are synchronized continually while panning
        * "throttle": updates are synchronized while panning, at
          intervals determined by the viewport_update_throttle parameter
        )r   
continuousthrottle)r   r   objects   )r   Nz
        Time interval in milliseconds at which viewport updates are
        synchronized when viewport_update_policy is "throttle".)r   boundsr   r   z:
        Number of renders, increment to trigger re-renderg?zClassVar[float | bool | None]priorityzcss/plotly.csszClassVar[List[str]]_stylesheetszClassVar[bool]_updatesN)link_figureobjectz"ClassVar[Mapping[str, str | None]]_renameobjr   returnfloat | bool | Nonec                     t          |t                    r|rt           fd|D                       p,t          |d          pt          |t                    od|v od|v S )Nc              3  B   K   | ]}                     |          V  d S N)applies).0oclss     1lib/python3.11/site-packages/panel/pane/plotly.py	<genexpr>z!Plotly.applies.<locals>.<genexpr>c   s-      6S6S!s{{1~~6S6S6S6S6S6S    to_plotly_jsondatalayout)
isinstancelistallhasattrdict)r0   r'   s   ` r1   r-   zPlotly.appliesa   s    C&&S3S36S6S6S6Ss6S6S6S3S3S Z-..Z3=c43H3H 4Y7=}4YIQUX	[r3   c                     t                      j        |fi | d | _        d | _        |                                  d S r,   )super__init___figure_event_update_figure)selfr%   params	__class__s      r1   r>   zPlotly.__init__g   sH    **6***r3   c                (   dd l m} t          ||j                  r|S t          |t                    r|d         |d         }}nt          |t
                    r|\  }}n|i }}t          |t                    r|n|g}|                    ||          S )Nr   r5   r6   r5   r6   )plotly.graph_objs
graph_objsr7   Figurer;   tupler8   )rB   r'   gor5   r6   s        r1   
_to_figurezPlotly._to_figurem   s    &&&&&&c29%% 	#JT"" 	#v;H&DDU## 	#LD&&&D!$--9ttD6yyd6y222r3   c                    g }|                      dg           }|D ]A}i }t                              ||           |                    t	          |                     B|S )Nr5   )getr   _get_sources_for_traceappendr
   )jsonsourcestracestracer5   s        r1   _get_sourceszPlotly._get_sourcesz   sg    &"%% 	3 	3ED))%666NN+D112222r3    c                L   t          |                                           D ] \  }}|s|nd                    ||          }t          |t          j                  r|                     |          g||<   Tt          |t                    rt          	                    |||           t          |t                     rd|rbt          |d         t                    rGt          |          D ]7\  }}|dz   t          |          z   }t          	                    |||           8d S )Nz{}.{})r5   parent_pathr   .)r8   itemsformatr7   npndarraypopr;   r   rO   	enumeratestr)	rQ   r5   rX   keyvalue	full_pathielementelement_paths	            r1   rO   zPlotly._get_sources_for_trace   s.   tzz||,, 	 	JC#.TGNN;PS4T4TI%,, #'88C==/YE4(( 	--e$I-VVVVE4(( U z%(D7Q7Q "+E"2"2  JAw#,s?SVV#;L11d 2    	 	r3   r%   r$   )watchc                :    dd l m}  j        0t           j                  |j        us j         j        u s j        sd S  j        } fd|_         fd|_         fd|_	         j
        |_
         j        |_         j        |_         fd|_        | _        d S )Nr   c                 .                         d          S )Nadd_update_from_figure___rB   s     r1   <lambda>z'Plotly._update_figure.<locals>.<lambda>   s    43K3KE3R3R r3   c                 .                         d          S )Nmoverk   rm   s     r1   rp   z'Plotly._update_figure.<locals>.<lambda>   s    D4L4LV4T4T r3   c                 .                         d          S )Ndeleterk   rm   s     r1   rp   z'Plotly._update_figure.<locals>.<lambda>   s    d6N6Nx6X6X r3   c                 .                         d          S )Nanimaterk   rm   s     r1   rp   z'Plotly._update_figure.<locals>.<lambda>   s    1I1I)1T1T r3   )rG   rH   r%   typerI   r?   r$   _send_addTraces_msg_send_moveTraces_msg_send_deleteTraces_msg_send_restyle_msg_send_relayout_msg_send_update_msg_send_animate_msg)rB   rK   figs   `  r1   rA   zPlotly._update_figure   s    &&&&&&K4#4#4BI#E#EK4<''t/?'F
 k"R"R"R"R#T#T#T#T %X%X%X%X" $ 6!%!8#4 T T T Tr3   c                6    |                      i |d |           d S r,   r}   )rB   relayout_datasource_view_ids      r1   r|   zPlotly._send_relayout_msg   s"    b-~FFFFFr3   c                6    |                      |i ||           d S r,   r   )rB   restyle_datatrace_indexesr   s       r1   r{   zPlotly._send_restyle_msg   s"    lB~NNNNNr3   r   c                N    | j         | j        d S  | j         j        | j          d S r,   )r?   r   plotly_restyle)rB   s    r1   _update_figure_stylezPlotly._update_figure_style   s2    <4#4#<F##T%67777r3   r   c                    | j         | j        d S |                     | j                  }| j         j        j                                         | j                             |           d S r,   )r?   r   _clean_relayout_datar6   _compound_array_propsclearplotly_relayout)rB   r   s     r1   _update_figure_layoutzPlotly._update_figure_layout   se    <4#5#=F11$2DEE 	177999$$]33333r3   c                >    d |                                  D             S )Nc                D    i | ]\  }}|                     d           ||S )z	._derived)endswith)r.   ra   vals      r1   
<dictcomp>z/Plotly._clean_relayout_data.<locals>.<dictcomp>   s?     
 
 
!c#,,{B[B[

 
 
r3   )rZ   )r   s    r1   r   zPlotly._clean_relayout_data   s/    
 
%2%8%8%:%:
 
 
 	
r3   c                    |rd S | j                             |          }i }|r||d<   |r||d|d<   | j                                        D ] \  }\  }}|                     g |||           !d S )Nrelayout)r5   rS   restyle)r?   _normalize_trace_indexes_modelsrZ   _apply_update)	rB   r   r   r   r   msgrefmrn   s	            r1   r}   zPlotly._send_update_msg   s      	F==mLL 	,+C
O 	M&2mLLC	N<--// 	0 	0KC!Qr33////	0 	0r3   c                p    || _         	 | j                            d           d | _         d S # d | _         w xY w)Nr%   )r@   paramtrigger)rB   eventargskwargss       r1   rl   zPlotly._update_from_figure   sB    	Jx(((DKKK$DKs   , 	5c                   i }t                               ||           d}|                                D ]\  }}|d         }	 |j                            |          d         }t          |          t          |          k    p'|j        |j        k    p||k                                    }	n# t          $ r d}	Y nw xY w|	rd}|g|j        |<   t          |j                  D ]}||vr
|j        |= d}|S )NFr   T)
r   rO   rZ   r5   rN   rw   shapeany	Exceptionr8   )
rB   cdsrT   trace_arraysupdate_sourcesra   new_colnewoldupdate_arrays
             r1   _update_data_sourceszPlotly._update_data_sources   s%   %%e\:::(..00 	& 	&LC!*C$hll3''*#YY$s))+ 'Y#)+'CZ$$&&   $ $ $#$  &!%!$>> 	& 	&C,&&HSM!%s   A(B++B:9B:c                |   |                                  }|d         }t          t          |                    D ]}||         D ]w}t          ||         |                   rZ||         |         }t	          |t
          j                  r|                    t                    }nd |D             }|||         |<   x|S )zvWraps around to_plotly_json and applies necessary fixes.

        For #382: Map datetime elements to strings.
        r5   c                ,    g | ]}t          |          S  )r`   )r.   vs     r1   
<listcomp>z/Plotly._plotly_json_wrapper.<locals>.<listcomp>	  s    333!s1vv333r3   )	r4   rangelenr   r7   r\   r]   astyper`   )r   rQ   r5   idxra   arrs         r1   _plotly_json_wrapperzPlotly._plotly_json_wrapper   s     !!##F|T## 	) 	)CCy ) )d3in-- )s)C.C!#rz22 4!jjoo33s333%(DIcN) r3   c                n    d  j         D             }t          t          j                   |z   } fd|D             } j        i g }}nI                      j                  }                     |          }t                              |          } j        |d<    j	        pi |d<   |
                    dg           |d<   ||d<   |
                    di           x|d<   }|
                    dg           |d<   |
                    d	          r& j         j         j        j        u rd
|d<   d|vri |d<   |S )Nc                    g | ]}d |v |	S )viewportr   )r.   ps     r1   r   z'Plotly._init_params.<locals>.<listcomp>  s    DDDJ!OO1OOOr3   c                R    i | ]#}t          |          |t          |          $S r,   )getattr)r.   r   rB   s     r1   r   z'Plotly._init_params.<locals>.<dictcomp>  s>     3 3 3!T1%%1 WT1%%111r3   _render_countconfigr5   data_sourcesr6   framesautosizestretch_bothsizing_modestyles)r   r8   r   r%   rL   r   r   rU   r   r   rN   r   r   )rB   viewport_params
parametersrC   rQ   rR   r   r6   s   `       r1   _init_paramszPlotly._init_params  sc   DDdjDDD**++O;
3 3 3 3z 3 3 3 ;'DD//$+..C,,S11D))$//G"&"4;,"x&"--v!(~$(HHXr$:$::x688Hb11x::j!! 	&d&6$*:P:X&X&X$2F=!v%%#%x r3   c                   t                                          |          }d|v sd|v rd|v r	|d         }nA| j        r8t          | j                                                  d         d         j        }n|S |                    di                               di                               di                               dd          }|                    dg           d| d	gz   |d<   |S )
Nr6   stylesheetsr   templatefontcolorblackz?:host { --plotly-icon-color: gray; --plotly-active-icon-color: z; })r=   _process_param_changer   r8   valuesr6   rN   )rB   rC   propsr6   	btn_colorrD   s        r1   r   zPlotly._process_param_change&  s    --f55u 6 65  x dl113344Q7:A

:r2266xDDHHQSTTXXY`bijjI#(99]B#?#?bS\bbbC $E-  r3   r   r   rootOptional[Model]parentcommOptional[Comm]r   c                    t          ddt          |t                    |          | _        t	                                          ||||          S )Nzpanel.models.plotly
PlotlyPlot)r   r7   r   _bokeh_modelr=   
_get_model)rB   r   r   r   r   rD   s        r1   r   zPlotly._get_model6  sK     &!<D+1N1NPT
 
 ww!!#tVT:::r3   r   r`   modelNonec                z   | j         )|                    g i            |xj        dz  c_        d S |                     | j                   }|                     |          }|                    d          }|                    d          }|d         }g }d}	t          |          D ]f\  }
}|
t          |j                  k     r|j        |
         }n#t                      }|
                    |           |                     ||          p|	}	g	 |j        |k    }n# t          $ r d}Y nw xY wt          |j                  t          |          k    rd}nsd}t          ||j                  D ][\  }}	 d |                                D             d	 |                                D             k    }n# t          $ r d}Y nw xY w|r n\	 |j        |k    }n# t          $ r d}Y nw xY wi }| j        | j        j        j        u r^d
|v rZ|                    d
          }t+          |j                  }|r|j        dk    rd|d<   d|d<   n|s|j        dk    rd|d<   d|v r|d= |r|j        |z   |d<   |r|                    d          |d<   |r||d<   |r|pg |d<   |r |j        di | |s|	r|xj        dz  c_        d S d S )NrF   r   r6   r   r5   FTc                &    i | ]\  }}|d k    ||S uidr   r.   kr   s      r1   r   z"Plotly._update.<locals>.<dictcomp>d  #    DDD$!QeAr3   c                &    i | ]\  }}|d k    ||S r   r   r   s      r1   r   z"Plotly._update.<locals>.<dictcomp>e  r   r3   r   r   r   contentsdisplayfixedr   r   )r%   updater   rL   r   rN   r_   r   r   r
   rP   r   r6   r   r5   ziprZ   r   r   r   r   r;   r   )rB   r   r   r   rQ   r6   r   rS   new_sourcesr   rd   rT   r   update_layoutupdate_datar   r   update_framesupdatesr   r   s                        r1   _updatezPlotly._update?  s   ;LLbL,,,1$Foodk**((--(##(##f!&)) 	U 	UHAu3u)****(+&((""3'''!66sEBBTnNN	!!LF2MM 	! 	! 	! MMM	! 
OOs6{{**KKK
33 	 	S'DD#))++DDDDD#))++DDDE  K ! ' ' '"&KKK' E	!!LF2MM 	! 	! 	! MMM	! tz5===*PVBVBVzz*--H%,''F *E-??)7&$.y!! *%"3w">">)0&&&y) 	G&+&8;&FGN# 	/"hhv..GFO 	' &GH 	- &"GH 	$EL##7###  	%n 	%1$	% 	%s6   D D('D(0>F//F>=F>G G"!G")r'   r   r(   r)   r,   )rV   )NN)NNN)
r   r   r   r   r   r   r   r   r(   r   )r   r`   r   r   r(   r   )3__name__
__module____qualname____doc__r   Dict
click_dataclickannotation_datar   
hover_dataBooleanr$   r   r   r   selected_datar   Selectorviewport_update_policyIntegerviewport_update_throttler   r!   __annotations__r   r"   r#   r&   classmethodr-   r>   rL   staticmethodrU   rO   dependsrA   r|   r{   r   r   r   r}   rl   r   r   r   r   r   r   __classcell__)rD   s   @r1   r   r      s         &  5666J%5:*IJJJUZDm<<<F 5666J%- 3  ! ! !K EJ45MNNNM5:$4KLLLLEJ45MNNNMuzd0HIIIH+U^I D ;::< < <  -u}S QC  D  D  D "EM! 2= > > >M /2H1111 ###)L      $H#### t3 3G     [ [ [ [[
     3 3 3   \    \" U]8]$777  87(G G G GO O O O U]>...8 8 /.8
 U]?$///4 4 0/4 
 
 \
 OS0 0 0 0    8   \&  2    " 6:?C; ; ; ; ; ; ;P% P% P% P% P% P% P% P%r3   r   ) r   
__future__r   typingr   r   r   r   r   r	   numpyr\   r   bokeh.modelsr
   pyviz_commsr   io.resourcesr   utilr   r   viewabler   baser   bokeh.documentr   bokeh.modelr   r   r   r   r3   r1   <module>r     sx    # " " " " "                     ) ) ) ) ) ) # # # # # # # # # # # # ( ( ( ( ( ( ( ( ! ! ! ! ! !       !''''''!!!!!!      s% s% s% s% s%Y s% s% s% s% s%r3   