
    UgT                    
   d Z ddlmZ ddlmZ ddlmZ ddlmZ 	 ddl	Z	ddl	m
Z
mZ 	 ddlZdd
lmZmZmZ ddlZddlZddlZddlZddlZddlmZ  edg d      Zej:                  j=                  ej>                  de      Z  ejB                   ejD                  ejD                  ddd   ejD                  ddd         dddejD                  ejD                  d      d        Z# ejB                   ejD                  dddddf   ejD                  dddddf   ejD                  dddddf   ejH                  ddd   ejJ                        dddejD                  ddd   ejD                  ddd   ejD                  ddd   ejH                  ejL                  ejL                  ejD                  d      d        Z' ejB                   ej:                  jQ                  ejR                  ejL                  ejH                  ddd   f      ejD                  dddddf   e       dddejD                  ddd   ejD                  ddd   ejL                  ejL                  ejD                  d      d        Z* ejB                   ejD                  dddddf   ejD                  dddddf   e ejJ                        dd      d        Z+d Z, ejB                   ejZ                  ejD                  dddddf   ejD                  ejJ                  ejJ                        dddejH                  ejD                  dddddf   ejD                  ddd   ejD                  ddd   ejD                  ddd   d      d        Z.d Z/ ejB                   ejD                  dddddf   ejD                  dddddf   ejD                  dddddf   ejD                  dddddf   ejJ                  ej>                  e ejL                  ejL                  ejJ                  	      dddej`                  ejH                  ejH                  ejH                  d      d        Z1d  Z2d! Z3d" Z4 ejB                   ejZ                  ejD                  dddddf   ejD                  dddddf         ddd#      d$        Z5d% Z6 G d& d'      Z7 G d( d)e7      Z8 G d* d+e7      Z9 G d, d-e7      Z: G d. d/e7      Z;d0 Z<d1 Z= G d2 d3ej|                        Z?e?Z@d4 ZAd5 ZB G d6 d7e?      ZCy# e$ r d\  Z	Z
d	 ZY w xY w# e$ r dZY w xY w)8a  Bundle a graph's edges to emphasize the graph structure.

Given a large graph, the underlying structure can be obscured by edges in close
proximity. To uncover the group structure for clearer visualization, edges are
split into smaller edges and bundled with neighbors.

Ian Calvert's `Edgehammer`_ is the original implementation of the main
algorithm.

.. _Edgehammer:
   https://gitlab.com/ianjcalvert/edgehammer
    )annotations)ceil)	DataFrame)
namedtupleN)computedelayed)NNc                     d }|S )Nc                     t        d      )Nz)dask is required to use delayed functions)ImportError)argskwargss     3lib/python3.12/site-packages/datashader/bundling.pyfunczdelayed.<locals>.func   s    IJJ     )r   r   r   s      r   r   r      s    	Kr   )gaussiansobel_hsobel_v   )ngjitSegmentLength)minmaxmean   T)resultdiff)nopythonnogilfastmathlocalsc                L    | d   |d   z
  }||z  }| d   |d   z
  }|||z  z  }|S )z/Find the Euclidean distance between two points.r   r   r   )abr   r   s       r   distance_betweenr%   0   sB     Q4!A$;DD[FQ4!A$;D
dTkFMr   )
next_pointcurrent_pointstep_vectoriposindexdistancec                   t        j                  || j                        }| d   }d}d}|t        |       k  r| |   }||   dk(  r2d|cxk  rt        |       dz
  k  rn n||z   dz  }|||<   |dz  }|dz  }nN||   dkD  r5||   }||z
  |z  }	t	        |      D ]  }
||
|	z  z   ||<   |dz  } |}|dz  }n|||<   |dz  }|}|dz  }|t        |       k  r|||<   |S )Ndtyper   r      )npzerosr/   lenrange)segmentsnew_segmentsn_points_to_addndimsr&   r'   r*   r+   pointsr(   r)   s              r   resample_segmentr:   ?   s0     %x~~6JQKM
CE
#h-
e_
E"a'A,KX9J,K*Z71<M -L1HCQJEU#a'$U+F%5?K6]$1Q_$ES!q # 'MQJE !.L1HC&MQJE- #h-
. #Lr   )r&   r'   r*   r+   r,   c                N   | d   }d}d}d}t        j                  t        |       t         j                        }|t        |       k  r| |   }t	        ||      }||j
                  k  r4d|cxk  rt        |       dz
  k  rn nd}||z   dz  }d||<   |dz  }|dz  }nr||j                  kD  rRd}t        j                  t        t        j                  ||j                  z                    }	|	||<   ||	z  }|}|dz  }nd||<   |dz  }|}|dz  }|t        |       k  r|dz  }|||fS )Nr   r   Fr.   r0   T)
r1   r2   r3   uint16r%   r   r   r   sqrtr   )
r5   squared_segment_lengthr'   r+   total
any_changer7   r&   r,   r9   s
             r   calculate_resamplingrA   m   sP    QKMEEJhhs8}BII>O
#h-
e_
#M:>-111a%6U3x=STCT6UJ*Z71<M%&OE"QJEQJE.222JYYtBGGH7M7R7R,R$STUF%+OE"VOE&MQJE &'OE"QJE&MQJE/ #h-
0 
QJEuo--r   )r   r   c                    t        | |      \  }}}|s| S t        j                  ||ft        j                        }t	        | |||       |S )Nr.   )rA   r1   emptyfloat32r:   )r5   r>   r8   changetotal_resamplesr7   	resampleds          r   resample_edgerH      sQ     0DHDZ0\,FO_/51DIXy/5Ar   c                B    | D cg c]  }t        |||       c}S c c}w N)rH   )edge_segmentsr>   r8   r5   s       r   resample_edgesrL      s1    )+) ($:EB)+ + +s   )r)   r5   previouscurrentr&   c                   t        d      D ]v  }t        |       dz
  }t        d|      D ]W  }| |dz
     | |   | |dz      }	}}d|z
  ||   z  |||   |	|   z   z  dz  z   ||<   d|z
  ||   z  |||   |	|   z   z  dz  z   ||<   Y x y )N
   r0   r   r4   r3   )
r5   tensionidxidy_
seg_lengthr)   rM   rN   r&   s
             r   smooth_segmentrW      s     2Y]Q&
q*%A,4QUOXa[(STWXSX/zgHi5$hsmjo&EFJLGCLi5$hsmjo&EFJLGCL	 & r   c                .    | D ]  }t        ||||        y rJ   )rW   )rK   rR   rS   rT   r5   s        r   smoothrY      s    !x#s3 "r   )itr)   xyc	           
        t        |      D ]  }	t        dt        |      dz
        D ]  }
t        j                  ||
|f   |z        }t        j                  ||
|f   |z        }||
|fxx   |||f   |z  z  cc<   ||
|fxx   | ||f   |z  z  cc<   t	        dt        ||
|f   d            ||
|f<   t	        dt        ||
|f   d            ||
|f<    |	dz  dk(  st        |||      } |S )Nr   r   r0   )r4   r3   r1   r<   r   r   rH   )verthorizr5   
iterationsaccuracyr>   rS   rT   r8   rZ   r)   r[   r\   s                r   advect_and_resamplerb      s    Jq#h-!+,A		(1c6*X56A		(1c6*X56AQVadh 66QVQT
X 55"1c(1c6*:A&>?HQV"1c(1c6*:A&>?HQV - 6Q;$X/EuMH   Or   c                X    | \  }}	|D 
cg c]  }
t        ||	|
||||||	       c}
S c c}
w rJ   )rb   )	gradientsrK   r`   ra   r>   rS   rT   r8   r^   r_   edgess              r   advect_resample_allrf      sK    KD% '(&  eUJJ` #S%1&( ( (s   'c              #  V   K   t        dt        |       |      D ]  }| |||z      yw)z*Yield successive n-sized batches from seq.r   NrQ   )seqnr)   s      r   batchesrj      s-     1c#h"!AEl #s   ')c                    t        j                  |dz   |dz   ft         j                        }| D ]  } ||||        t        ||dz        S )Nr   r.   r0   )sigma)r1   r2   rD   r   )rK   	bandwidthra   accumulatorimgr5   s         r   draw_to_surfacerp      sJ    
((HqL(Q,/rzz
BC!C8, "Cy1}--r   )r   r   r    c                
   t        | j                  d         D ]h  }t        | j                  d         D ]K  }t        j                  |||f   dz  | ||f   dz  z         dz   }| ||fxx   |z  cc<   |||fxx   |z  cc<   M j y )Nr   r   r0   gh㈵>)r4   shaper1   r=   )r^   r_   r)   j	magnitudes        r   normalize_gradientsru      s     4::a=!tzz!}%AadQadQ >?$FIAJ)#J!Q$K9$K & "r   c                ~    | t        j                  |       z  } t        |       }t        |       }t	        ||       ||fS rJ   )r1   r   r   r   ru   )ro   r_   r^   s      r   get_gradientsrw     s:    266#;CCLE3<De$%=r   c                      e Zd Zed        Zy)BaseSegmentc                b    t        j                  d| j                  ft         j                        S )Nr   )r1   fullr8   nan)clss    r   create_delimiterzBaseSegment.create_delimiter  s    ww399~rvv..r   N)__name__
__module____qualname__classmethodr~   r   r   r   ry   ry     s    / /r   ry   c                  n    e Zd ZdZd\  ZZed        Zed        Zee	d               Z
ee	d               Zy)UnweightedSegmentr   r   r0   c                4    d| j                   | j                  gS Nedge_idr[   r\   paramss    r   get_columnszUnweightedSegment.get_columns  s    688VXX..r   c                
    g dS N)r   src_xsrc_ydst_xdst_yr   r   s    r   get_merged_columnsz$UnweightedSegment.get_merged_columns      >>r   c                    t        j                  | d   | d   | d   g| d   | d   | d   ggt         j                        S )Nr   r   r0   r      r.   r1   arrayrD   edges    r   create_segmentz UnweightedSegment.create_segment  I     xx$q'47DG4tAwQa6QR jj* 	*r   c                l    |D ]/  }| t        |d   |z        t        |d   |z        fxx   dz  cc<   1 y )Nr   r0   intro   r9   ra   points       r   
accumulatezUnweightedSegment.accumulate#  ?     EE!Hx'(#eAh.A*BBCqHC r   Nr   r   r   r8   rS   rT   staticmethodr   r   r   r   r   r   r   r   r   r     sp    EHC/ / ? ? 
*  * 
I  Ir   r   c                  n    e Zd ZdZd\  ZZed        Zed        Zee	d               Z
ee	d               Zy)EdgelessUnweightedSegmentr0   r   r   c                2    | j                   | j                  gS rJ   r   r   s    r   r   z%EdgelessUnweightedSegment.get_columns.  s    &((##r   c                
    g dS r   r   r   s    r   r   z,EdgelessUnweightedSegment.get_merged_columns2  r   r   c                p    t        j                  | d   | d   g| d   | d   ggt         j                        S )Nr   r   r0   r   r.   r   r   s    r   r   z(EdgelessUnweightedSegment.create_segment6  s8     xx$q'47+d1gtAw-?@

SSr   c                l    |D ]/  }| t        |d   |z        t        |d   |z        fxx   dz  cc<   1 y )Nr   r   r   r   s       r   r   z$EdgelessUnweightedSegment.accumulate;  r   r   Nr   r   r   r   r   r   *  sr    EHC$ $ ? ? 
T  T 
I  Ir   r   c                  n    e Zd ZdZd\  ZZed        Zed        Zee	d               Z
ee	d               Zy)WeightedSegmentr   r   c                J    d| j                   | j                  | j                  gS r   r[   r\   weightr   s    r   r   zWeightedSegment.get_columnsF  s    688VXXv}}==r   c                &    ddddd| j                   gS )Nr   r   r   r   r   r   r   s    r   r   z"WeightedSegment.get_merged_columnsJ  s    7GWgv}}MMr   c                    t        j                  | d   | d   | d   | d   g| d   | d   | d   | d   ggt         j                        S )Nr   r   r0      r   r   r.   r   r   s    r   r   zWeightedSegment.create_segmentN  sZ     xx$q'47DGT!W=q'47DGT!W=?FHjjR 	Rr   c                r    |D ]2  }| t        |d   |z        t        |d   |z        fxx   |d   z  cc<   4 y )Nr   r0   r   r   r   s       r   r   zWeightedSegment.accumulateT  C     EE!Hx'(#eAh.A*BBCuQxOC r   Nr   r   r   r   r   r   B  st    EHC> > N N 
R  R 
P  Pr   r   c                  n    e Zd ZdZd\  ZZed        Zed        Zee	d               Z
ee	d               Zy)EdgelessWeightedSegmentr   r   c                H    | j                   | j                  | j                  gS rJ   r   r   s    r   r   z#EdgelessWeightedSegment.get_columns_  s    &((FMM22r   c                $    dddd| j                   gS )Nr   r   r   r   r   r   s    r   r   z*EdgelessWeightedSegment.get_merged_columnsc  s    '7FMMBBr   c                    t        j                  | d   | d   | d   g| d   | d   | d   ggt         j                        S )Nr   r   r   r0   r   r.   r   r   s    r   r   z&EdgelessWeightedSegment.create_segmentg  r   r   c                r    |D ]2  }| t        |d   |z        t        |d   |z        fxx   |d   z  cc<   4 y )Nr   r   r0   r   r   s       r   r   z"EdgelessWeightedSegment.accumulatem  r   r   Nr   r   r   r   r   r   [  sr    EHC3 3 C C 
*  * 
P  Pr   r   c                   t        j                  || |j                  gd      }|j                  |j                  d|j
                  di      }t        j                  || |j                  gd      }|j                  |j                  d|j
                  di      }|j                         }|j                         }|j                  }|r|j                  dd	i      }|j                  xr |j                  |v }|r|rt        }nt        }n|rt        }nt        }|j                  |j!                  |      
      }g }|j#                         D ]~  }|j$                  |j&                  |j(                  |j*                  f}	|r|j,                  f|	z   }	|r|	t/        ||j                        fz  }	|j1                  |j3                  |	              ||fS )aB  
    Merge graph dataframes into a list of edge segments.

    Given a graph defined as a pair of dataframes (nodes and edges), the
    nodes (id, coordinates) and edges (id, source, target, weight) are
    joined by node id to create a single dataframe with each source/target
    of an edge (including its optional weight) replaced with the respective
    coordinates. For both nodes and edges, each id column is assumed to be
    the index.

    We also return the dimensions of each point in the final dataframe and
    the accumulator function for drawing to an image.
    T)left_onright_indexr   r   )columnsr   r   idr   )items)pdmergesourcerenamer[   r\   target
sort_indexreset_indexinclude_edge_idr   r   r   r   r   filterr   
itertuplesr   r   r   r   r   getattrappendr   )
nodesre   r   dfr   include_weightsegment_classrK   tupr   s
             r   _convert_graph_to_edge_segmentsr   t  s    
%T	JB	FHHgvxxA	BB	"efmm_$	GB	FHHgvxxA	BB	B		B,,OYYi0Y1]]=v}}'=N+M-M3M5M	99&A	BBM}}		399cii;KK>D(DWS&--022D]99$?@  -''r   c                ,   t        j                  t        |       d|j                  ft         j                        }t        t        j                  t        | |             }t        t        j                  |            }|j                  |      |_        |S )z
    Convert list of edge segments into a dataframe.

    For all edge segments, we create a dataframe to represent a path
    as successive points separated by a point with NaN as the x or y
    value.
    r   )r1   r{   r3   r8   r|   list	itertoolschainzipr   concatenater   r   )rK   r   r   
delimiterscombinedr   s         r   #_convert_edge_segments_to_dataframer     sn     #m,a1D1DErvvNJIOOS
%CDEH	2>>(+	,B**62BJIr   c                     e Zd Z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d      Z
 ej                  dd      Zd Zy)connect_edgesz
    Convert a graph into paths suitable for datashading.

    Base class that connects each edge using a single line segment.
    Subclasses can add more complex algorithms for connecting with
    curved or manhattan-style polylines.
    r[   z2
        Column name for each node's x coordinate.defaultdocr\   z2
        Column name for each node's y coordinate.r   z,
        Column name for each edge's source.r   z,
        Column name for each edge's target.NTH
        Column name for each edge weight. If None, weights are ignored.r   
allow_Noner   Fz.
        Include edge IDs in bundled dataframec                h    t        j                  | |      }t        |||      \  }}t        |||      S )a(  
        Convert a graph data structure into a path structure for plotting

        Given a set of nodes (as a dataframe with a unique ID for each
        node) and a set of edges (as a dataframe with with columns for the
        source and destination IDs for each edge), returns a dataframe
        with with one path for each edge suitable for use with
        Datashader. The returned dataframe has columns for x and y
        location, with paths represented as successive points separated by
        a point with NaN as the x or y value.
        )paramParamOverridesr   r   )selfr   re   r   pr   s         r   __call__zconnect_edges.__call__  s8       v.>ueQO}25-KKr   )r   r   r   __doc__r   Stringr[   r\   r   r   r   Booleanr   r   r   r   r   r   r     s     	S '5 	6A 	S '5 	6A U\\( 1/ 0F U\\( 1/ 0F U\\$4 >K LF $emmE 81 2OLr   r   c                    | |z
  ||z
  z  S rJ   r   Xloweruppers      r   minmax_normalizer     s    I%%-((r   c                    | ||z
  z  |z   S rJ   r   r   s      r   minmax_denormalizer     s    &&r   c                     e Zd ZdZ ej
                  ddd      Z ej
                  ddd      Z ej                  d	d
d      Z	 ej                  dd
d      Z
 ej
                  dddd      Z ej                  dddd      Z ej                  dddd      Z ej
                  dddd      Z ej
                  dddd      Z ej                   ddd      Z ej$                  d d!"      Zd# Zy$)%hammer_bundlez
    Iteratively group edges and return as paths suitable for datashading.

    Breaks each edge into a path with multiple line segments, and
    iteratively curves this path to bundle edges into groups.
    g?)        Nz+
        Initial value of the bandwidth....)r   boundsr   gffffff?)r   g      ?zL
        Rate of decay in the bandwidth value, with 1.0 indicating no decay.r   )r   Nz5
        Number of passes for the smoothing algorithmi N  z,
        Number of edges to process togetherg333333?)r   Ng      z;
        Exponential smoothing factor to use when smoothing)r   r   
precedencer   i  )r   i  z*
        Number of entries in table for...2   z;
        Number of iterations to move edges along gradientsgMb?z<
        Minimum length (in data space?) for an edge segmentgMb?z<
        Maximum length (in data space?) for an edge segmentr   Tr   r   Fz<
        Whether to use dask to parallelize the computation.r   c                   t         t        t        d      t        j                  | |      }|j
                  r=t        t              }t        t              }t        t              }t        t              }nt        }t        }t        }t        }t        j                  ||j                           t        j                  ||j                           }
}	t        j                  ||j                           t        j                  ||j                           }}|j!                         }t#        ||j                     |	|
      ||j                  <   t#        ||j                     ||      ||j                  <   t%        |||      \  }}t'        t)        ||j*                              }t-        |j.                  dz  |j0                  dz  |j.                  |j0                  z   dz  dz        }|D cg c]  } ||||j2                         }}t5        |j6                        D ]  }|j8                  |j:                  |dz   z  z  |j<                  z  }|dk  r n|D cg c]!  } ||||j<                  |j>                        # }}tA        |      } ||      }|D cg c]C  } ||||jB                  |j<                  ||jD                  |jF                  |j2                        E }} |D cg c]  } ||||j2                         }}|j
                  rtI        |      d   }g }|D ]  }|jK                  |        tM        ||jN                  |jD                  |jF                         tQ        |||      }tS        ||j                     |	|
      ||j                  <   tS        ||j                     ||      ||j                  <   |S c c}w c c}w c c}w c c}w )Nzshammer_bundle operation requires dask and scikit-image. Ensure you install the dependency before applying bundling.r0   r   r   )*daskskimager   r   r   use_daskr   rL   rp   rw   rf   r1   r   r[   r   r\   copyr   r   r   rj   
batch_sizer   min_segment_lengthmax_segment_lengthr8   r4   r`   initial_bandwidthdecayra   r   sumadvect_iterationsrS   rT   r   extendrY   rR   r   r   )r   r   re   r   r   resample_edges_fndraw_to_surface_fnget_gradients_fnadvect_resample_all_fnxminxmaxyminymaxr   edge_batchesr>   batchrK   r)   rm   segmentimagesoverall_imagerd   new_segsr   s                             r   r   zhammer_bundle.__call__  s   <7? * + +   v.:: ' 7!(!9&}5%,-@%A" .!0,%8" VVE!##J'acc
);dVVE!##J'acc
);d 

%eACCj$=acc
%eACCj$=acc
  ?ueQO} GE1<<89!.  !#Q%9%91%<""Q%9%99Q>B"
 KWXJV +52H(5(;(;=JV 	 X q||$A++aggA.>>KI 1} &34%2' ))QZZIaIab%2  4KM(7I -:	; -:	 4IwH[H[12=S1>1B1BMDUDU1>1D1DF -:	  ;# %2 MZ[LY +74J(5(;(;=LY 	 [ ::#M215M "EOOE" # 	xM$5$5}7H7HI 1=!L %RWdD9133$RWdD9133	aX4;[s   ,O&OAO'ON)r   r   r   r   r   Numberr  r  Integerr`   r  rR   ra   r	  r  r  r   r   r   r  r   r   r   r   r   r     sQ    %T I. / ELLI ;O PE q >8 9J uH B/ 0J ell3h$ L> ?G u}}S	T O- .H &bD V> ? &e8t Y? @ &e8t Y? @ U\\(t BK LF u}}U 1? @HYr   r   )Dr   
__future__r   mathr   pandasr   collectionsr   r   r   r   r   r   skimage.filtersr   r   r   	Exceptionnumpyr1   r   r   numbanbr   utilsr   r   typesNamedUniTuplefloat64segment_length_typejitrD   r%   r<   int64uint64r:   TuplebooleanrA   rH   rL   voidrW   rY   uint8rb   rf   rj   rp   ru   rw   ry   r   r   r   r   r   r   ParameterizedFunctionr   directly_connect_edgesr   r   r   r   r   r   <module>r2     s-   #   "%::      O-CDhh,,RZZMJ  BJJrzz#A#

3Q30
jj"**5 BJJq1ubjj3Q3'AccE):BIIccNBHHU
jj1oCaCzz#A#YYyyJJ> ;BHHNNBJJ		299SqS>:;BJJq1u<MObc
jj1oCaCyyJJ..B BJJq#A#vrzz!SqS&)+>I


+
 BGGBJJq1urzz288RXX>
YYJJq1u%JJssO::cc?jj1oMM4 BJJq1ubjj3Q3'AccE):BJJq1u<MrxxY[YcYc)299biiK
((K(
. BGGBJJq1urzz!CaC%01
	%%/ /I I2I I0Pk P2Pk P24(n")LE// )LV ' )'BM Bu  MD'  Gs"   T1 U 1UUUU