U
    /e@                     @  s  d dl m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mZmZmZ dd Zdd	 Zd
d ZedZedZd-ddZd.ddZd/ddZeddgZeddgZdd Zd0ddZdd  Zd1d!d"Zd2dd#d#d$ddd%d&d&d'd(d(d(d)d)d*d+d,ZdS )3    )annotationsN)partial)get_dependencies
ishashableistask)applyfuncnameimport_required	key_splitc                 C  s   | d }|t kr| d }t|drTt|jdkrDt|jd  dS t|jd }nt|}tdd | dd D r| dS |S dS )zLabel for a task on a dot graph.

    Examples
    --------
    >>> from operator import add
    >>> task_label((add, 1, 2))
    'add'
    >>> task_label((add, (add, 1, 2), 3))
    'add(...)'
    r      funcsz(...)c                 s  s   | ]}t |V  qd S Nhas_sub_tasks.0i r   ,/tmp/pip-unpacked-wheel-dbjnr7gq/dask/dot.py	<genexpr>    s     ztask_label.<locals>.<genexpr>N)r   hasattrlenr   r   any)taskfuncheadr   r   r   
task_label   s    

r   c                 C  s0   t | rdS t| tr(tdd | D S dS dS )z&Returns True if the task has sub tasksTc                 s  s   | ]}t |V  qd S r   r   r   r   r   r   r   +   s     z has_sub_tasks.<locals>.<genexpr>FN)r   
isinstancelistr   )r   r   r   r   r   &   s
    
r   c                 C  s8   zt t| W S  tk
r2   t tt |  Y S X d S r   )strhash	TypeError)xr   r   r   name0   s    r#   z([0-9a-z]{32})z>([0-9a-z]{8}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{4}-[0-9a-z]{12})c                 C  sx   t | }ttfD ]b}t||}|dk	r| D ]@}|dk	r`||t|}d| }|||< nd}|||}q0q|S )a  

    >>> label('x')
    'x'

    >>> label(('x', 1))
    "('x', 1)"

    >>> from hashlib import md5
    >>> x = 'x-%s-hello' % md5(b'1234').hexdigest()
    >>> x
    'x-81dc9bdb52d04dc20036dbd8313ed055-hello'

    >>> label(x)
    'x-#-hello'

    >>> from uuid import uuid1
    >>> x = 'x-%s-hello' % uuid1()
    >>> x  # doctest: +SKIP
    'x-4c1a3d7e-0b45-11e6-8334-54ee75105593-hello'

    >>> label(x)
    'x-#-hello'
    N#)	r   _HASHPAT_UUIDPATresearchgroupsgetr   replace)r"   cachespatternmhnlabelr   r   r   r2   ;   s    

r2   Fc                 C  sD   t | tr0| dd } t| dkr(| \} t| S |r<t| S dS dS )zLabel boxes in graph by chunk index

    >>> box_label(('x', 1, 2, 3))
    '(1, 2, 3)'
    >>> box_label(('x', 123))
    '123'
    >>> box_label('x')
    ''
    r   N )r   tupler   r   )keyverboser   r   r   	box_labeld   s    

r7   BTc	                 K  s@  t dd}
|pi }|pi }|p i }|p(i }|p0i }||d< d|d< ||	 |
j|||d}t }t }|  D ]\}}t|}t|r|st|dfn|}|s||kr|| ||i 	 }|
dt| |
d	d
 |j|f| |s||| || || t| |D ]~}t|}||kr||| ||i 	 }|
dt|| |
d	d |j|f| ||| || || q n<t|r|| krt|}||| || || |r||krp||krp|| ||i 	 }|
dt|| |
d	d |j|f| qp|S )Ngraphviza<  Drawing dask graphs with the graphviz engine requires the `graphviz` python library and the `graphviz` system library.

Please either conda or pip install as follows:

  conda install python-graphviz     # either conda install
  python -m pip install graphviz    # or pip install and follow installation instructionsrankdir	helveticaZfontname)
graph_attr	node_attr	edge_attrfunctionr2   shapeZcircleZbox)r	   updateZDigraphsetitemsr#   r   addr*   copy
setdefaultr
   nodeedger   r7   r   )dskdata_attributesfunction_attributesr:   r<   r=   r>   collapse_outputsr6   kwargsr9   gseen	connectedkvk_name	func_nameattrsdepdep_namev_namer   r   r   to_graphvizy   sp    	
  









rY   ZjpegpngdotZpdfc                 C  sr   dd }zddl m} W n tk
r0   | Y S X | tkr>|S | tkrTt|j| dS | dkrb|jS td|  dS )a  
    Get the appropriate IPython display class for `format`.

    Returns `IPython.display.SVG` if format=='svg', otherwise
    `IPython.display.Image`.

    If IPython is not importable, return dummy function that swallows its
    arguments and returns None.
    c                  _  s   d S r   r   )argsrM   r   r   r   <lambda>       z"_get_display_cls.<locals>.<lambda>r   Nformatsvgz)Unknown format '%s' passed to `dot_graph`)	ZIPython.displaydisplayImportErrorIPYTHON_NO_DISPLAY_FORMATSIPYTHON_IMAGE_FORMATSr   ZImageZSVG
ValueError)r`   dummyrb   r   r   r   _get_display_cls   s    

rh   mydaskc                 K  s   t | f|}t|||S )a$  
    Render a task graph using dot.

    If `filename` is not None, write a file to disk with the specified name and extension.
    If no extension is specified, '.png' will be used by default.

    Parameters
    ----------
    dsk : dict
        The graph to display.
    filename : str or None, optional
        The name of the file to write to disk. If the provided `filename`
        doesn't include an extension, '.png' will be used by default.
        If `filename` is None, no file will be written, and we communicate
        with dot using only pipes.  Default is 'mydask'.
    format : {'png', 'pdf', 'dot', 'svg', 'jpeg', 'jpg'}, optional
        Format in which to write output file.  Default is 'png'.
    **kwargs
        Additional keyword arguments to forward to `to_graphviz`.

    Returns
    -------
    result : None or IPython.display.Image or IPython.display.SVG  (See below.)

    Notes
    -----
    If IPython is installed, we return an IPython.display object in the
    requested format.  If IPython is not installed, we just return None.

    We always return None if format is 'pdf' or 'dot', because IPython can't
    display these formats natively. Passing these formats with filename=None
    will not produce any useful output.

    See Also
    --------
    dask.dot.to_graphviz
    )rY   graphviz_to_file)rI   filenamer`   rM   rN   r   r   r   	dot_graph   s    &rl   c              	     s   ddddddg}|d krV d k	rVt  fdd|D rVtj \ }|d	d   }|d krbd
}| j|d}|sztdt|} d kr||dS d |g}t	|d}|
| W 5 Q R X ||dS )Nz.pngz.pdfz.dotz.svgz.jpegz.jpgc                 3  s   | ]}   |V  qd S r   )lowerendswith)r   fmtrk   r   r   r     s     z#graphviz_to_file.<locals>.<genexpr>r   rZ   r_   zGraphviz failed to properly produce an image. This probably means your installation of graphviz is missing png support. See: https://github.com/ContinuumIO/anaconda-issues/issues/485 for more information.)data.wbrp   )r   ospathsplitextrm   pipeRuntimeErrorrh   joinopenwrite)rN   rk   r`   Zfmtsrq   Zdisplay_clsZfull_filenamefr   rp   r   rj     s.    
rj   c              
   K  s  g }g }||d}|pi }|p i }t  }	t  }
|  D ]\}}t|}t|r`|sbt|dfn|}|sr||	kr|	| ||i  }|d|t|ddd|i |s|d||di |
| |
| t	| |D ]z}t|}||	kr4|	| ||i  }|d|t
||ddd|i |d||di |
| |
| qnDt|r|| krt|}|d||di |
| |
| |r||
kr6||	kr6|	| ||i  }|d|t
||ddd|i q6|S )	zf
    Convert a dask graph to Cytoscape JSON:
    https://js.cytoscape.org/#notation/elements-json
    )nodesedgesr?   rq   Zellipsegray)idr2   r@   color)sourcetargetZ	rectangle)rB   rC   r#   r   rD   r*   rE   appendr
   r   r7   r   )rI   rJ   rK   rL   r6   rM   r}   r~   rq   rO   rP   rQ   rR   rS   rT   rU   rV   rW   rX   r   r   r   _to_cytoscape_json9  s    










r   
   r   )r:   node_sepedge_sepspacing_factor
node_style
edge_stylez
str | Noner   floatzdict[str, str] | None)rk   r`   r:   r   r   r   r   r   c                K  s  t dd}
|pi }|pi }t| f|	}|
jddid}|jd||||dd |jj|dd	 |d
ddddddddddddddd|dddddddd|dg |j}|d |_|d  |_	d!|_
|d"k	rd#d$lm} |d%r|n|d% }|||gd&d' |S )(a  
    Create an ipycytoscape widget for a dask graph.

    If `filename` is not None, write an HTML file to disk with the specified name.

    This uses the Cytoscape dagre layout algorithm. Options for that are documented here:
    https://github.com/cytoscape/cytoscape.js-dagre#api

    Parameters
    ----------
    dsk : dict
        The graph to display.
    filename : str or None, optional
        The name of the HTML file to write to disk.
    format : str, optional
        Not used in this engine.
    rankdir: str
        The direction in which to orient the visualization.
    node_sep: float
        The separation (in px) between nodes in the DAG layout.
    edge_sep: float
        The separation (in px) between edges in the DAG layout.
    spacing_factor: float
        An overall scaling factor to increase (>1) or decrease (<1) the spacing
        of the layout.
    node_style: dict[str, str], optional
        A dictionary of style attributes for nodes (refer to Cytoscape JSON docs
        for available options: https://js.cytoscape.org/#notation/elements-json)
    edge_style: dict[str, str], optional
        A dictionary of style attributes for edges (refer to Cytoscape JSON docs
        for available options: https://js.cytoscape.org/#notation/elements-json)
    **kwargs
        Additional keyword arguments to forward to `_to_cytoscape_json`.

    Returns
    -------
    result : ipycytoscape.CytoscapeWidget
    ipycytoscapea  Drawing dask graphs with the cytoscape engine requires the `ipycytoscape` python library.

Please either conda or pip install as follows:

  conda install ipycytoscape            # either conda install
  python -m pip install ipycytoscape    # or pip installheightZ400px)ZlayoutZdagreT)r#   ZrankDirZnodeSepZedgeSepZspacingFactorZnodeDimensionsIncludeLabels)ZdirectedrG   r;   Z24pxZboldZblackz#eeezdata(color)   z1.0centerzdata(label)zdata(shape)@   )zfont-familyz	font-sizezfont-weightr   zbackground-colorzborder-colorzborder-widthZopacityztext-valignztext-halignr2   r@   widthr   )selectorstylerH      r   ZtriangleZbezier)r   z
line-colorztarget-arrow-shapeztarget-arrow-colorzcurve-styleg       @g      $@g?Nr   )embed_minimal_htmlz.htmlzDask task graph)Zviewstitle)r	   r   ZCytoscapeWidgetZ
set_layoutgraphZadd_graph_from_jsonZ	set_styleZzoomZmax_zoomZmin_zoomZwheel_sensitivityZipywidgets.embedr   rn   )rI   rk   r`   r:   r   r   r   r   r   rM   r   rq   rN   zr   r   r   r   cytoscape_graph  s~    3	$


r   )N)F)NNr8   NNNFF)ri   N)NNFF)ri   N) 
__future__r   rt   r'   	functoolsr   Z	dask.corer   r   r   Z
dask.utilsr   r   r	   r
   r   r   r#   compiler%   r&   r2   r7   rY   	frozensetre   rd   rh   rl   rj   r   r   r   r   r   r   <module>   sR   



)
        
P
*&    
i  