a
    `E                     @   s  d Z ddlmZmZmZ ddlmZ ddlmZm	Z	 ddl
mZ z ddlZddlmZmZmZ W n eyv   dZY n0 ddlZddlZddl
ZddlZdd	lmZ ed
d Zejdd Zejdd Zdd Ze	dd Zejdd Z dd Z!edd Z"dd Z#e	dd Z$dd Z%e	d d! Z&e	d"d# Z'G d$d% d%e(Z)G d&d' d'e)Z*G d(d) d)e)Z+G d*d+ d+e)Z,G d,d- d-e)Z-d.d/ Z.d0d1 Z/G d2d3 d3ej0Z1e1Z2d4d5 Z3d6d7 Z4G d8d9 d9e1Z5dS ):a  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
    )absolute_importdivisionprint_function)ceil)computedelayed)	DataFrameN)gaussiansobel_hsobel_v   )ngjitc                 C   s,   | d |d  d | d |d  d  d S )z/Find the Euclidean distance between two points.r      r   g      ? )abr   r   2lib/python3.9/site-packages/datashader/bundling.pydistance_between#   s    r   c                 C   s  t j|| jd}| d }d}d}|t| k r| | }t||}	|	|k rd|  k rdt| d k rn n&|| d }|||< |d7 }|d7 }q |	|krtt|	|| d  }
t|
D ]$}|||| |
   ||< |d7 }q|}|d7 }q |||< |d7 }|}|d7 }q |||< |S )N)dtyper   r   r   )npzerosr   lenr   intr   range)segmentsZnew_segmentsmin_segment_lengthmax_segment_lengthndims
next_pointcurrent_pointposindexdistancepointsir   r   r   resample_segment)   s2    
(



r%   c           
      C   s   | d }d}d}d}|t | k r| | }t||}||k r|d|  k rVt | d k r|n n"d}|| d }|d7 }|d7 }q||krd}tt||| d  }	||	7 }|}|d7 }q|d7 }|}|d7 }q|d7 }||fS )Nr   r   Fr   T)r   r   r   r   )
r   r   r   r   r!   totalZ
any_changer   r"   r#   r   r   r   calculate_lengthJ   s.    
(


r'   c                 C   s:   t | ||\}}|s| S t||f}t| |||| |S N)r'   r   emptyr%   )r   r   r   r   ZchangeZtotal_resamplesZ	resampledr   r   r   resample_edgeh   s    r*   c                 C   s&   g }| D ]}| t|||| q|S r(   )appendr*   )edge_segmentsr   r   r   Zreplaced_edgesr   r   r   r   resample_edgesq   s    r-   c           	      C   s   t | d }td|D ]}| |d  | | | |d    }}}d| ||  ||| ||   d  ||< d| ||  ||| ||   d  ||< qd S )Nr   r   )r   r   )	r   tensionidxidyZ
seg_lengthr$   Zpreviouscurrentr   r   r   r   smooth_segmenty   s
    $,r2   c                 C   s   | D ]}t |||| qd S r(   )r2   )r,   r.   r/   r0   r   r   r   r   smooth   s    r3   c           	      C   s   t dt| d D ]}t| | | | }t| | | | }| | | |||f |  | | |< | | | |||f |  | | |< tdt| | | d| | |< tdt| | | d| | |< qd S )Nr   r   )r   r   r   maxmin)	r   verthorizaccuracyr/   r0   r$   xyr   r   r   advect_segments   s    $$ r;   c           	      C   sD   t |D ]6}t|| |||j|j |d dkrt||||j}q|S )Nr   r   )r   r;   r/   r0   r*   r   )	r6   r7   r   
iterationsr8   r   r   segment_classitr   r   r   advect_and_resample   s
    r?   c                    s&   | \ fdd|D S )Nc                    s"   g | ]}t | qS r   )r?   ).0edgesr8   r7   r<   r   r   r=   r6   r   r   
<listcomp>   s   z'advect_resample_all.<locals>.<listcomp>r   )	gradientsr,   r<   r8   r   r   r=   r   rB   r   advect_resample_all   s    rE   c                 c   s,   t dt| |D ]}| |||  V  qdS )z(Yield successive n-sized batches from l.r   N)r   r   )lnr$   r   r   r   batches   s    rH   c                 C   sF   t |d |d f}| D ]}|D ]}|||| q"qt||d dS )Nr   r   )Zsigma)r   r   r	   )r,   	bandwidthr8   Zaccumulatorimgr   pointr   r   r   draw_to_surface   s
    rL   c                 C   sP   | t |  } t| }t| }t |d |d  d }|| }|| }||fS )Nr   gh㈵>)r   r4   r
   r   Zsqrt)rJ   r7   r6   Z	magnituder   r   r   get_gradients   s    rM   c                   @   s   e Zd Zedd ZdS )BaseSegmentc                 C   s   t d| jft jS )Nr   )r   Zfullr   nan)clsr   r   r   create_delimiter   s    zBaseSegment.create_delimiterN)__name__
__module____qualname__classmethodrQ   r   r   r   r   rN      s   rN   c                   @   sR   e Zd ZdZd\ZZedd Zedd Zee	j
dd Zeed	d
 ZdS )UnweightedSegment   r   r   c                 C   s   d| j | jgS Nedge_idr9   r:   paramsr   r   r   get_columns   s    zUnweightedSegment.get_columnsc                 C   s   g dS N)rZ   src_xsrc_ydst_xdst_yr   r\   r   r   r   get_merged_columns   s    z$UnweightedSegment.get_merged_columnsc                 C   s2   t | d | d | d g| d | d | d ggS )Nr   r   r   rW      r   Zarrayedger   r   r   create_segment   s    z UnweightedSegment.create_segmentc                 C   s0   | t |d | t |d | f  d7  < d S )Nr   r   r   rJ   rK   r8   r   r   r   
accumulate   s    zUnweightedSegment.accumulateNrR   rS   rT   r   r/   r0   staticmethodr^   rd   nbjitri   r   rl   r   r   r   r   rV      s   

rV   c                   @   sR   e Zd ZdZd\ZZedd Zedd Zee	j
dd Zeed	d
 ZdS )EdgelessUnweightedSegmentr   r   r   c                 C   s   | j | jgS r(   r[   r\   r   r   r   r^      s    z%EdgelessUnweightedSegment.get_columnsc                 C   s   g dS r_   r   r\   r   r   r   rd      s    z,EdgelessUnweightedSegment.get_merged_columnsc                 C   s&   t | d | d g| d | d ggS )Nr   r   r   rW   rf   rg   r   r   r   ri      s    z(EdgelessUnweightedSegment.create_segmentc                 C   s0   | t |d | t |d | f  d7  < d S )Nr   r   rj   rk   r   r   r   rl      s    z$EdgelessUnweightedSegment.accumulateNrm   r   r   r   r   rq      s   

rq   c                   @   sR   e Zd ZdZd\ZZedd Zedd Zee	j
dd Zeed	d
 ZdS )WeightedSegmentre   rX   c                 C   s   d| j | j| jgS rY   r9   r:   weightr\   r   r   r   r^      s    zWeightedSegment.get_columnsc                 C   s   ddddd| j gS )NrZ   r`   ra   rb   rc   ru   r\   r   r   r   rd      s    z"WeightedSegment.get_merged_columnsc                 C   s>   t | d | d | d | d g| d | d | d | d ggS )Nr   r   r      rW   re   rf   rg   r   r   r   ri      s    zWeightedSegment.create_segmentc                 C   s4   | t |d | t |d | f  |d 7  < d S )Nr   r   rW   rj   rk   r   r   r   rl     s    zWeightedSegment.accumulateNrm   r   r   r   r   rs      s   

rs   c                   @   sR   e Zd ZdZd\ZZedd Zedd Zee	j
dd Zeed	d
 ZdS )EdgelessWeightedSegmentrW   rr   c                 C   s   | j | j| jgS r(   rt   r\   r   r   r   r^     s    z#EdgelessWeightedSegment.get_columnsc                 C   s   dddd| j gS )Nr`   ra   rb   rc   rv   r\   r   r   r   rd     s    z*EdgelessWeightedSegment.get_merged_columnsc                 C   s2   t | d | d | d g| d | d | d ggS )Nr   r   re   r   rW   rf   rg   r   r   r   ri     s    z&EdgelessWeightedSegment.create_segmentc                 C   s4   | t |d | t |d | f  |d 7  < d S )Nr   r   r   rj   rk   r   r   r   rl     s    z"EdgelessWeightedSegment.accumulateNrm   r   r   r   r   rx     s   

rx   c                 C   s   t j|| |jgdd}|j|jd|jdid}t j|| |jgdd}|j|jd|jdid}| }| }|j	r|jdd	id}|j
o|j
|v }|j	r|rt}qt}n|rt}nt}|j||d
}g }|jD ]}||| q||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)Zleft_onZright_indexr`   ra   )columnsrb   rc   idrZ   )items)pdmergesourcerenamer9   r:   targetZ
sort_indexZreset_indexinclude_edge_idru   rs   rV   rx   rq   filterrd   valuesr+   ri   )nodesrA   r]   dfZinclude_weightr=   r,   rh   r   r   r   _convert_graph_to_edge_segments  s*    
r   c                    s2    fdd}t tt| }||_|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.
    c                  3   s    D ]} | V    V  qd S r(   )rQ   rg   r,   r=   r   r   edge_iteratorY  s    z:_convert_edge_segments_to_dataframe.<locals>.edge_iterator)r   r   Zconcatenatelistr^   ry   )r,   r=   r]   r   r   r   r   r   #_convert_edge_segments_to_dataframeO  s    
r   c                   @   sn   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Zdd ZdS )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.
    r9   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   Z
allow_Noner   Fz.
        Include edge IDs in bundled dataframec                 K   s(   t | |}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   rA   r]   pr=   r   r   r   __call__~  s    zconnect_edges.__call__)rR   rS   rT   __doc__r   Stringr9   r:   r~   r   ru   ZBooleanr   r   r   r   r   r   r   c  s   r   c                 C   s   | | ||  S r(   r   Xlowerupperr   r   r   minmax_normalize  s    r   c                 C   s   | ||  | S r(   r   r   r   r   r   minmax_denormalize  s    r   c                   @   s   e Zd Z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dZejdd
dddZejdddddZejdddddZejdddddZejddddZdd  Zd!S )"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.re   )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   Z
precedencer   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 segmentru   Tr   r   c                    s  t d u rtdt| |t|j t|j  }}t|j t|j  }}|	 }t
|j |||j< t
|j |||j< t||\}tt|j}fdd|D }	tjD ]j}
jj|
d   j   dk r qB fdd|	D }t|}t|fdd|	D }	qևfdd|	D }	t|	 }	td	D ]&}
|	D ]}t|jjj qnqfg }|	D ]}|| qt|}t|j |||j< t|j |||j< |S )
Nzjhammer_bundle operation requires scikit-image. Ensure you install the dependency before applying bundling.c                    s    g | ]}t | j jjqS r   r-   r   r   r   )r@   batchr   r=   r   r   rC         z*hammer_bundle.__call__.<locals>.<listcomp>r   r   c                    s   g | ]}t | jjqS r   )rL   r8   rl   r@   Zsegment)rI   r   r=   r   r   rC     r   c              
      s(   g | ] }t  |jjjjqS r   )rE   advect_iterationsr8   r   r   r   )rD   r   r=   r   r   rC     s   c                    s    g | ]}t | j jjqS r   r   r   r   r   r   rC     r   
   )skimageImportErrorr   r   r   r5   r9   r4   r:   copyr   r   r   rH   
batch_sizer   r<   initial_bandwidthdecayr8   sumrM   r   r3   r.   r/   r0   extendr   r   )r   r   rA   r]   ZxminZxmaxZyminZymaxZedge_batchesr,   r$   ZimagesZoverall_imager   Znew_segsr   r   )rI   rD   r   r=   r   r     sB    ""
zhammer_bundle.__call__N)rR   rS   rT   r   r   Numberr   r   ZIntegerr<   r   r.   r8   r   r   r   r   ru   r   r   r   r   r   r     s   r   )6r   Z
__future__r   r   r   Zmathr   Zdaskr   r   Zpandasr   r   Zskimage.filtersr	   r
   r   	ExceptionZnumbaro   Znumpyr   r|   r   Zutilsr   r   rp   r%   r'   r*   r-   r2   r3   r;   r?   rE   rH   rL   rM   objectrN   rV   rq   rs   rx   r   r   ZParameterizedFunctionr   Zdirectly_connect_edgesr   r   r   r   r   r   r   <module>   s`   


 
	






0+