B
    T\79                 @   s   d dl mZmZmZ d dlZd dlmZ d dlmZ d dl	m
Z
 d dlmZmZ ddlmZmZ dd	lmZ dd
lmZ dZdZdd Zd"ddZdd Zd#ddZdd Zd$ddZd%ddZdd Zd&d d!ZdS )'    )absolute_importdivisionprint_functionN)bisect_left)LooseVersion)cycle)
itemgetteradd   )funcnameimport_required)istask)applyz1Diagnostics plots require `bokeh` to be installedz1Diagnostics plots require `toolz` to be installedc             C   sr   t | rn| d tttfkr0| d tt| d S | d tkrnt| d trnt| d d trnttt| d S | S )Nr      )r   tuplelistsetmapunquotedict
isinstance)expr r   Alib/python3.7/site-packages/dask/diagnostics/profile_visualize.pyr      s    r   <   c       	         s6  t | rv| d }|tkrdt| d }d}t| dkrBt| d nd}t| dkr^t| d ni }nPt|drdd	d
 |jD }dt|j }nt| d }d}| dd }i }|s|rt|t| t| t|t|   fdd|r"dkrdfdd
|D }nd}nd}|rbdkr\ddfdd
t	|
 D  }nd}nd}d||||S t| tr| sdS t| dkrt| dd  |}|dd d S t|d dt|   t|  d fdd
| D }d|S n.y|  krdS dS W n tk
r0   dS X dS )a?  Return a nicely formatted string for a task.

    Parameters
    ----------
    task:
        Value within dask graph to render as text
    keys: iterable
        List of keys within dask graph
    label_size: int (optional)
        Maximum size of output label, defaults to 60

    Examples
    --------
    >>> from operator import add, mul
    >>> dsk = {'a': 1,
    ...        'b': 2,
    ...        'c': (add, 'a', 'b'),
    ...        'd': (add, (mul, 'a', 'b'), 'c'),
    ...        'e': (sum, ['a', 'b', 5]),
    ...        'f': (add,),
    ...        'g': []}

    >>> pprint_task(dsk['c'], dsk)
    'add(_, _)'
    >>> pprint_task(dsk['d'], dsk)
    'add(mul(_, _), _)'
    >>> pprint_task(dsk['e'], dsk)
    'sum([_, _, *])'
    >>> pprint_task(dsk['f'], dsk)
    'add()'
    >>> pprint_task(dsk['g'], dsk)
    '[]'
    r   r   )r
   r      funcs(c             s   s   | ]}t |V  qd S )N)r   ).0fr   r   r   	<genexpr>H   s    zpprint_task.<locals>.<genexpr>Nc                s   t |  S )N)pprint_task)t)keyslabel_size2r   r   <lambda>R   s    zpprint_task.<locals>.<lambda>   z, c             3   s   | ]} |V  qd S )Nr   )r   r#   )pprintr   r   r!   U   s    z... c             3   s"   | ]\}}d  | |V  qdS )z{0}={1}N)format)r   kv)r(   r   r   r!   \   s   z, ...z{0}({1}{2}{3}z[]z, ...]c             3   s   | ]}t | V  qd S )N)r"   )r   r#   )r$   r%   r   r   r!   k   s    z[{0}]_*)r   r   r   lenr   hasattrjoinr   intsorteditemsr*   r   r   r"   	TypeError)	Ztaskr$   
label_sizefuncheadtailargskwargsresultr   )r$   r%   r(   r   r"      sZ    "



 
r"   c       	         s   t dt}t dt}tt||}t|}|j|  }tt| }|t	t
||t|d  }|| } t|| } t| |krtd|  tt|t|   fdd|D S )a  Get a dict mapping funcs to colors from palette.

    Parameters
    ----------
    palette : string
        Name of the bokeh palette to use, must be a member of
        bokeh.palettes.all_palettes.
    funcs : iterable
        Iterable of function names
    zbokeh.palettestoolzr   *   c                s   g | ]} | qS r   r   )r   n)color_lookupr   r   
<listcomp>   s    zget_colors.<locals>.<listcomp>)r   _BOKEH_MISSING_MSG_TOOLZ_MISSING_MSGr   r4   uniquer0   all_palettesr$   minr   randomZRandomZshuffler   zipr   )	paletter   palettestzZunique_funcsZn_funcsZpalette_lookupr$   indexr   )rA   r   
get_colorsw   s    


rN   Tc                sd  t dt}ddl}t|jdkr8ddlm} | j}nddlm	}	 |	j
}|s`|pTd}|| t| tsp| g}  fdd	| D }
t|
d
kr|
d }n|
d }x6|
d
d D ]&}|j|_d|_d|_| jd8  _qW x0|
dd D ] }d|j_d|_| jd8  _qW x|
D ]}d|_d|_qW |dd	 |
D }|rJ|| |r`|r`|| |S )a  Visualize the results of profiling in a bokeh plot.

    If multiple profilers are passed in, the plots are stacked vertically.

    Parameters
    ----------
    profilers : profiler or list
        Profiler or list of profilers.
    file_path : string, optional
        Name of the plot output file.
    show : boolean, optional
        If True (default), the plot is opened in a browser.
    save : boolean, optional
        If True (default), the plot is saved to disk.
    **kwargs
        Other keyword arguments, passed to bokeh.figure. These will override
        all defaults set by visualize.

    Returns
    -------
    The completed bokeh plot object.
    zbokeh.plottingr   Nz0.12.10)state)_statezprofile.htmlc                s   g | ]}|j f  qS r   )Z_plot)r   Zprof)r<   r   r   rB      s    zvisualize.<locals>.<listcomp>r         r-   K   c             S   s   g | ]
}|gqS r   r   )r   r    r   r   r   rB      s    )r   rC   bokehr   __version__Zbokeh.iorO   ZcurstateZnotebookrP   Z	_notebookZoutput_filer   r   r0   x_rangetitleZmin_border_topplot_heightxaxis
axis_labelZmin_border_bottomZmin_border_leftZmin_border_rightZgridplotshowsave)Z	profilersZ	file_pathr[   r\   r<   bprT   rO   Zin_notebookrP   Zfigsptopr    r   )r<   r   	visualize   sD    






r`   c              C   s"   t dt} | j }|d |S )Nzbokeh.plottingtools)r   rC   ZFigureZ
propertiesr	   )r]   or   r   r   _get_figure_keywords   s    


rc   Viridisc          	      s  t dt}ddlm} t dt}tddddd	d
}|dd | D  | rt|  \}	}
}}}|	t
d| }tdd | D }tdd tt| t
dddD t|t|}|jf dd ttD d| gd|}i }dd t||D  |d< }fddt||D |d< fdd|D |d<  fdd|
D  |d< }t|||d< dd |	D |d < |j|d!}|j|dddddd"d# n(|jf d$d td%D dd&gd|}d'|j_d'|j_d'|j_d(|j_d)|j_||}d*|_d+|_|S ),ae  Visualize the results of profiling in a bokeh plot.

    Parameters
    ----------
    results : sequence
        Output of Profiler.results
    dsk : dict
        The dask graph being profiled.
    palette : string, optional
        Name of the bokeh palette to use, must be a member of
        bokeh.palettes.all_palettes.
    label_size: int (optional)
        Maximum size of output labels in plot, defaults to 60
    **kwargs
        Other keyword arguments, passed to bokeh.figure. These will override
        all defaults set by visualize.

    Returns
    -------
    The completed bokeh plot object.
    zbokeh.plottingr   )	HoverToolr>   zProfile Resultsz!hover,save,reset,xwheel_zoom,xpanabovei   i,  )rW   ra   toolbar_location
plot_widthrX   c             s   s$   | ]\}}|t  kr||fV  qd S )N)rc   )r   r+   r,   r   r   r   r!      s    zplot_tasks.<locals>.<genexpr>   c             s   s$   | ]\}}|d d |D fV  qdS )c             S   s   g | ]}|j |j qS r   )Zend_time
start_time)r   ir   r   r   rB     s    z(plot_tasks.<locals>.<genexpr>.<listcomp>Nr   )r   r+   r,   r   r   r   r!     s    c             s   s   | ]\}}|d  |fV  qdS )r   Nr   )r   r@   r#   r   r   r   r!     s    r   T)keyreversec             S   s   g | ]}t |qS r   )str)r   rk   r   r   r   rB   	  s    zplot_tasks.<locals>.<listcomp>)y_rangerV   c             S   s   g | ]\}}|| qS r   r   )r   ser   r   r   rB     s    widthc                s    g | ]\}}|d  |   qS )r
   r   )r   wrp   )leftr   r   rB     s    xc                s   g | ]} | d  qS )r   r   )r   rk   )id_lkr   r   rB     s    yc                s   g | ]}t | qS r   )r"   )r   rk   )dskr7   r   r   rB     s    Zfunctioncolorc             S   s   g | ]}t |qS r   )rn   )r   rk   r   r   r   rB     s    rl   )dataZgray)sourceru   rw   Zheightrr   ry   
line_colorc             S   s   g | ]}t |qS r   )rn   )r   rk   r   r   r   rB     s       
   Nz	Worker IDzTime (s)as  
    <div>
        <span style="font-size: 14px; font-weight: bold;">Key:</span>&nbsp;
        <span style="font-size: 10px; font-family: Monaco, monospace;">@key</span>
    </div>
    <div>
        <span style="font-size: 14px; font-weight: bold;">Task:</span>&nbsp;
        <span style="font-size: 10px; font-family: Monaco, monospace;">@function</span>
    </div>
    Zfollow_mouse) r   rC   bokeh.modelsre   rD   r   updater5   rI   groupbyr   	enumerater4   rG   maxfigureranger0   rN   ColumnDataSourceZrectZgridZgrid_line_colorZaxisZaxis_line_colorZmajor_tick_line_coloryaxisrZ   rY   selecttooltipsZpoint_policy)resultsrx   rJ   r7   r<   r]   re   rL   defaultsr$   ZtasksstartsendsZidsZid_groupZtimingsrightr^   rz   rr   r   r{   hoverr   )rx   rv   r7   rt   r   
plot_tasks   sP    


 

r   c                sr  t dt}ddlm} ddlm}m} tddddd	d
}|dd |	 D  | rt
|  \}}	}
t|t|  } fdd|D }|jf tdt|
dtd|  dd|}n"g  } }	}
|jf ddd|}|j| d }|j||
|d ddd d|j_d|t|	rt|	nd|	r*t|	ndd i|_|j||	|d dddd ||dddd d|j_|S ) a  Plot resource usage in a bokeh plot.

    Parameters
    ----------
    results : sequence
        Output of ResourceProfiler.results
    palette : string, optional
        Name of the bokeh palette to use, must be a member of
        bokeh.palettes.all_palettes.
    **kwargs
        Other keyword arguments, passed to bokeh.figure. These will override
        all defaults set by plot_resources.

    Returns
    -------
    The completed bokeh plot object.
    zbokeh.plottingr   )rK   )
LinearAxisRange1dzProfile Resultszsave,reset,xwheel_zoom,xpanrf   i   i,  )rW   ra   rg   rh   rX   c             s   s$   | ]\}}|t  kr||fV  qd S )N)rc   )r   r+   r,   r   r   r   r!   K  s    z!plot_resources.<locals>.<genexpr>c                s   g | ]}|  qS r   r   )r   rk   )rt   r   r   rB   P  s    z"plot_resources.<locals>.<listcomp>d   r   )ro   rV   )r   r   )r   r      ri   z% CPU)ry   
line_widthlegendZmemoryr
   ZMemory)ry   y_range_namer   r   zMemory (MB))r   rZ   r   zTime (s))r   rC   rT   rK   r   r   r   r   r   r5   rI   rG   r   r   
fix_boundsrF   liner   rZ   Zextra_y_rangesZ
add_layoutrY   )r   rJ   r<   r]   rK   r   r   r   r#   ZmemZcpur   r^   Zcolorsr   )rt   r   plot_resources1  s:    


r   c             C   s   | t || | fS )z6Adjust end point to ensure span of at least `min_span`)r   )startendZmin_spanr   r   r   r   e  s    r   c                s  t dt}ddlm} t dt}	tddddd	d
}
|
dd | D  | rtt	|  dd \}}tt
|	|| }|	 fdd| }i }x| D ]t\}}t|d}x4|D ],}||j  |j7  < ||j  |j8  < qW dgt|	t|	dt
|  ||< qW dgfdd|D  }|jf ddt|gi|
}xzt	| t|| D ]>\\}}|jdd|d|||fdd|D dd qhW n|jf ddgddgd|
}d||j_d|j_||}d|_|S )a  Visualize the results of profiling in a bokeh plot.

    Parameters
    ----------
    results : sequence
        Output of CacheProfiler.results
    dsk : dict
        The dask graph being profiled.
    start_time : float
        Start time of the profile.
    metric_name : string
        Metric used to measure cache size
    palette : string, optional
        Name of the bokeh palette to use, must be a member of
        bokeh.palettes.all_palettes.
    label_size: int (optional)
        Maximum size of output labels in plot, defaults to 60
    **kwargs
        Other keyword arguments, passed to bokeh.figure. These will override
        all defaults set by visualize.

    Returns
    -------
    The completed bokeh plot object.
    zbokeh.plottingr   )re   r>   zProfile Resultsz hover,save,reset,wheel_zoom,xpanrf   i   i,  )rW   ra   rg   rh   rX   c             s   s$   | ]\}}|t  kr||fV  qd S )N)rc   )r   r+   r,   r   r   r   r!     s    zplot_cache.<locals>.<genexpr>r   Nc                s   t | d  S )Nr   )r"   )d)rx   r7   r   r   r&     s    zplot_cache.<locals>.<lambda>r   c                s   g | ]}|  qS r   r   )r   rk   )rj   r   r   rB     s    zplot_cache.<locals>.<listcomp>rV   ru   rw   c                s   g | ]} qS r   r   )r   rk   )rl   r   r   rB     s    )ru   rw   Zlabel)r|   r   r{   r~   )ro   rV   zCache Size ({0})zTime (s)z
    <div>
        <span style="font-size: 14px; font-weight: bold;">Task:</span>&nbsp;
        <span style="font-size: 10px; font-family: Monaco, monospace;">@label</span>
    </div>
    ) r   rC   r   re   rD   r   r   r5   r   rI   r4   rE   r   fromkeysZ
cache_timeZmetricZ	free_time
accumulater	   Zpluckr   r   rN   r$   r   r   r*   r   rZ   rY   r   r   )r   rx   rj   Zmetric_namerJ   r7   r<   r]   re   rL   r   r   r   Zticsgroupsrz   r+   ZvalsZcntsr,   r^   valry   r   r   )rx   rl   r7   rj   r   
plot_cachej  s>    



.&$
r   )r   )NTT)rd   r   )rd   )rd   r   ) Z
__future__r   r   r   rH   Zbisectr   Zdistutils.versionr   	itertoolsr   operatorr   r	   Zutilsr   r   Zcorer   Zcompatibilityr   rC   rD   r   r"   rN   r`   rc   r   r   r   r   r   r   r   r   <module>   s(   
Z
A
U
4 