U
    /eI                  	   @  s  d Z ddlmZ ddlZddlmZmZmZ ddlm	Z	m
Z
 ddlmZ ddlmZmZ ddlmZ dd	lmZmZ dd
lmZmZmZmZmZ ddlmZ ejdkrdd Zndd Zd6ddZdd Z dd Z!d7ddZ"de"fddZ#dd Z$dd Z%dd  Z&d8d!d"Z'd#d$ Z(de%de&e'de(e(df	d%d&Z)G d'd( d(e	Z*e* Z+d)d*d+d,d-Z,G d.d/ d/e	Z-d0d1 Z.d2d3 Z/d4d5 Z0dS )9aQ  
Asynchronous Shared-Memory Scheduler for Dask Graphs.

This scheduler coordinates several workers to execute tasks in a dask graph in
parallel.  It depends on a ``concurrent.futures.Executor``
and a corresponding Queue for worker-to-scheduler communication.

It tries to execute tasks in an order which maintains a small memory footprint
throughout execution.  It does this by running tasks that allow us to release
data resources.


Task Selection Policy
=====================

When we complete a task we add more data in to our set of available data; this
new data makes new tasks available.  We preferentially choose tasks that were
just made available in a last-in-first-out fashion.  We implement this as a
simple stack.  This results in more depth-first rather than breadth first
behavior which encourages us to process batches of data to completion before
starting in on new data when possible.

When the addition of new data readies multiple tasks simultaneously we add
tasks to the stack in sorted order so that tasks with greater keynames are run
first.  This can be handy to break ties in a predictable fashion.


State
=====

Many functions pass around a ``state`` variable that holds the current state of
the computation.  This variable consists of several other dictionaries and
sets, explained below.

Constant state
--------------

1.  dependencies: {x: [a, b ,c]} a,b,c, must be run before x
2.  dependents: {a: [x, y]} a must run before x or y

Changing state
--------------

### Data

1.  cache: available concrete data.  {key: actual-data}
2.  released: data that we've seen, used, and released because it is no longer
    needed

### Jobs

1.  ready: A fifo stack of ready-to-run tasks
2.  running: A set of tasks currently in execution
3.  finished: A set of finished tasks
4.  waiting: which tasks are still waiting on others :: {key: {keys}}
    Real-time equivalent of dependencies
5.  waiting_data: available data to yet-to-be-run-tasks :: {key: {keys}}
    Real-time equivalent of dependents


Examples
--------

>>> import pprint  # doctest: +SKIP
>>> inc = lambda x: x + 1
>>> add = lambda x, y: x + y
>>> dsk = {'x': 1, 'y': 2, 'z': (inc, 'x'), 'w': (add, 'z', 'y')}  # doctest: +SKIP
>>> pprint.pprint(start_state_from_dask(dsk))  # doctest: +SKIP
{'cache': {'x': 1, 'y': 2},
 'dependencies': {'w': {'z', 'y'}, 'x': set(), 'y': set(), 'z': {'x'}},
 'dependents': defaultdict(None, {'w': set(), 'x': {'z'}, 'y': {'w'}, 'z': {'w'}}),
 'finished': set(),
 'ready': ['z'],
 'released': set(),
 'running': set(),
 'waiting': {'w': {'z'}},
 'waiting_data': {'x': {'z'}, 'y': {'w'}, 'z': {'w'}}}

Optimizations
=============

We build this scheduler with out-of-core array operations in mind.  To this end
we have encoded some particular optimizations.

Compute to release data
-----------------------

When we choose a new task to execute we often have many options.  Policies at
this stage are cheap and can significantly impact performance.  One could
imagine policies that expose parallelism, drive towards a particular output,
etc..

Our current policy is to run tasks that were most recently made available.


Inlining computations
---------------------

We hold on to intermediate computations either in memory or on disk.

For very cheap computations that may emit new copies of the data, like
``np.transpose`` or possibly even ``x + 1`` we choose not to store these as
separate pieces of data / tasks.  Instead we combine them with the computations
that require them.  This may result in repeated computation but saves
significantly on space and computation complexity.

See the function ``inline_functions`` for more information.
    )annotationsN)HashableMappingSequence)ExecutorFuture)partial)EmptyQueue)config)local_callbacksunpack_callbacks)_execute_taskflattenget_dependencies	has_tasksreverse_dict)orderntc                 C  s,   z| j dddW S  tk
r$   Y q X q d S )NTg?)blocktimeout)getr	   q r   ./tmp/pip-unpacked-wheel-dbjnr7gq/dask/local.py	queue_get   s    r   c                 C  s   |   S N)r   r   r   r   r   r      s    c              
     s:  |dkrt | j}|dkr&tdd}|dkr4t }t  |  D ]$\}}t| |sB|||<  | qB|  	| fdd| D } fdd| D }t
|}|D ]$}||dD ]}	||	 | qqdd | D }
dd	 | D }t||d
d}dd | D }||||
||t t t d	}|S )a  Start state from a dask

    Examples
    --------
    >>> inc = lambda x: x + 1
    >>> add = lambda x, y: x + y
    >>> dsk = {'x': 1, 'y': 2, 'z': (inc, 'x'), 'w': (add, 'z', 'y')}  # doctest: +SKIP
    >>> from pprint import pprint  # doctest: +SKIP
    >>> pprint(start_state_from_dask(dsk))  # doctest: +SKIP
    {'cache': {'x': 1, 'y': 2},
     'dependencies': {'w': {'z', 'y'}, 'x': set(), 'y': set(), 'z': {'x'}},
     'dependents': defaultdict(None, {'w': set(), 'x': {'z'}, 'y': {'w'}, 'z': {'w'}}),
     'finished': set(),
     'ready': ['z'],
     'released': set(),
     'running': set(),
     'waiting': {'w': {'z'}},
     'waiting_data': {'x': {'z'}, 'y': {'w'}, 'z': {'w'}}}
    Ncachec                   s   i | ]}|t  |qS r   )r   ).0k)dsk2r   r   
<dictcomp>   s      z)start_state_from_dask.<locals>.<dictcomp>c                   s"   i | ]\}}| kr||  qS r   copyr   r    v)	data_keysr   r   r"      s       r   c                 S  s   i | ]\}}|r||  qS r   r#   r%   r   r   r   r"      s       c                 S  s   h | ]\}}|s|qS r   r   r%   r   r   r   	<setcomp>   s      z(start_state_from_dask.<locals>.<setcomp>Tkeyreversec                 S  s   i | ]\}}|r||qS r   r   r%   r   r   r   r"      s       )	dependencies
dependentswaitingwaiting_datar   readyrunningfinishedreleased)r   r   r   dictsetitemsr   addr$   updater   removesorted)dskr   sortkeyr    r&   r,   r.   r-   abr/   Z	ready_setr0   stater   )r'   r!   r   start_state_from_dask   sD    


r@   c              
   C  sl   z0||\}}t ||}| }	|||	f}d}
W n0 tk
r` } z|||}d}
W 5 d}~X Y nX | ||
fS )zy
    Compute task and handle all administration

    See Also
    --------
    _execute_task : actually execute task
    FTN)r   BaseException)r*   Z	task_infodumpsloadsget_idpack_exceptiontaskdataresultidfaileder   r   r   execute_task   s    

rL   c                 C  s   dd | D S )z?
    Batch computing of multiple tasks with `execute_task`
    c                 S  s   g | ]}t | qS r   )rL   )r   r=   r   r   r   
<listcomp>   s     z'batch_execute_tasks.<locals>.<listcomp>r   )itr   r   r   batch_execute_tasks   s    rO   Tc                 C  sF   | |d kr&|d |  rt |d | = |d |  |rB|d | = dS )zRRemove data from temporary storage

    See Also
    --------
    finish_task
    r/   r3   r   N)AssertionErrorr7   )r*   r?   deleter   r   r   release_data   s    
rR   c           	      C  s   t |d | |ddD ]6}|d | }|| |s|d |= |d | q|d | D ]\}||d kr|d | }|| |s||kr||||d qZ|rZ||krZ||||d qZ|d	 | |d
 | |S )zo
    Update execution state after a task finishes

    Mutates.  This should run atomically (with a lock).
    r-   Tr)   r.   r0   r,   r/   )rQ   r2   r1   )r:   r9   appendr7   )	r;   r*   r?   resultsr<   rQ   rR   depsr   r   r   finish_task  s"    


rW   c                   s,   t | tr t fdd| D S  |  S dS )zGet nested index from collection

    Examples
    --------

    >>> nested_get(1, 'abc')
    'b'
    >>> nested_get([1, 0], 'abc')
    ('b', 'a')
    >>> nested_get([[1, 0], [0, 1]], 'abc')
    (('b', 'a'), ('a', 'b'))
    c                 3  s   | ]}t | V  qd S r   )
nested_get)r   icollr   r   	<genexpr>.  s     znested_get.<locals>.<genexpr>N)
isinstancelisttuple)indr[   r   rZ   r   rX      s    
rX   c                   C  s   dS )zDefault get_idNr   r   r   r   r   default_get_id3  s    ra   c                  C  s    d S r   r   )rK   rB   r   r   r   default_pack_exception8  s    rb   c                 C  s   | j |k	r| || d S r   )__traceback__with_traceback)exctbr   r   r   reraise<  s    

rg   c                 C  s   | S )z=Identity function. Returns x.

    >>> identity(3)
    3
    r   )xr   r   r   identityB  s    ri   c           #        sF  |pt dd}t t|tr.tt|}n|h}t|}t  t|	}	t	|	\}}}}g }d}i z|	D ]"}|d r|d   |
| qvt }t ||jd|	D ]\}}}}}|r|  q|dkrt dd}d rd	 std
 	f
dd}d s@d	 s@d r|| t D ]\}}}|r|\}}|rfddt |D } | }t|| n
||| |\} }!| d |< t |||j |D ]}"|"||  |! qڐqTq"d}W 5 |D ]$\}}}}}|r| |  qX W 5 Q R X t|d S )ad  Asynchronous get function

    This is a general version of various asynchronous schedulers for dask.  It
    takes a ``concurrent.futures.Executor.submit`` function to form a more
    specific ``get`` method that walks through the dask array with parallel
    workers, avoiding repeat computation and minimizing memory use.

    Parameters
    ----------
    submit : function
        A ``concurrent.futures.Executor.submit`` function
    num_workers : int
        The number of workers that task submissions can be spread over
    dsk : dict
        A dask dictionary specifying a workflow
    result : key or list of keys
        Keys corresponding to desired data
    cache : dict-like, optional
        Temporary storage of results
    get_id : callable, optional
        Function to return the worker id, takes no arguments. Examples are
        `threading.current_thread` and `multiprocessing.current_process`.
    rerun_exceptions_locally : bool, optional
        Whether to rerun failing tasks in local process to enable debugging
        (False by default)
    pack_exception : callable, optional
        Function to take an exception and ``dumps`` method, and return a
        serialized tuple of ``(exception, traceback)`` to send back to the
        scheduler. Default is to just raise the exception.
    raise_exception : callable, optional
        Function that takes an exception and a traceback, and raises an error.
    callbacks : tuple or list of tuples, optional
        Callbacks are passed in as tuples of length 5. Multiple sets of
        callbacks may be passed in as a list of tuples. For more information,
        see the dask.diagnostics documentation.
    dumps: callable, optional
        Function to serialize task data and results to communicate between
        worker and parent.  Defaults to identity.
    loads: callable, optional
        Inverse function of `dumps`.  Defaults to identity.
    chunksize: int, optional
        Size of chunks to use when dispatching work. Defaults to 1.
        If -1, will be computed to evenly divide ready work across workers.

    See Also
    --------
    threaded.get
    	chunksize   Fr   )r   r<   Nrerun_exceptions_locallyr.   r0   z Found no accessible jobs in daskc              	     s*  t d }| dkr&|}|   } n0t d |    }t| d}t|| | }g }t|D ]n}d  }d | D ]}||  qfddt |D }	|| | |	ff qbtt ||    D ]>}
||
|  |
d |   }|s q&	t|}|	j
 qdS )	z"Fire off a task to the thread poolr0   r1   r   c                   s   i | ]}| d  | qS r   r   r   rU   r?   r   r   r"     s     z1get_async.<locals>.fire_tasks.<locals>.<dictcomp>rk   N)lenmaxminrangepopr7   r   rS   rO   Zadd_done_callbackput)rj   ZnreadyZntasksZused_workersZavail_workersargs_r*   frG   rY   Z	each_argsfut
r;   rB   rD   rC   num_workersrE   Zpretask_cbsqueuer?   submitr   r   
fire_tasks  s>    

zget_async.<locals>.fire_tasksr1   c                   s   i | ]}| d  | qS rn   r   ro   rp   r   r   r"     s    zget_async.<locals>.<dictcomp>r   T)r   r   r
   r]   r^   r5   r   r4   r   r   rS   r   r@   
ValueErrorr   rH   r   r   rW   rX   )#r~   r|   r;   rH   r   rD   rl   rE   Zraise_exception	callbacksrB   rC   rj   kwargsZresult_flatrT   rx   Zposttask_cbsZstarted_cbsZ	succeededfinishcbZkeyorderZstart_stater   r*   Zres_inforJ   re   rf   rG   rF   resZ	worker_idry   r   r{   r   	get_async^  sb    @
.

r   c                   @  s   e Zd ZdZdd ZdS )SynchronousExecutorrk   c              
   O  sL   t  }z|||| W n, tk
rF } z|| W 5 d }~X Y nX |S r   )r   
set_resultrA   set_exception)selffnrw   r   rz   rK   r   r   r   r~     s    zSynchronousExecutor.submitN)__name__
__module____qualname___max_workersr~   r   r   r   r   r     s   r   r   zSequence[Hashable] | Hashable)r;   keysc                 K  s"   | dd ttjtj| |f|S )zOA naive synchronous version of get_async

    Can be useful for debugging.
    r|   N)ru   r   synchronous_executorr~   r   )r;   r   r   r   r   r   get_sync'  s    r   c                   @  s   e Zd Zdd Zdd ZdS )MultiprocessingPoolExecutorc                 C  s   || _ t|j| _d S r   )poolrq   _poolr   )r   r   r   r   r   __init__B  s    z$MultiprocessingPoolExecutor.__init__c                 O  s   t | jj|f||S r   )submit_apply_asyncr   apply_async)r   r   rw   r   r   r   r   r~   F  s    z"MultiprocessingPoolExecutor.submitN)r   r   r   r   r~   r   r   r   r   r   A  s   r   c                 O  s   t  }| ||||j|j |S r   )r   r   r   )r   r   rw   r   rz   r   r   r   r   J  s    r   c                 O  s   t tt| |f||S r   )r   r   r   )r   r|   rw   r   r   r   r   get_apply_asyncP  s     r   c                 C  s   t | j| fS )a  Sorting key function that is robust to different types

    Both strings and tuples are common key types in dask graphs.
    However In Python 3 one can not compare strings with tuples directly.
    This function maps many types to a form where they can be compared

    Examples
    --------
    >>> sortkey('Hello')
    ('str', 'Hello')

    >>> sortkey(('x', 1))
    ('tuple', ('x', 1))
    )typer   )itemr   r   r   r<   V  s    r<   )NN)T)N)1__doc__
__future__r   oscollections.abcr   r   r   concurrent.futuresr   r   	functoolsr   r}   r	   r
   Zdaskr   Zdask.callbacksr   r   Z	dask.corer   r   r   r   r   Z
dask.orderr   namer   r@   rL   rO   rR   rW   rX   ra   rb   rg   ri   r   r   r   r   r   r   r   r<   r   r   r   r   <module>   sV   l

	
J
 

!
 ;	