ó
ßüÚ\c           @` s„  d  Z  d d l m Z m Z m Z d d l Z d d l m Z m Z d d l	 Z	 d d l
 Z
 d d l Z d d l m 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
 „  Z d „  Z d „  Z d d d „ Z d „  Z d „  Z d „  Z d d „ Z d d d d „  d „ Z d d d d d d „  d „ Z  d d d d d „ Z! d „  Z" d „  Z# d „  Z$ d „  Z% d S(   s,   This module contains utility functions to construct and manipulate counting
data structures for frames.

When performing statistical profiling we obtain many call stacks.  We aggregate
these call stacks into data structures that maintain counts of how many times
each function in that call stack has been called.  Because these stacks will
overlap this aggregation counting structure forms a tree, such as is commonly
visualized by profiling tools.

We represent this tree as a nested dictionary with the following form:

    {
     'identifier': 'root',
     'description': 'A long description of the line of code being run.',
     'count': 10  # the number of times we have seen this line
     'children': {  # callers of this line. Recursive dicts
         'ident-b': {'description': ...
                   'identifier': 'ident-a',
                   'count': ...
                   'children': {...}},
         'ident-b': {'description': ...
                   'identifier': 'ident-b',
                   'count': ...
                   'children': {...}}}
    }
i    (   t   print_functiont   divisiont   absolute_importN(   t   defaultdictt   deque(   t   sleepi   (   t   time(   t   format_timet   color_oft   parse_timedelta(   t   get_thread_identityc         C` sB   |  d k r d Sd j |  j j |  j j t |  j j ƒ f ƒ Sd S(   sq    A string identifier from a frame

    Strings are cheaper to use as indexes into dicts than tuples or dicts
    t   Nonet   ;N(   R   t   joint   f_codet   co_namet   co_filenamet   strt   co_firstlineno(   t   frame(    (    s2   lib/python2.7/site-packages/distributed/profile.pyt
   identifier+   s    		c         C` sU   |  j  } d | j |  j | j f } t j | j |  j |  j ƒ j ƒ  } | d | S(   s>    Render a frame as a line for inclusion into a text traceback s     File "%s", line %s, in %ss   
	(   R   R   t   f_linenoR   t	   linecachet   getlinet	   f_globalst   lstrip(   R   t   cot   textt   line(    (    s2   lib/python2.7/site-packages/distributed/profile.pyt
   repr_frame<   s    	$c         C` sV   |  j  } t j | j |  j |  j ƒ j ƒ  } i | j d 6| j d 6|  j d 6| d 6S(   Nt   filenamet   namet   line_numberR   (   R   R   R   R   R   R   R   R   (   R   R   R   (    (    s2   lib/python2.7/site-packages/distributed/profile.pyt
   info_frameD   s    	$


c         ` s*  | d	 k	 r, t ‡  f d †  | Dƒ ƒ r, t Sˆ  j } | d	 k	 rŽ | d	 k sc | j j j | ƒ rŽ t | ˆ  | d | ƒ} | t k rŽ t Sn  t ˆ  ƒ } y | d | } WnG t	 k
 rõ i d d 6t
 ˆ  ƒ d 6i  d 6| d 6} | | d | <n X| d c d 7<| d	 k	 r| S| d c d 7<d	 S(
   sZ   Add counts from a frame stack onto existing state

    This recursively adds counts to the existing state dictionary and creates
    new entries for new functions.

    Example
    -------
    >>> import sys, threading
    >>> ident = threading.get_ident()  # replace with your thread of interest
    >>> frame = sys._current_frames()[ident]
    >>> state = {'children': {}, 'count': 0, 'description': 'root',
    ...          'identifier': 'root'}
    >>> process(frame, None, state)
    >>> state
    {'count': 1,
     'identifier': 'root',
     'description': 'root',
     'children': {'...'}}
    c         3` s$   |  ] } ˆ  j  j j | ƒ Vq d  S(   N(   R   R   t   endswith(   t   .0t   o(   R   (    s2   lib/python2.7/site-packages/distributed/profile.pys	   <genexpr>c   s    t   stopt   childreni    t   countt   descriptionR   i   N(   R   t   anyt   Falset   f_backR   R   R"   t   processR   t   KeyErrorR!   (   R   t   childt   stateR%   t   omitt   prevt   identt   d(    (   R   s2   lib/python2.7/site-packages/distributed/profile.pyR,   O   s,    (	"
c          G` sõ   |  s t  ƒ  Sd „  |  Dƒ } t | ƒ d k rH t d t | ƒ ƒ ‚ n  t t ƒ } x< |  D]4 } x+ | d D] } | | j | d | ƒ ql Wq[ Wd „  | j ƒ  Dƒ } t d „  |  Dƒ ƒ } i |  d d d 6t	 | ƒ d 6| d	 6|  d d
 d
 6S(   s&    Merge multiple frame states together c         S` s   h  |  ] } | d  ’ q S(   R   (    (   R#   t   arg(    (    s2   lib/python2.7/site-packages/distributed/profile.pys	   <setcomp>‡   s   	 i   s   Expected identifiers, got %sR&   c         S` s%   i  |  ] \ } } t  | Œ  | “ q S(    (   t   merge(   R#   t   kt   v(    (    s2   lib/python2.7/site-packages/distributed/profile.pys
   <dictcomp>   s   	 c         s` s   |  ] } | d  Vq d S(   R'   N(    (   R#   R4   (    (    s2   lib/python2.7/site-packages/distributed/profile.pys	   <genexpr>   s    i    R(   R'   R   (
   t   createt   lent
   ValueErrorR   R   t   listt   appendt   itemst   sumt   dict(   t   argst   sR&   R4   R.   R'   (    (    s2   lib/python2.7/site-packages/distributed/profile.pyR5   ƒ   s     !c           C` s<   i d d 6i  d 6d d 6i d d 6d d 6d d	 6d d
 6d 6S(   Ni    R'   R&   t   rootR   t    R   R   R    R   R(   (    (    (    (    s2   lib/python2.7/site-packages/distributed/profile.pyR8   ™   s
    c         C` s@   g  } x& |  r. | j  t |  ƒ ƒ |  j }  q	 W| d d d … S(   sX    Create a call text stack from a frame

    Returns
    -------
    list of strings
    Niÿÿÿÿ(   R<   R   R+   (   R   t   L(    (    s2   lib/python2.7/site-packages/distributed/profile.pyt
   call_stack¢   s
    	g{®Gáz„?c         ` s$  g  ‰ g  ‰	 g  ‰ g  ‰ g  ‰  g  ‰ g  ‰
 g  ‰ g  ‰ g  ‰ g  ‰ ‡  ‡ ‡ ‡ ‡ ‡ ‡ ‡ ‡ ‡	 ‡
 ‡ ‡ f d †  ‰ ˆ |  d d d ƒ g  ˆ D] } d j  d | ƒ ^ q } i ˆ d 6ˆ	 d 6ˆ d 6ˆ d	 6g  ˆ D] } | d ^ qÔ d
 6ˆ  d 6ˆ d 6ˆ d 6ˆ d 6ˆ d 6ˆ d 6ˆ
 d 6| d 6S(   s    Convert a profile state into data useful by Bokeh

    See Also
    --------
    plot_figure
    distributed.bokeh.components.ProfilePlot
    c         ` sš  |  d s d  Sˆ j  | ƒ ˆ	 j  | ƒ ˆ j  | ƒ | | } ˆ j  | ƒ ˆ j  |  ƒ ˆ
 j  t |  d ˆ ƒ ƒ |  d } ˆ j  | d ƒ ˆ j  | d ƒ ˆ j  | d ƒ ˆ j  | d ƒ |  d } y | d } Wn t k
 rú ˆ  j  d ƒ n0 X| d	 k rˆ  j  d
 ƒ n ˆ  j  t | ƒ ƒ | | |  d } | }	 xQ |  d j ƒ  D]? \ }
 } | d | } ˆ | |	 |	 | | d ƒ |	 | 7}	 qSWd  S(   NR'   R(   R   R   R    R   R   t   grays   <low-level>t	   lightgrayR&   i   (   R<   R   t
   IndexErrorR   R=   (   R/   t   startR%   t   heightt   widtht   descR2   t   fnt   deltat   xR   R.   (   t   colorst	   filenamest   heightst   line_numberst   linest   namest   profile_intervalt   startst   statest   stopst   timest   traverset   widths(    s2   lib/python2.7/site-packages/distributed/profile.pyR[   Å   s8    



i    i   s   {:.2f}%id   t   leftt   rightt   bottomRK   t   topt   colorRX   R   R   R    R   R   t
   percentage(   t   format(   R/   RV   t   wt   percentagesRO   (    (   RP   RQ   RR   RS   RT   RU   RV   RW   RX   RY   RZ   R[   R\   s2   lib/python2.7/site-packages/distributed/profile.pyt	   plot_data°   s8    3&&t   20mst   2sc           C` s   t  S(   N(   R*   (    (    (    s2   lib/python2.7/site-packages/distributed/profile.pyt   <lambda>þ   RC   c   	      C` sÅ   t  | ƒ } t  | ƒ } t ƒ  } t ƒ  } x” | ƒ  sÀ t ƒ  | | k rt | j t ƒ  | f ƒ t ƒ  } t ƒ  } n  y t j ƒ  |  } Wn t k
 rœ d  SXt | d  | d | ƒt	 | ƒ q- Wd  S(   NR0   (
   R	   R8   R   R<   t   syst   _current_framesR-   R,   R   R   (	   t	   thread_idt   logt   intervalt   cycleR0   R%   t   recentt   lastR   (    (    s2   lib/python2.7/site-packages/distributed/profile.pyt   _watchþ   s    			iè  c           C` s   t  S(   N(   R*   (    (    (    s2   lib/python2.7/site-packages/distributed/profile.pyRi     RC   c      	   C` s†   |  d k r t ƒ  }  n  t d | ƒ } t j d t d d d i |  d 6| d 6| d 6| d	 6| d
 6| d 6ƒ } t | _ | j ƒ  | S(   sH   Gather profile information on a particular thread

    This starts a new thread to watch a particular thread and returns a deque
    that holds periodic profile information.

    Parameters
    ----------
    thread_id: int
    interval: str
        Time per sample
    cycle: str
        Time per refreshing to a new profile state
    maxlen: int
        Passed onto deque, maximum number of periods
    omit: str
        Don't include entries that start with this filename
    stop: callable
        Function to call to see if we should stop

    Returns
    -------
    deque
    t   maxlent   targetR   t   Profilet   kwargsRl   Rn   Ro   Rm   R0   R%   N(	   R   R
   R   t	   threadingt   ThreadRr   t   Truet   daemonRI   (   Rl   Rn   Ro   Rs   R0   R%   Rm   t   thread(    (    s2   lib/python2.7/site-packages/distributed/profile.pyt   watch  s     		
c         C` s(  t  ƒ  } | d k r d } n t j |  | f ƒ } | d k rH d } n4 t j |  | f ƒ d } | t |  ƒ k r| d } n  | d k r£ | d k r£ t |  ƒ }  nD | d k r» t |  ƒ n | } g  t | | ƒ D] }	 |  |	 ^ qÑ }  t t	 j
 d |  ƒ Œ  }
 |  st ƒ  S| r$t |
 | ƒ }
 n  |
 S(   s   Collect profile information from a sequence of profile states

    Parameters
    ----------
    history: Sequence[Tuple[time, Dict]]
        A list or deque of profile states
    recent: dict
        The most recent accumulating state
    start: time
    stop: time
    i    i   N(   R   R   t   bisectt   bisect_leftt   bisect_rightR9   R;   t   rangeR5   t   toolzt   pluckR8   (   t   historyRp   RI   R%   t   keyt   nowt   istartt   istopt   iistopt   it   prof(    (    s2   lib/python2.7/site-packages/distributed/profile.pyt   get_profileI  s&    				&c   	      K` sú   d d l  m } m } d d l m } d |  k rG t j |  d ƒ }  n  | d |  ƒ } | d d |  } | j d d	 d
 d d d d d d d d | ƒ} d | _	 d | _
 | d d d d ƒ } | j | ƒ t | j _ t | j _ t | j _ | | f S(   s§    Plot profile data using Bokeh

    This takes the output from the function ``plot_data`` and produces a Bokeh
    figure

    See Also
    --------
    plot_data
    i    (   t   ColumnDataSourcet   figure(   t	   HoverToolRX   t   datat   toolst   tapR]   R^   R`   R_   Ra   t
   line_colort   blackt
   line_widthi   t   sourcet   point_policyt   follow_mouset   tooltipss.  
            <div>
                <span style="font-size: 14px; font-weight: bold;">Name:</span>&nbsp;
                <span style="font-size: 10px; font-family: Monaco, monospace;">@name</span>
            </div>
            <div>
                <span style="font-size: 14px; font-weight: bold;">Filename:</span>&nbsp;
                <span style="font-size: 10px; font-family: Monaco, monospace;">@filename</span>
            </div>
            <div>
                <span style="font-size: 14px; font-weight: bold;">Line number:</span>&nbsp;
                <span style="font-size: 10px; font-family: Monaco, monospace;">@line_number</span>
            </div>
            <div>
                <span style="font-size: 14px; font-weight: bold;">Line:</span>&nbsp;
                <span style="font-size: 10px; font-family: Monaco, monospace;">@line</span>
            </div>
            <div>
                <span style="font-size: 14px; font-weight: bold;">Time:</span>&nbsp;
                <span style="font-size: 10px; font-family: Monaco, monospace;">@time</span>
            </div>
            <div>
                <span style="font-size: 14px; font-weight: bold;">Percentage:</span>&nbsp;
                <span style="font-size: 10px; font-family: Monaco, monospace;">@width</span>
            </div>
            N(   t   bokeh.plottingRŒ   R   t   bokeh.modelsRŽ   R   t   dissoct   quadR   t   selection_glypht   nonselection_glypht	   add_toolsR*   t   xaxist   visiblet   yaxist   grid(	   R   Rv   RŒ   R   RŽ   R•   t   figt   rt   hover(    (    s2   lib/python2.7/site-packages/distributed/profile.pyt   plot_figures  s2    
				c         c` s'   x  |  D] } | j  r Pn  | Vq Wd  S(   N(   t	   is_python(   t   framest   entry(    (    s2   lib/python2.7/site-packages/distributed/profile.pyt   _remove_py_stackº  s    	c         C` s  |  s
 d S|  j  ƒ  } |  r1 t |  | | ƒ } n  t | j | j ƒ } d j t t | j d | f ƒ ƒ } y | d | } Wnf t	 k
 rå i d d 6i d d 6| j d 6d d	 6t | ƒ d
 6d 6i  d 6| d 6} | | d | <n X| d c d 7<| d k	 r| S| d c d 7<d S(   sW   Add counts from low level profile information onto existing state

    This uses the ``stacktrace`` module to collect low level stack trace
    information and place it onto the given sttate.

    It is configured with the ``distributed.worker.profile.low-level`` config
    entry.

    See Also
    --------
    process
    ll_get_stack
    NR   s   <low-level>R&   i    R'   R   R   R    R   R(   R   i   (   t   popt	   llprocesst   hext   addrt   offsetR   t   mapR   R   R-   R   (   R©   R.   R/   R   R¯   R2   R3   (    (    s2   lib/python2.7/site-packages/distributed/profile.pyR­   Á  s0    $

c         C` sE   d d l  m } | |  d t ƒ} t t | ƒ ƒ d d d … } | S(   s4    Collect low level stack information from thread id i    (   t   get_thread_stackt   show_pythonNiÿÿÿÿ(   t
   stacktraceR²   R*   R;   R«   (   t   tidR²   R©   t   llframes(    (    s2   lib/python2.7/site-packages/distributed/profile.pyt   ll_get_stackï  s    (&   t   __doc__t
   __future__R    R   R   R}   t   collectionsR   R   R   Rj   Rw   R   R   R   t   metricst   utilsR   R   R	   t   compatibilityR
   R   R   R!   R   R,   R5   R8   RE   Rf   Rr   R|   R‹   R§   R«   R­   R·   (    (    (    s2   lib/python2.7/site-packages/distributed/profile.pyt   <module>   s>   			4				N0*	G		.