
    e`                        d dl Z d dlZd dlZd dlZd dlmZ d dlmZ d dlZ	d dl
mZmZmZ d dlmZmZ d dlmZmZmZmZmZmZmZ d dlmZ d dlmZmZ 	 d d	lmZm Z  n# e!$ r d dl"Zd dl#Z Y nw xY wd dl$m%Z& d d
lm'Z' d dl(m)Z)m*Z*m+Z+  e	j,        d            edg d          Z- edg d          Z. edg d          Z/d Z0	 d!dZ1d Z2d Z3d Z4d Z5d Z6d Z7d Z8dej9        e j:        ddfdZ;d  Z<dS )"    N)
namedtuple)PreventUpdate)expr_to_fn_of_stream_contentsinitialize_dynamicto_expr_extract_streams)
DynamicMapPlotlyRenderer)BoundsXCallbackBoundsXYCallbackBoundsYCallbackRangeXCallbackRangeXYCallbackRangeYCallbackSelection1DCallback) clean_internal_figure_properties)DerivedHistory)dcchtml)callback_context)InputOutputStateplotlyStreamCallback	input_idsfn	output_idDashComponents)graphskdimsstoreresetschildrenHoloViewsFunctionSpecr   r"   streamsc                    i }| j         }|d         D ]}|                    d          r)d|d         |         v rd|d         |         d         i||<   |                    d          rWi }d|d         |         v r|d         |         d         |d<   d|d         |         v r|d         |         d         |d<   |r|||<   |S )Nlayoutxaxisyaxisrangemapboxcenterzoom)state
startswith)plotlayout_rangesfig_dictkmapbox_rangess        >lib/python3.11/site-packages/holoviews/plotting/plotly/dash.pyget_layout_rangesr:   5   s    MzHh 1 1<<*++ 	M(8,Q///$+Xh-?-B7-K#La <<!! 	1M8H-a000*28*<Q*?*Ih'(+A...(0(:1(=f(Ef% 1#0a     Tc                    | j         }t          |           dt          |          z   |d         d<   |r|r|d         D ]}|                    d          r"|d         |                             dd           |                    d          rD|d         |                             dd           |d         |                             d	d           |r|d                             d
d           |du s|dk    r|d                             dd           |du s|dk    r|d                             dd           t          j        |          }|r|r|                    |           |S )a  
    Convert a HoloViews plotly plot to a plotly.py Figure.

    Args:
        plot: A HoloViews plotly plot object
        reset_nclicks: Number of times a reset button associated with the plot has been
            clicked

    Returns:
        A plotly.py Figure
    reset-r*   
uirevisionr+   r.   Nr/   r1   r0   autosizeTwidthheight)r2   r   strr3   popgoFigureupdate_layout)r4   reset_nclicksr5   
responsive
use_rangesr6   r7   figs           r9   plot_to_figurerK   I   s    zH$X... (0#m2D2D'DHX|$  : :(# 	: 	:A||.// 9"1%))'4888||H%% :"1%))&$777"1%))(D999  1z4000TZ722w---TZ833x... )H

C ) )-(((Jr;   c                 0   g }g }g }i }t          |            t          | ||||          }t          |t          |                    }t	          | t
                    rP| j        rId                    d | j        D                       }d}t          |	                    |                    d | 
                                D             }	i }
|D ]5}|	|j                 }|j        p|j        }||j        p|j        f|
|j        <   6t          ||
|          S )a  
    Convert Dynamic HoloViews object into a pure function that accepts kdim values
    and stream contents as positional arguments.

    This borrows the low-level holoviews decollate logic, but instead of returning
    DynamicMap with cloned streams, returns a HoloViewsFunctionSpec.

    Args:
        hvobj: A potentially dynamic Holoviews object

    Returns:
        HoloViewsFunctionSpec
    )nkdimsz, c              3      K   | ]}|V  d S N ).0dims     r9   	<genexpr>z#to_function_spec.<locals>.<genexpr>   s$      ??C??????r;   zDynamicMap cannot be displayed without explicit indexing as {dims} dimension(s) are unbounded. 
Set dimensions bounds with the DynamicMap redim.range or redim.values methods.)dimsc                     i | ]
}|j         |S rP   )name)rQ   ds     r9   
<dictcomp>z$to_function_spec.<locals>.<dictcomp>   s    ===Qqvq===r;   r'   )r   r   r   len
isinstancer   	unboundedjoin
ValueErrorformat
dimensionsrV   labelvaluesr.   r&   )hvobj
kdims_listoriginal_streamsr(   stream_mappingexprexpr_fnrT   msgdimensions_dictr"   r7   rR   r`   s                 r9   to_function_specrj   z   s@    JGNu"z7$4n D ,DZIIIG %$$ 0 0yy??u?????* ../// >=%*:*:*<*<===OE 7 7af%	%SXsz6SY6af G5BRSSSSr;   c                    |D ]}t          j        |j                  | d         t          |          <   t	          |t
                    rt          | |j                   \t	          |t                    rt          | |j	        g           dS )z
    Add contents of streams to the store dictionary

    Args:
        store_data: The store dictionary
        streams: List of streams whose contents should be added to the store

    Returns:
        None
    r(   N)
copydeepcopycontentsidrZ   r   #populate_store_with_stream_contentsinput_streamsr   input_stream)
store_datar(   streams      r9   rp   rp      s      S S,0M&/,J,J
9bjj)fg&& 	S/
F<PQQQQ(( 	S/
V=P<QRRRS Sr;   c                     d | j         D             }t          j        | j                  | j        fd}t	          ||t          |                     S )z
    Build StreamCallback for Derived stream

    Args:
        derived_stream: A Derived stream

    Returns:
        StreamCallback
    c                 ,    g | ]}t          |          S rP   ro   rQ   rt   s     r9   
<listcomp>z*build_derived_callback.<locals>.<listcomp>   s    GGGFGGGr;   c                       |           S )N)stream_values	constantsrP   )r{   r|   	transforms    r9   derived_callbackz0build_derived_callback.<locals>.derived_callback   s    y}	JJJJr;   r   )rq   rl   r|   transform_functionr   ro   )derived_streamr   r~   r|   r}   s      @@r9   build_derived_callbackr      s     HG.*FGGGI	.233I1IK K K K K K  0B~<N<N   r;   c                 v    t          |           }t          | j                  }d }t          ||g||          S )z
    Build StreamCallback for History stream

    Args:
        history_stream: A History stream

    Returns:
        StreamCallback
    c                 d    t          j        |           }|d                             |           |S )Nra   )rl   rm   append)prior_valueinput_value	new_values      r9   history_callbackz0build_history_callback.<locals>.history_callback   s0    M+..	("";///r;   r   )ro   rr   r   )history_stream
history_idinput_stream_idr   s       r9   build_history_callbackr      sW     N##J455O  
 /   r;   c                 D   |D ]}t          |t                    r8t          |          }|j        | vr|| |j        <   t	          | |j                   Ot          |t                    r8t          |          }|j        | vr || |j        <   t	          | |j        g           dS )a6  
    Populate the stream_callbacks dict with StreamCallback instances
    associated with all of the History and Derived streams in input stream list.

    Input streams to any History or Derived streams are processed recursively

    Args:
        stream_callbacks:  dict from id(stream) to StreamCallbacks the should
            be populated. Order will be a breadth-first traversal of the provided
            streams list, and any input streams that these depend on.

        streams: List of streams to build StreamCallbacks from

    Returns:
        None
    N)	rZ   r   r   r   populate_stream_callback_graphrq   r   r   rr   )stream_callbacksr(   rt   cbs       r9   r   r      s    "  
X 
Xfg&& 		X'//B|#33313 ../?AUVVV(( 	X'//B|#33313 ../?&BUAVWWW
X 
Xr;   c                 x    dt          j        t          j        |                                         d          iS )a  
    Encode store_data dict into a JSON serializable dict

    This is currently done by pickling store_data and converting to a base64 encoded
    string. If HoloViews supports JSON serialization in the future, this method could
    be updated to use this approach instead

    Args:
        store_data: dict potentially containing HoloViews objects

    Returns:
        dict that can be JSON serialized
    pickledzutf-8)base64	b64encodepickledumpsdecoders   s    r9   encode_store_datar   	  s2     v'Z(@(@AAHHQQRRr;   c                 Z    t          j        t          j        | d                             S )z
    Decode a dict that was encoded by the encode_store_data function.

    Args:
        store_data: dict that was encoded by encode_store_data

    Returns:
        decoded dict
    r   )r   loadsr   	b64decoder   s    r9   decode_store_datar     s$     <(I)>??@@@r;   Fr@   c                   /012345678 t          |          6g }g }i }	g }
g }g }g }g 1g 2i /g 4i 8i }i 0t          t          t          t          t
          t          t          g}g 5t          |          D ]|\  }}t          |          }|||<   4
                    t          |j                             /                    |j                   t          j        |          }|
                    |           5
                    t!          |                     t#          |d5d                                                   }2
                    |           dt'          t)          j                              z   }1
                    |            |||ddi          }|
                    |           i }|D ]Z}|d         D ]O}|                    d	d
          |j        v r0|j        |d	                  |                    |i           |d	         <   P[|                                D ]k\  }}|                                D ]Q\  }}8                    |i                               |g                               d |j        D                        Rl|

                    t9          |d                     |                    t;          |d          t;          |d          g           ~di i}dt'          t)          j                              z   }|
                    t=          |d                     |                                D ]}tA          ||j                   i 7|                                D ]}tC          7|j                   |                                D ] \  }}|j"        d |j        D             f0|<   !tG          j$        |tK          |                    }|

                    t9          |d                     tM          j'        |d                   3g } /                                D ]@\  }!\  }"}#t'          t)          j                              }$|!dz   |$z   }%|!dz   |$z   }&| 
                    |$           tQ          j)        |&|"          }'tU          |#t                    rLtQ          j+        |'tG          j,        |%|#d         |#d         d
d |#D             |#d                   g          }(nRtQ          j+        |'tG          j,        |%|#d         |#d         |#d         |#d         z
  dz  |#d                   g          }(|(|	|!<   |
                    t;          |%d                     Bridt'          t)          j                              z   }) ||)d          |
                    t;          |)d                     |
                               | -                    |
||          /012345678fd             }*t          /          D ]o\  }}!/|!         d         }"|!dz   | |         z   }+|!dz   | |         z   },| -                    t9          |,d!          t;          |+d          g          |"fd"            }-pt]          ||	|||t          |	                                          z   |z   |gz   #          }.|.S )$a  
    Build Dash components and callbacks from a collection of HoloViews objects

    Args:
        app: dash.Dash application instance
        hvobjs: List of HoloViews objects to build Dash components from
        reset_button: If True, construct a Button component that, which clicked, will
            reset the interactive stream values associated with the provided HoloViews
            objects to their initial values. Defaults to False.
        graph_class: Class to use when creating Graph components, one of dcc.Graph
            (default) or ddk.Graph.
        button_class: Class to use when creating reset button component.
            E.g. html.Button (default) or dbc.Button
        responsive: If True graphs will fill their containers width and height
            responsively. If False, graphs will have a fixed size matching their
            HoloViews size. If "width" (default), the width is responsive but
            height matches the HoloViews size. If "height", the height is responsive
            but the width matches the HoloViews size.
        use_ranges: If True, initialize graphs with the dimension ranges specified
            in the HoloViews objects. If False, allow Dash to perform its own
            auto-range calculations.
    Returns:
        DashComponents named tuple with properties:
            - graphs: List of graph components (with type matching the input
                graph_class argument) with order corresponding to the order
                of the input hvobjs list.
            - resets: List of reset buttons that can be used to reset figure state.
                List has length 1 if reset_button=True and is empty if
                reset_button=False.
            - kdims: Dict from kdim names to Dash Components that can be used to
                set the corresponding kdim value.
            - store: dcc.Store the must be included in the app layout
            - children: Single list of all components above. The order is graphs,
                kdims, resets, and then the store.
    r   rG   r5   rH   rI   zgraph-
scrollZoomT)ro   figureconfigdatauidNc                 ,    g | ]}t          |          S rP   rw   rx   s     r9   ry   zto_dash.<locals>.<listcomp>  s    999FRZZ999r;   r   )component_idcomponent_propertyselectedDatarelayoutDatar(   zstore-c                 ,    g | ]}t          |          S rP   rw   rx   s     r9   ry   zto_dash.<locals>.<listcomp>  s    .X.X.Xfr&zz.X.X.Xr;   )ro   r   -z-label-)ro   r%   c                     i | ]}|d S ) rP   )rQ   ms     r9   rX   zto_dash.<locals>.<dictcomp>  s'       "#2  r;   )ro   minmaxstepmarksvalue)r%   g      &@)ro   r   r   r   r   r   r=   Resetn_clicksc            	          d t           j        D             } fdt          d$dz  d          D             } fdt          d$dz  d          D             }d}t           d                   d}%r\ d	         pd}                    d
d          }||k    r6|d
<   t          j        !          d<   d |D             }d |D             }d}di i                    di            t          t          $dz  $dz  t                    z                       D ]:\  }}|d         vsd         |          |         k    r |         d         |<   d};t          t                               D ]}	|	         }
(
                                D ]\  }}|j        D ]}|dk    r>|
dz   |v r6|                    |||	          |	                   }t          ||          p|}F|dk    r\|
dz   |v rT|                    |||	          |	                   }d |
                                D             }t          ||          p|}|dk    r=|
dz   |v r6|                    |||	          |	                   }t          ||          p|}|st          t          '          D ]=}'|         }|j        }|j        }|j        }fd|D             } || }|d         |<   >d g$z  }
                                D ]w\  }	\  }}fd"|	         D             }fd|D             } |||z    }t'          j        |          }t+          ||#|	         &)                                          }|||	<   x|t/                    gz   S )Nc                     h | ]
}|d          S )prop_idrP   )rQ   entrys     r9   	<setcomp>z1to_dash.<locals>.update_figure.<locals>.<setcomp>  s    WWW5eI.WWWr;   c                 $    g | ]}|         pi S rP   rP   rQ   jargss     r9   ry   z2to_dash.<locals>.update_figure.<locals>.<listcomp>  !    KKKA$q'-RKKKr;   r      c                 $    g | ]}|         pi S rP   rP   r   s     r9   ry   z2to_dash.<locals>.update_figure.<locals>.<listcomp>  r   r;      Fr   rG   r(   c                     g | ]}d S rO   rP   rQ   _s     r9   ry   z2to_dash.<locals>.update_figure.<locals>.<listcomp>      !?!?!?1$!?!?!?r;   c                     g | ]}d S rO   rP   r   s     r9   ry   z2to_dash.<locals>.update_figure.<locals>.<listcomp>  r   r;   Tr"   selected_dataz.selectedDataviewportz.relayoutDatac                 :    i | ]\  }}|d          |d         ||S )x_rangeNy_rangerP   )rQ   r   
event_datas      r9   rX   z2to_dash.<locals>.update_figure.<locals>.<dictcomp>6  sA     1 1 1$3C#-i#8#D#-y#9#E !$Z $F#E#Er;   relayout_datac                 ,    g | ]}d          |         S r(   rP   )rQ   input_idrs   s     r9   ry   z2to_dash.<locals>.update_figure.<locals>.<listcomp>R  s#    VVVJy1(;VVVr;   c                 ,    g | ]}d          |         S )r"   rP   )rQ   kdrs   s     r9   ry   z2to_dash.<locals>.update_figure.<locals>.<listcomp>X  s#    XXX2z'226XXXr;   c                 ,    g | ]}d          |         S r   rP   )rQ   	stream_idrs   s     r9   ry   z2to_dash.<locals>.update_figure.<locals>.<listcomp>Y  s0       5>
9%i0  r;   r   )r   	triggeredr.   r   getrl   rm   
setdefaultziprY   itemscallback_properties#get_event_data_from_property_updateupdate_stream_values_for_typer   reversedr   r   r   r	   get_plotrK   to_dictr   )*r   triggered_prop_idsselected_dictsrelayout_dicts
any_changerG   prior_reset_nclicksikdimfig_indgraph_idplotly_stream_typeuid_to_streams_for_type
panel_propstream_event_datar   stream_callbackr   r   input_valuesoutput_valuefigs
stream_idsfig_kdim_valuesr{   rb   r4   rJ   rs   	all_kdimsfig_to_fn_stream_ids	graph_idsinitial_fig_dictsinitial_stream_contentskdims_per_figr5   num_figsreset_buttonrH   r   uid_to_stream_idsrI   s*   `                           @r9   update_figurezto_dash.<locals>.update_figure  s    XW<L<VWWW LKKKq(Q,1J1JKKKKKKKq(Q,1J1JKKK 
&tBx00
 
	" HMM",..!"D"D 333.;
?+ )-6M(N(N
9%!?!?!?!?!?!?!?!?!?!?!
 #RJ 	gr***hlHqL3y>>$ABB
 
 	" 	"GAt :g...*W2Ed2KtTUw2V2V,0G
7#D)!
 S!23344 '	, '	,G )H?P?V?V?X?X $, $,;"$;"4"H #, #,J!_44#o59KKK 1C0f0f *N7,CEVW^E_1 1- *G *,=?V* * *,!+ ' $z11#o59KKK0B0f0f *N7,CEVW^E_1 1-1 17H7N7N7P7P1 1 1- *G *,=?V* * *,!+ ' $66#o59KKK0B0f0f *N7,CEVW^E_1 1- *G *,=?V* * *,!+ 'C#,$,L  	  ""233 	< 	<I.y9O'1I #B'1IVVVVIVVVL2|,L/;Jy!),,v )=)C)C)E)E 	  	 %G%b*XXXXwAWXXXO   BL  M B=8:E!*511D M+G4%   gii	 
  DMM(44555r;   r%   c                     | d| dS )Nz: z.2frP   )r   
kdim_labels     r9   update_kdim_labelz"to_dash.<locals>.update_kdim_labeln  s    
 !//E////r;   )r!   r"   r$   r#   r%   )/rY   r   r   r   r   r   r
   r   	enumeraterj   r   listr"   updater	   r   r:   rK   r   rB   uuiduuid4r   	instancesr   r   extendr(   r   r   r   ra   rp   r   r   r   Storer   rl   rm   r   LabelrZ   DivSlidercallbackr    )9apphvobjsr   graph_classbutton_classrH   rI   reset_componentsgraph_componentskdim_componentsoutputsinputsstatesplotsfig_to_fn_streamplotly_stream_typesr   rb   fn_specr4   rJ   r   graphplotly_streamsr   tstreams_for_typer   r   rs   store_idr#   
kdim_uuids	kdim_namer  
kdim_rangeslider_uuid	slider_idslider_label_id
html_labelsliderreset_idr   kdim_slider_idkdim_label_idr  
componentsr   r   r   r   r   r   r5   r   r   r   s9     `  ``                                        @@@@@@@@@@r9   to_dashr.  '  sT   P 6{{H O GFF EIIM  	9L/? Mf%% 2 25"5))%T'-00111''' &u--T.t44555r1B!j
 
 
 ')) 	 	  %%% c$*,,///""" $'
 
 

 	&&& "5 	? 	?[ ? ?55%%);)EEE*4QuX> #--.@"EEahO? 5C4H4H4J4J 	 	0 0+1133  R!,,& *S"%%ff99bj999' ' ' ' 	v8QQQRRRxNKKKxNKKK
 	 	 	 	 RJ#djll+++H
MM%&))***
 $**,, I I+JHHHH #**,, J J&'7IIII ',,.. Y Y
7")*.X.X.X.X.X"XQ Iz**  E NN6(F++,,, #mJy,ABB J/8/@/@ !Q !Q+	+J
$*,,''Ok1	#i/+=+&&&Z?ZHHH
j$'' 	X
 "1"2 '1   %Q-	 	 	(   FF X
 "1"2$R.:a=8D@$Q-  (   F &,	"ewOOOPPPP  .c$*,,///#|x'BBBe!j
 
 
 	 	 	 	--- 	\\ l6 l6 l6 l6 l6 l6 l6 l6 l6 l6 l6 l6 l6 l6 l6 l6 l6` "),, 
0 
09y)!,
"S:a=8!I-
1=	*MMM7KKKL

 

 1; 	0 	0 	0	

 

	0 	0   _++--../ !   J r;   c                     d}|                                 D ]=\  }}||v r4||         D ]+}|| d         vs| d         |         |k    r|| d         |<   d},>|S )a  
    Update the store with values of streams for a single type

    Args:
        store_data: Current store dictionary
        stream_event_data:  Potential stream data for current plotly event and
            traces in figures
        uid_to_streams_for_type: Mapping from trace UIDs to HoloViews streams of
            a particular type
    Returns:
        any_change: Whether any stream value has been updated
    Fr(   T)r   )rs   r   r   r   r   r   r   s          r9   r   r     s     J,2244 & &Z)))4S9 & &	Jy$999"9-i8JFF7AJy))4!%Jr;   )r   NTT)=r   rl   r   r  collectionsr   dash.exceptionsr   	holoviewshvholoviews.core.decollater   r   r   holoviews.plotting.plotlyr   r	   #holoviews.plotting.plotly.callbacksr
   r   r   r   r   r   r   holoviews.plotting.plotly.utilr   holoviews.streamsr   r   dashr   r   ImportErrordash_core_componentsdash_html_componentsplotly.graph_objectsgraph_objectsrD   r   dash.dependenciesr   r   r   	extensionr   r    r&   r:   rK   rj   rp   r   r   r   r   r   GraphButtonr.  r   rP   r;   r9   <module>rC     s       " " " " " " ) ) ) ) ) )             
 A @ @ @ @ @ @ @                  L K K K K K . . . . . . . .( ( ( (&&&&''''''( " ! ! ! ! ! ! ! ! ! ! ! 2 2 2 2 2 2 2 2 2 2 X    ,.N.N.NOOHHH  #
#:<V<V<VWW   * PT. . . .b)T )T )TXS S S,  ,  2X X X<S S S"
A 
A 
A #(SY[W\ \ \ \~
    s   A A-,A-