
    I.e7S                     T   d dl mZ d dlZd dlZd dlZd dlm	Z	 d dlm
Z
mZ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 d	dlmZ d	dlmZmZ ej        r$ eej        dd          s ej        dd           de
f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*d Z+dS )    )defaultdictN)	HoverTool)GraphLabelsdim)Storedimension_sanitizer)	GraphPlot
LabelsPlot)markers   )_transfer_opts_cur_backend)process_crs)saveshow_loadedFbokeh)logoc                     t          t                    |                                 D ]\  }}t          | j        |         |                                                   D ]=\  }}t          |t          t          f          r"|                             |           >t          |t                    rt          |          }t          |t                    rt          |          }d                             |           d                             |           t          fdD                       }	d |	D             }
t          fdddg|	z   D                       }j        j        dd         \   }}|rx|                                |j        d         j        t          fd	                                D              \  }}d
 t                   t          |           D             }ng }d}t          t                    |                                D ]@\  }}| j                            |          }|#|\  }} j                                     |           |j                                     |           |                                D ]C\  }}t          |t          t          t          f          r(|                             |           Dt%          |          D ],\  }}|                             ||         |                    -t          |t                    rt          |          }|j                                     |           Bt           fdD                       } j        |j        |j        g|z   t          |          z   }t          fd|D                       }g }|D ]_}t          |t&                    rt          |          }n#|||j        v r|                    |          }n|}|                    |           `                    ||          } ||f|
          S )aF  
    Generate a Graph element from a networkx.Graph object and networkx
    layout function or dictionary of node positions.  Any keyword
    arguments will be passed to the layout function. By default it
    will extract all node and edge attributes from the networkx.Graph
    but explicit node information may also be supplied. Any non-scalar
    attributes, such as lists or dictionaries will be ignored.

    Parameters
    ----------
    G : networkx.Graph
       Graph to convert to Graph element
    positions : dict or callable
       Node positions defined as a dictionary mapping from node id to
       (x, y) tuple or networkx layout function which computes a
       positions dictionary.
    kwargs : dict
       Keyword arguments for the element

    Returns
    -------
    graph : holoviews.Graph
       Graph element
    startendc              3   |   K   | ]6}|d vr0t          |                   t          d                   k    2|V  7dS ))r   r   r   N)len).0kedgess     /lib/python3.11/site-packages/hvplot/networkx.py	<genexpr>z!_from_networkx.<locals>.<genexpr>?   s^       B BQ14D+D+DaMMSw-@-@@@ @@@@B B    c                 Z    g | ](}t          |t                    rt          |          n|)S  )
isinstanceintstr)r   cols     r   
<listcomp>z"_from_networkx.<locals>.<listcomp>A   s1    QQQjc22;#c(((QQQr    c              3   (   K   | ]}|         V  d S Nr"   )r   r&   r   s     r   r   z!_from_networkx.<locals>.<genexpr>B   s'      GGSeCjGGGGGGr    N   r   c              3   2   K   | ]\  }}|k    ||fV  d S r)   r"   )r   r   vidx_dims      r   r   z!_from_networkx.<locals>.<genexpr>I   s0      !Z!ZTQQRY\\1a&\\\\!Z!Zr    c                     i | ]\  }}||	S r"   r"   )r   ivalss      r   
<dictcomp>z"_from_networkx.<locals>.<dictcomp>J   s    UUUDQUUUr    c              3      K   | ]E}|j         j        vr5t          |                   t          j                           k    A|V  Fd S r)   )	node_typekdimsr   name)r   r   clsnode_columnsxdims     r   r   z!_from_networkx.<locals>.<genexpr>a   sg       R RQ!3=;N2N2NQ00CTY8O4P4PPP PPPPR Rr    c              3   (   K   | ]}|         V  d S r)   r"   )r   r&   r7   s     r   r   z!_from_networkx.<locals>.<genexpr>d   s(      ;;Cl3';;;;;;r    )vdims)r   listr   sortedadjitemsr#   dictappendtupler%   r3   r4   columnsr5   zipnodesget	enumerater$   r:   get_dimension)!G	positionsrD   r6   kwargsr   r   attrvalue	edge_cols
edge_vdims	edge_dataydimidim	info_colsvalues	node_infoidxposnodexyr/   r&   	node_colsrB   	node_datar:   r   r   r-   r7   r8   s!      `                         @@@@r   _from_networkxr\      s   6 Eggii ! !
s!!%,s"3"9"9";";<< 	& 	&KD%%$.. $Ku%%%% eU## 	JJEc5!! 	c((Cge$$$eC     B B B B% B B B B BIQQyQQQJGGGGWe,<Y,FGGGGGI }*2A2.D$ }}+a.%!Z!Z!Z!Z\5G5G5I5I!Z!Z!Z[	6UUCW0EsF|,T,TUUU				t$$L OO%% , ,Sw{{3<1TY&&q)))TY&&q)))::<< 	- 	-KD%%$e!455 %%e,,,,	** 	8 	8FAs$$Ys^A%67777c5!! 	c((CTY&&s++++ R R R R R R, R R R R RIy$)TY/	9$y//IG;;;;7;;;;;I E  c3 	c((CC3%+#5#5%%c**CCCSMM)5M11E 3	5!4444r    c                 r   |t           j        j        }t          |t                    s || fi                     di           }i i }}t          }                    dd          sdv r`	 ddl}n# t          $ r t          d          w xY wt                              d                    }|j        }|j
        |d<   ||d<   ||d<   t          | |fi |d	v r4j        j        j        t          d	                            j        _        d
v r                    ddg          }g }	d
         D ]}
|	                    ||
k               t%          |	          r>t'          j        t&          j                            |	          j         }j        |         nj        dd                             dd          }t	          d                    dd                              dt          | t           j                                                dd                              dd                              dd                              dd                              dd          |d
  
        }	 |                    ddd           |                    fdt                    D                        d|v rPt          |d         t6                    rt9          |d                   |d<   t'          j        |d                   |d<   d|v r|                    d          |d <   d!|v r|                    d!          |d"<   d#v rc                    d#          }|t<          v r@t<          |         }|d$         }d%|v r't?          j         t          d&gd'           |d%         |d&<   ||d(<   d)v r                    d)          }||d*<   ||d+<   d,v r                    d,          |d-<   d.v r                    d.          |d/<   d0v r                    d0          |d1<   d2D ]}t          |                    |          t&          j!        t          tD          f          rY#                    j        j        $                    |t%          j        j%                  ||         d          f          |||<   d3D ]q}t          |                    |          t&          j!        t          tD          f          r5$                    |t%          j%                  ||         d          |||<   r|                    d           j        &                                v rf                    d4d                              d5d          f}|d6k    r4j        '                    |                    d                     }||_"        |                    d"          &                                v ra                    d7d                              d8d          f}|d6k    r/'                    |                    d"                    }||_"        |dk    r.fd9j        j(        d:d         j        j%        z   D             }nfd;j(        j%        z   D             }fd<|D             }tS          |=          d>g|d?<    j*        dOi |d@d'i                     dA                    dBd                    rhfdCt                    D             }dDv r                    dD          |dD<   dEv r                    dE          |dE<   dFv r                    dF          |dG<   dHv r                    dH          |dI<   dJv r                    dJ          |dK<                       dBj        j(        d:                   t          t                    rPj                            j        j(                  }fdL|D             } ||j        j(        dd:         dMfi |n" |j        j        j(        dd:         fi | j*        dOi |d@d'iz  dNv r(+                                        dN                    tY                    S )PaV  
    Draw the graph G using hvPlot.

    Draw the graph with hvPlot with options for node positions,
    labeling, titles, and many other drawing features.

    Parameters
    ----------
    G : graph
       A networkx graph
    pos : dictionary, optional
       A dictionary with nodes as keys and positions as values.
       If not specified a spring layout positioning will be computed.
       See :py:mod:`networkx.drawing.layout` for functions that
       compute node positions.
    arrows : bool, optional (default=True)
       For directed graphs, if True draw arrowheads.
       Note: Arrows will be the same color as edges.
    arrowhead_length : float, optional (default=0.025)
       The length of the arrows as fraction of the overall extent of
       the graph
    with_labels :  bool, optional (default=True)
       Set to True to draw labels on the nodes.
    nodelist : list, optional (default G.nodes())
       Draw only specified nodes
    edgelist : list, optional (default=G.edges())
       Draw only specified edges
    node_size : scalar or array, optional (default=300)
       Size of nodes.  If an array is specified it must be the
       same length as nodelist.
    node_color : color string, node attribute, or array of floats, (default='r')
       Can be a single color, the name of an attribute on the nodes or
       sequence of colors with the same length as nodelist.  If the
       node_color references an attribute on the nodes or is a list of
       values they will be colormapped using the cmap and vmin, vmax
       parameters.
    node_shape :  string, optional (default='o')
       The shape of the node. Specification is as valid bokeh marker.
    alpha : float, optional (default=1.0)
       The node and edge transparency
    cmap : Colormap, optional (default=None)
       Colormap for mapping intensities of nodes
    vmin,vmax : float, optional (default=None)
       Minimum and maximum for node colormap scaling
    linewidths : [None | scalar | sequence]
       Line width of symbol border (default =1.0)
    edge_width : float, optional (default=1.0)
       Line width of edges
    edge_color : color string, or array of floats (default='r')
       Can be a single color, the name of an attribute on the edges or
       sequence of colors with the same length as the edges.  If the
       edge_color references an attribute on the edges or is a list of
       values they will be colormapped using the edge_cmap and
       edge_vmin, edge_vmax parameters.
    edge_cmap : Matplotlib colormap, optional (default=None)
       Colormap for mapping intensities of edges
    edge_vmin,edge_vmax : floats, optional (default=None)
       Minimum and maximum for edge colormap scaling
    style : string, optional (default='solid')
       Edge line style (solid|dashed|dotted,dashdot)
    labels : dictionary or string, optional (default=None)
       Node labels in a dictionary keyed by node of text labels or
       a string referencing a node attribute
    font_size : int, optional (default=12)
       Font size for text labels
    font_color : string, optional (default='black')
       Font color string
    font_family : string, optional (default='sans-serif')
       Font family
    label : string, optional
       Label for graph legend
    selection_policy : string, optional (default='nodes')
       Whether to select 'nodes', 'edges' or None on tap and selection
       events.
    inspection_policy : string, optional (default='nodes')
       Whether to select 'nodes', 'edges' or None on tap and selection
       events.
    geo : boolean, optional (default=False)
       Whether to return a GeoViews graph
    crs : cartopy.crs.CRS
       A cartopy coordinate reference system (enables a geographic plot)
    height : int, optional (default=400)
       The height of the plot in pixels
    width : int, optional (default=400)
       The width of the plot in pixels
    Nlayout_kwargsgeoFcrsr   zsIn order to use geo-related features the geoviews library must be available. It can be installed with pip or conda.r6   nodelistedgelistr   inspection_policyrD   Tarrowhead_lengthg?arrowscolorbarpaddingg?widthi  heightselection_policyred)
axiswiserd   directedrf   rg   rh   ri   rj   rc   node_fill_color_axis_defaults)xaxisyaxis
show_framec                 X    i | ]&}|t           j        v |                    |          'S r"   )r   
style_optspopr   r   rJ   s     r   r1   zdraw.<locals>.<dictcomp>  s2    UUUa1	@T;T;TFJJqMM;T;T;Tr    	node_size
node_colorrn   
edge_coloredge_line_color
node_shapemarkerangle
node_angler   node_markeralpha
node_alpha
edge_alpha
linewidthsnode_line_width
edge_widthedge_line_widthstyleedge_line_dash)rn   rw   r   r   )rz   edge_line_alphar   r   vminvmax)NN	edge_vmin	edge_vmaxc                 L    g | ] }|j         |j        j        v rd n|j        f!S )index_hover)labelrD   r4   r5   r   dgs     r   r'   zdraw.<locals>.<listcomp>:  sJ     D D D 13E3E--16R D D Dr       c                 R    g | ]#}|j         |j        v r
|j        d z   n|j        f$S )_values)r   r4   r5   r   s     r   r'   zdraw.<locals>.<listcomp>=  sH     4 4 4 a17ll!&"2"2O 4 4 4r    c                 L    g | ] \  }}|z   v|d t          |          z  f!S )z@{%s}r	   )r   r   r5   edge_stylesnode_styless      r   r'   zdraw.<locals>.<listcomp>?  sL     Z Z ZE44{[?X3X3X "5d";";;<3X3X3Xr    )tooltipstaptoolsbackendwith_labelslabelsc                 X    i | ]&}|t           j        v |                    |          'S r"   )r   rt   ru   rv   s     r   r1   zdraw.<locals>.<dictcomp>G  s2    [[[1ZEZ@Z@ZaA@Z@Z@Zr    xoffsetyoffset	font_sizetext_font_size
font_color
text_colorfont_family	text_fontc                 6    g | ]\  }}}|v 
|||         fS r"   r"   )r   rX   rY   r/   r   s       r   r'   zdraw.<locals>.<listcomp>U  s/    MMM)1afQ6!9%r    textr   r"   )-nxdrawingspring_layoutr#   r?   rE   r   geoviewsImportErrorr   r   r\   rD   datailocr;   arrayr@   r   nplogical_and
logical_orreduceTru   DiGraphupdater%   r   sqrtr   r   add_style_optsndarrayrangecloneadd_dimensionr:   
dimensionsrG   r4   r   optsrelabelr   )rH   rV   rJ   paramslabel_paramslabel_elementr   r`   r   comparisonsedgeselectorrc   r   r|   marker_optsr   
node_style
edge_stylelims	dimensiontooltip_dimsr   
label_optsrS   r   r   r   r   r   s     `                       @@@@r   drawr   v   sn	   n {j&c4   8c!77vzz/26677rLFMzz% "5F??	HOOOO 	H 	H 	H G H H H	H &**U++,,  uu!U 	q#((((AVw|(fZ.@)A)ABVA:& 	. 	.Du}----{ 	~r}';';K'H'H'JKHx AArr
A 

#6@@$6>>HjBJ&?&?@@J..

9c**jj#&&zz(C(($6@@+
 
 
D>$du===KKUUUU4<<UUUVVVdd;'-- 	7 #D$5 6 6DGD$566[t"&((<"8"8t"&((<"8"8vL))W!&/K *F+%%$U\NGDDD%0%9\"$]&

7##"\"\v"(**\":":v"(**\":":&!'G!4!4SK! * *
dhhz**RZu,EFF 	*!6!6z3qw}CUCUW[\fWgim!n!noppA)DYK! * *
dhhz**RZu,EFF 	*
CLL$z:JDQQA)Dxx!""ag&8&8&:&:::

64((&**VT*B*BC<--dhh7H.I.IJJI"IOxx!""allnn44

;--vzz+t/L/LM<1B(C(CDDI"IOG##D D D D!"qrr!2QW]!BD D D4 4 4 4!"17!24 4 4Z Z Z Z Z#/Z Z ZH11159DM
AF##T##7#### zz-He!<!<== ;[[[[V[[[
$*JJy$9$9Jy!$*JJy$9$9Jy!&  +1::k+B+BJ'(6!!'-zz,'?'?J|$F""&,jj&?&?J{#HagmA&677fd## 	WW]]17=11FMMMMvMMMD"]4rr):FSSlSSFF"]17AGM"1",=vVVVVF::j::':::: &IIfjj))** 	#1%%AHs   1A6 6Bc                 (    d|d<   t          | |fi |S )ao  Draw a networkx graph.

    Draw the graph with hvPlot with options for node positions,
    labeling, titles, and many other drawing features. See draw() for
    simple drawing without labels or axes.

    Parameters
    ----------
    G : graph
       A networkx graph
    pos : dictionary, optional
       A dictionary with nodes as keys and positions as values or a
       layout `networkx.drawing.layout` function.  If not specified a
       spring layout positioning will be computed. See
       :py:mod:`networkx.drawing.layout` for functions that compute
       node positions.
    kwargs : optional keywords
       See hvplot.networkx.draw() for a description of optional
       keywords, with the exception of the pos parameter which is not
       used by this function.

    Returns
    -------
    graph : holoviews.Graph or holoviews.Overlay
       Graph element
    Fro   )r   rH   rV   rJ   s      r   draw_networkxr   e  s'    6  %F3!!&!!!r    c                     d|v r|                     d          |d<   |                     dd           d|d<   d|d<   d|d	<   d|d
<   t          | |fi |S )a  Draw networkx graph nodes.

    Parameters
    ----------
    G : graph
       A networkx graph
    kwargs : optional keywords
       See hvplot.networkx.draw() for a description of optional
       keywords, with the exception of the pos parameter which is not
       used by this function.

    Returns
    -------
    graph: holoviews.Graph or holoviews.Overlay
       Graph element
    r   r   rb   NFro   r   r   edge_hover_alphaedge_nonselection_alpha)ru   r   r   s      r   draw_networkx_nodesr     s|    " &%zz'22|
JJz4   $FF<!"F()F$%3!!&!!!r    c                    d|v r|                     d          |d<   |                     dd           d|d<   d|d<   d|d<   d	|d
<   |                    d          d|d<   |                    d          d|d<   t          | |fi |S )a  Draw networkx graph edges.

    Parameters
    ----------
    G : graph
       A networkx graph
    kwargs : optional keywords
       See hvplot.networkx.draw() for a description of optional
       keywords, with the exception of the pos parameter which is not
       used by this function.

    Returns
    -------
    graph : holoviews.Graph or (holoviews.Graph * holoviews.Labels)
       Graph element
    r   r   ra   Nr   r   node_hover_alphanode_nonselection_alphaFro   rj   r   rc   )ru   rE   r   r   s      r   draw_networkx_edgesr     s    " &%zz'22|
JJz4   F<!"F()F$%$Fzz$%%1%,!"zz%&&2&-"#3!!&!!!r    c                     t          | |fi |}t          |j        |j        j        dd         |j        j        d                   S )aw  Draw networkx graph node labels.

    Parameters
    ----------
    G : graph
       A networkx graph
    kwargs : optional keywords
       See hvplot.networkx.draw() for a description of optional
       keywords, with the exception of the pos parameter which is not
       used by this function.

    Returns
    -------
    graph : Labels element
       Labels element
    Nr   )r   r   rD   r4   )rH   rV   rJ   r   s       r   draw_networkx_labelsr     sE    " 	QvA!'17=!,agmA.>???r    c                 4    t          | fdt          j        i|S a  Draw networkx graph with circular layout.

    Parameters
    ----------
    G : graph
       A networkx graph
    kwargs : optional keywords
       See hvplot.networkx.draw() for a description of optional
       keywords, with the exception of the pos parameter which is not
       used by this function.

    Returns
    -------
    graph : holoviews.Graph or holoviews.Overlay
       Graph element or Graph and Labels
    rV   )r   r   circular_layoutrH   rJ   s     r   draw_circularr     s"    " 44r)4V444r    c                 4    t          | fdt          j        i|S r   )r   r   kamada_kawai_layoutr   s     r   draw_kamada_kawair     s"    " 88r-8888r    c                 2    t          | t          j        fi |S )a  Draw networkx graph with random layout.

    Parameters
    ----------
    G : graph
       A networkx graph
    kwargs : optional keywords
       See hvplot.networkx.draw() for a description of optional
       keywords, with the exception of the pos parameter which is not
       used by this function.

    Returns
    -------
    graph : holoviews.Graph or holoviews.Overlay
       Graph element
    )r   r   random_layoutr   s     r   draw_randomr         " 2#..v...r    c                 p    |                     dd          }|d|i|d<   t          | t          j        fi |S )a  Draw networkx graph with shell layout.

    Parameters
    ----------
    G : graph
       A networkx graph
    kwargs : optional keywords
       See hvplot.networkx.draw() for a description of optional
       keywords, with the exception of the pos parameter which is not
       used by this function.

    Returns
    -------
    graph : holoviews.Graph or holoviews.Overlay
       Graph element or Graph and Labels
    nlistNr^   )ru   r   r   shell_layout)rH   rJ   r   s      r   
draw_shellr     sF    " JJw%%E#*E"22?--f---r    c                 2    t          | t          j        fi |S )a  Draw networkx graph with spectral layout.

    Parameters
    ----------
    G : graph
       A networkx graph
    kwargs : optional keywords
       See hvplot.networkx.draw() for a description of optional
       keywords, with the exception of the pos parameter which is not
       used by this function.

    Returns
    -------
    graph : holoviews.Graph or holoviews.Overlay
       Graph element or Graph and Labels
    )r   r   spectral_layoutr   s     r   draw_spectralr   &  s    " 2%00000r    c                 2    t          | t          j        fi |S )a  Draw networkx graph with spring layout.

    Parameters
    ----------
    G : graph
       A networkx graph
    kwargs : optional keywords
       See hvplot.networkx.draw() for a description of optional
       keywords, with the exception of the pos parameter which is not
       used by this function.

    Returns
    -------
    graph : holoviews.Graph or holoviews.Overlay
       Graph element or Graph and Labels
    )r   r   r   r   s     r   draw_springr   :  r   r    c                 2    t          | t          j        fi |S )a  Draw networkx graph with planar layout.

    Parameters
    ----------
    G : graph
       A networkx graph
    kwargs : optional keywords
       See hvplot.networkx.draw() for a description of optional
       keywords, with the exception of the pos parameter which is not
       used by this function.

    Returns
    -------
    graph : holoviews.Graph or holoviews.Overlay
       Graph element or Graph and Labels
    )r   r   planar_layoutr   s     r   draw_planarr   M  r   r    r)   ),collectionsr   numpyr   networkxr   	holoviews_hvbokeh.modelsr   r   r   r   holoviews.core.optionsr   holoviews.core.utilr
   holoviews.plotting.bokehr   r   holoviews.plotting.bokeh.stylesr   backend_transformsr   utilr   	utilitiesr   r   	extensiongetattrr\   r   r   r   r   r   r   r   r   r   r   r   r   r"   r    r   <module>r     s   # # # # # #             " " " " " " ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( ( 3 3 3 3 3 3 : : : : : : : : 3 3 3 3 3 3 : : : : : :       ! ! ! ! ! ! ! != '	5AA 'CM'&&&& (, ]5 ]5 ]5 ]5@l l l l^" " " ">" " "6" " ">@ @ @*5 5 5(9 9 9(/ / /(. . ..1 1 1(/ / /&/ / / / /r    