
    Lgt                       U d dl mZ d dlZd dl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 d dlmZmZ d dl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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 dl&m(Z) d dl&m*Z* d dl+m,Z, d dl-m.Z.m/Z/ d dl0m1Z1m2Z2m3Z3m4Z4m5Z5 da6da7da8dCdZ9dZ:d dl;m<Z<m=Z=m>Z>  edd      Z?de@d<   dDdZAedEd       ZBdCdZC G d d       ZDdFd!ZEd" ZFd# ZGdGd%ZHd& ZId$d'd(ZJd$d'd)ZKd$d$ddd*d+ZLd,d$d-ddd.	 dHd/ZM	 	 	 	 	 	 	 dI	 dHd0ZNd$d$dd1d2ZOd3 ZPe#j                  e#j                  e#j                  d4ZRd5e@d6<   e%s\d d7l!mSZS eRj                  eSjP                  eSjP                  d8       d d9l!mUZV eRj                  eVjP                  eVjP                  d:       d;j                         ZXdJd<ZYdKd=ZZdLd>Z[dMd?Z\ ed@e.e]      Z^dNdAZ_dOdBZ`y)P    )annotationsN)OrderedDict)HashableIteratorMapping)Executor)contextmanagersuppress)
ContextVar)partial)IntegralNumber)getitem)AnyLiteralTypeVar)groupbymerge)configlocal)
EMSCRIPTEN)flatten)get)quote)	CPU_COUNT)KeySchedulerGetCallable)applyensure_dictis_namedtuple_instance	key_splitshorten_tracebackc                 p    t         t         S 	 ddlma ddlma da t         S # t        $ r
 da Y t         S w xY w)Nr   )Client
get_clientTF)_DISTRIBUTED_AVAILABLEdistributedr$   _DistributedClientdistributed.workerr&   _get_distributed_clientImportError     )lib/python3.12/site-packages/dask/base.py_distributed_availabler0   '   sF     )%%'<L!% "!  '!&!!'s   " 55)DaskMethodsMixinannotateget_annotationsis_dask_collectioncomputepersistoptimize	visualizetokenizenormalize_tokenget_collection_namesget_name_from_keyreplace_name_in_key	clone_key)TokenizationErrorr:   r9   r   )defaultz!ContextVar[dict[str, Any] | None]_annotationsc                 2    t         j                         xs i S )zGet current annotations.

    Returns
    -------
    Dict of all current annotations

    See Also
    --------
    annotate
    )rA   r   r-   r.   r/   r3   r3   O   s     ##r.   c               +  t  K   d| v rmt        | d   t        t        t        f      rt        | d         | d<   n=t        | d   t              r
| d   g| d<   n t        | d         rnt        d| d   z        d| v r2t        | d   t              st        | d         st        d| d   z        d| v r2t        | d   t              st        | d         st        d| d   z        d| v r2t        | d   t              st        | d         st        d| d   z        d	| v r2t        | d	   t              st        | d	         st        d
| d	   z        t        j                         }|i }t        j                  t        ||             }	 d t        j                  |       y# t        j                  |       w xY ww)a  Context Manager for setting HighLevelGraph Layer annotations.

    Annotations are metadata or soft constraints associated with
    tasks that dask schedulers may choose to respect: They signal intent
    without enforcing hard constraints. As such, they are
    primarily designed for use with the distributed scheduler.

    Almost any object can serve as an annotation, but small Python objects
    are preferred, while large objects such as NumPy arrays are discouraged.

    Callables supplied as an annotation should take a single *key* argument and
    produce the appropriate annotation. Individual task keys in the annotated collection
    are supplied to the callable.

    Parameters
    ----------
    **annotations : key-value pairs

    Examples
    --------

    All tasks within array A should have priority 100 and be retried 3 times
    on failure.

    >>> import dask
    >>> import dask.array as da
    >>> with dask.annotate(priority=100, retries=3):
    ...     A = da.ones((10000, 10000))

    Prioritise tasks within Array A on flattened block ID.

    >>> nblocks = (10, 10)
    >>> with dask.annotate(priority=lambda k: k[1]*nblocks[1] + k[2]):
    ...     A = da.ones((1000, 1000), chunks=(100, 100))

    Annotations may be nested.

    >>> with dask.annotate(priority=1):
    ...     with dask.annotate(retries=3):
    ...         A = da.ones((1000, 1000))
    ...     B = A + 1

    See Also
    --------
    get_annotations
    workerszP'workers' annotation must be a sequence of str, a str or a callable, but got %s.priorityz@'priority' annotation must be a Number or a callable, but got %sretriesz?'retries' annotation must be a Number or a callable, but got %s	resourcesz1'resources' annotation must be a dict, but got %sallow_other_workerszJ'allow_other_workers' annotations must be a bool or a callable, but got %sN)
isinstancelistsettuplestrcallable	TypeErrorr   dictboolrA   r   r   reset)r   	ctx_annottokens      r/   r2   r2   ]   s    f Kk),tS%.@A%)+i*@%AK	"I.4&1)&<%=K	"k),-bi()  	k!;z2F;Z01N*%&
 	
 	[ ;y16:Y/0M)$%
 	
 	{";{3T:[12?+&'
 	
 	,;'<=tD%:;<X/01
 	
   "I	U9k:;E"5!5!s   FF8F F8F55F8c                    t        | t              s!t        | d      rt        | j                        syt        t        |       dd      j                  d      d   }|dv ry| j	                         d	uS )
a  Returns ``True`` if ``x`` is a dask collection.

    Parameters
    ----------
    x : Any
        Object to test.

    Returns
    -------
    result : bool
        ``True`` if `x` is a Dask collection.

    Notes
    -----
    The DaskCollection typing.Protocol implementation defines a Dask
    collection as a class that returns a Mapping from the
    ``__dask_graph__`` method. This helper function existed before the
    implementation of the protocol.

    __dask_graph__F
__module__ .r   )	dask_expr	dask_cudfTN)rI   typehasattrrN   rV   getattrsplit)xpkg_names     r/   r4   r4      sp    , 	1dq*+(()tAwb177<Q?H--
  T))r.   c                  .    e Zd ZdZdZddZd Zd Zd Zy)	r1   z/A mixin adding standard dask collection methods)__weakref__Nc                "    t        | f|||d|S )a&  Render the computation of this object's task graph using graphviz.

        Requires ``graphviz`` to be installed.

        Parameters
        ----------
        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.
        format : {'png', 'pdf', 'dot', 'svg', 'jpeg', 'jpg'}, optional
            Format in which to write output file.  Default is 'png'.
        optimize_graph : bool, optional
            If True, the graph is optimized before rendering.  Otherwise,
            the graph is displayed as is. Default is False.
        color: {None, 'order'}, optional
            Options to color nodes.  Provide ``cmap=`` keyword for additional
            colormap
        **kwargs
           Additional keyword arguments to forward to ``to_graphviz``.

        Examples
        --------
        >>> x.visualize(filename='dask.pdf')  # doctest: +SKIP
        >>> x.visualize(filename='dask.pdf', color='order')  # doctest: +SKIP

        Returns
        -------
        result : IPython.display.Image, IPython.display.SVG, or None
            See dask.dot.dot_graph for more information.

        See Also
        --------
        dask.visualize
        dask.dot.dot_graph

        Notes
        -----
        For more information on optimization see here:

        https://docs.dask.org/en/latest/optimize.html
        )filenameformatoptimize_graph)r8   )selfre   rf   rg   kwargss        r/   r8   zDaskMethodsMixin.visualize   s-    X 
)	

 
 	
r.   c                &    t        | fddi|\  }|S )a  Persist this dask collection into memory

        This turns a lazy Dask collection into a Dask collection with the same
        metadata, but now with the results fully computed or actively computing
        in the background.

        The action of function differs significantly depending on the active
        task scheduler.  If the task scheduler supports asynchronous computing,
        such as is the case of the dask.distributed scheduler, then persist
        will return *immediately* and the return value's task graph will
        contain Dask Future objects.  However if the task scheduler only
        supports blocking computation then the call to persist will *block*
        and the return value's task graph will contain concrete Python results.

        This function is particularly useful when using distributed systems,
        because the results will be kept in distributed memory, rather than
        returned to the local process as with compute.

        Parameters
        ----------
        scheduler : string, optional
            Which scheduler to use like "threads", "synchronous" or "processes".
            If not provided, the default is to check the global settings first,
            and then fall back to the collection defaults.
        optimize_graph : bool, optional
            If True [default], the graph is optimized before computation.
            Otherwise the graph is run as is. This can be useful for debugging.
        **kwargs
            Extra keywords to forward to the scheduler function.

        Returns
        -------
        New dask collections backed by in-memory data

        See Also
        --------
        dask.persist
        traverseF)r6   rh   ri   results      r/   r6   zDaskMethodsMixin.persist2  s     N D;5;F;	r.   c                &    t        | fddi|\  }|S )a  Compute this dask collection

        This turns a lazy Dask collection into its in-memory equivalent.
        For example a Dask array turns into a NumPy array and a Dask dataframe
        turns into a Pandas dataframe.  The entire dataset must fit into memory
        before calling this operation.

        Parameters
        ----------
        scheduler : string, optional
            Which scheduler to use like "threads", "synchronous" or "processes".
            If not provided, the default is to check the global settings first,
            and then fall back to the collection defaults.
        optimize_graph : bool, optional
            If True [default], the graph is optimized before computation.
            Otherwise the graph is run as is. This can be useful for debugging.
        kwargs
            Extra keywords to forward to the scheduler function.

        See Also
        --------
        dask.compute
        rk   F)r5   rl   s      r/   r5   zDaskMethodsMixin.compute\  s    0 D;5;F;	r.   c                     	 ddl mm  fd} |       j	                         S # t        $ r}t        d      |d }~ww xY w)Nr   )
futures_ofwaitz>Using async/await with dask requires the `distributed` packagec                 D   K           r        d {    S 7 wNr-   )rp   rh   rq   s   r/   fz%DaskMethodsMixin.__await__.<locals>.f  s&     $4j  K !s     )r(   rp   rq   r,   	__await__)rh   ert   rp   rq   s   `  @@r/   ru   zDaskMethodsMixin.__await__w  sE    	4	
 s}}  	P	s   ) 	A>A)mydaskNF)	__name__rW   __qualname____doc__	__slots__r8   r6   r5   ru   r-   r.   r/   r1   r1      s     9 I2
h(T6r.   r1   c                X    t        || |      } t        |       ||fi |} |||fi |S )zqCompute a graph as if it were of type cls.

    Allows for applying the same optimizations and default scheduler.)	schedulerclsr   )get_scheduleroptimization_function)r~   dskkeysr}   r   ri   scheduledsk2s           r/   compute_as_if_collectionr     s=     ycsCH% %c4:6:DD$)&))r.   c                    | S rs   r-   )r   r   ri   s      r/   dont_optimizer     s    Jr.   c                $    t        | dt              S )N__dask_optimize__)r^   r   )r`   s    r/   r   r     s    1)=99r.   Tc                   ddl m t        |      t        t        j                  dd            z   }|rt        t        |       }g }|j                         D ]?  \  }}t        |      \  }}	 |||	fi |}|D ]  }
 |
||	fi |} |j                  |       A t        fd|D              r j                  | }|S t        t        t        |       }|S t        |       \  }}|S )zO
    Convert many collections into a single dask graph, after optimization
    r   HighLevelGraphoptimizationsr-   c              3  6   K   | ]  }t        |        y wrs   rI   .0graphr   s     r/   	<genexpr>z%collections_to_dsk.<locals>.<genexpr>  s     EfUz%0f   )dask.highlevelgraphr   rL   r   r   r   r   items_extract_graph_and_keysappendanyr   mapr   )collectionsrg   r   ri   groupsgraphsoptvalr   r   	opt_inner_r   s               @r/   collections_to_dskr     s     3-(5OR1P+QQM.<HC/4ICc4*6*C*	T4V4 + MM# ' EfEE&.&&/C J	 [&12C J )5QJr.   c                $   ddl m g g }}| D ]@  }|j                  |j                                |j                  |j	                                B t        fd|D              r j                  | }||fS t        t        t        |       }||fS )zGiven a list of dask vals, return a single graph and a list of keys such
    that ``get(dsk, keys)`` is equivalent to ``[v.compute() for v in vals]``.r   r   c              3  6   K   | ]  }t        |        y wrs   r   r   s     r/   r   z*_extract_graph_and_keys.<locals>.<genexpr>  s     
A&:e^,&r   )	r   r   r   rV   __dask_keys__r   r   r   r   )valsr   r   vr   r   s        @r/   r   r     s     3rDFa&&()AOO%&  
A&
AA$$$f- $; s;/0$;r.   )rk   c                4   	 g i 	t        j                         j                  	 fdt        j                         j                  t        |D cg c]
  } |       c}f	<   	fd}t	              }j                          ||fS c c}w )a  Extract collections in preparation for compute/persist/etc...

    Intended use is to find all collections in a set of (possibly nested)
    python objects, do something to them (compute, etc...), then repackage them
    in equivalent python objects.

    Parameters
    ----------
    *args
        Any number of objects. If it is a dask collection, it's extracted and
        added to the list of collections returned. By default, python builtin
        collections are also traversed to look for dask collections (for more
        information see the ``traverse`` keyword).
    traverse : bool, optional
        If True (default), builtin python collections are traversed looking for
        any dask collections they might contain.

    Returns
    -------
    collections : list
        A list of all dask collections contained in ``args``
    repack : callable
        A function to call on the transformed collections to repackage them as
        they were in the original ``args``.
    c                   t        |       r7t        |       }|vr&t        
t        	      f|<   	j	                  |        |S t        j                         j                  }st        |       }n4t        | t              rt        n
t        |       }|t        t        t        fv r|| D cg c]
  } |       c}f}n|t        t         fv r4|| j#                         D cg c]  \  }} |       |      g c}}f}nt%        j&                  |       rht        | t              sXt(        |dt        t%        j*                  |       D cg c]*  }|j,                   t/        | |j,                              g, c}ff}n(t1        |       r|g| D cg c]
  } |       c}}n| S ||<   |S c c}w c c}}w c c}w c c}w )Nr-   )r4   r9   r   lenr   uuiduuid4hexr   rI   r   rJ   r\   rL   rK   rP   r   r   dataclassesis_dataclassr   fieldsnamer^   r    )exprtoktsktypikr   rt   _unpackr   collections_token
repack_dskrk   s           r/   r   z#unpack_collections.<locals>._unpack  s   d#4.C*$#*,=s;?O"P
3""4(Jjjl+C %T84$$t*CtUC((6AWQZ67{++$**,O,$!Qgaj'!*5,OP))$/
48N &1%7%7%=%= VVWWT166-B%CD%=	 (-8$7$Qgaj$78
3
- 7O 8s   *F, F1/F7F<c                X    j                         }t        |       |<   t        |      S rs   )copyr   
simple_get)resultsr   r   outr   s     r/   repackz"unpack_collections.<locals>.repack  s+    oo!&w#s##r.   )r   r   r   rL   rJ   clear)
rk   argsr   r   collections2r   r   r   r   r   s
   `    @@@@@r/   unpack_collectionsr     s    6 KJ

((% %N **,

C484awqz489JsO$ $L 9s   Bc                    t        |d| i\  }}|s|S t        |fi |}g }|D ]-  }|j                         \  }}	|j                   ||g|	        /  ||      S )a  Optimize several dask collections at once.

    Returns equivalent dask collections that all share the same merged and
    optimized underlying graph. This can be useful if converting multiple
    collections to delayed objects, or to manually apply the optimizations at
    strategic points.

    Note that in most cases you shouldn't need to call this method directly.

    Parameters
    ----------
    *args : objects
        Any number of objects. If a dask object, its graph is optimized and
        merged with all those of all other dask objects before returning an
        equivalent dask collection. Non-dask arguments are passed through
        unchanged.
    traverse : bool, optional
        By default dask traverses builtin python collections looking for dask
        objects passed to ``optimize``. For large collections this can be
        expensive. If none of the arguments contain any dask objects, set
        ``traverse=False`` to avoid doing this traversal.
    optimizations : list of callables, optional
        Additional optimization passes to perform.
    **kwargs
        Extra keyword arguments to forward to the optimization passes.

    Examples
    --------
    >>> import dask
    >>> import dask.array as da
    >>> a = da.arange(10, chunks=2).sum()
    >>> b = da.arange(10, chunks=2).mean()
    >>> a2, b2 = dask.optimize(a, b)

    >>> a2.compute() == a.compute()
    np.True_
    >>> b2.compute() == b.compute()
    np.True_
    rk   )r   r   __dask_postpersist__r   )
rk   r   ri   r   r   r   postpersistsarss
             r/   r7   r7      st    P -dFXFK
[
3F
3CL%%'1AcJAJ'  ,r.   )rk   rg   r}   r   c                   t        |d| i\  }}|s|S t        |||      }t        ||fi |}	g g }}
|D ]@  }|
j                  |j	                                |j                  |j                                B t               5   ||	|
fi |}ddd        |t        |      D cg c]  \  }\  }} ||g|  c}}}      S # 1 sw Y   :xY wc c}}}w )a  Compute several dask collections at once.

    Parameters
    ----------
    args : object
        Any number of objects. If it is a dask object, it's computed and the
        result is returned. By default, python builtin collections are also
        traversed to look for dask objects (for more information see the
        ``traverse`` keyword). Non-dask arguments are passed through unchanged.
    traverse : bool, optional
        By default dask traverses builtin python collections looking for dask
        objects passed to ``compute``. For large collections this can be
        expensive. If none of the arguments contain any dask objects, set
        ``traverse=False`` to avoid doing this traversal.
    scheduler : string, optional
        Which scheduler to use like "threads", "synchronous" or "processes".
        If not provided, the default is to check the global settings first,
        and then fall back to the collection defaults.
    optimize_graph : bool, optional
        If True [default], the optimizations for each collection are applied
        before computation. Otherwise the graph is run as is. This can be
        useful for debugging.
    get : ``None``
        Should be left to ``None`` The get= keyword has been removed.
    kwargs
        Extra keywords to forward to the scheduler function.

    Examples
    --------
    >>> import dask
    >>> import dask.array as da
    >>> a = da.arange(10, chunks=2).sum()
    >>> b = da.arange(10, chunks=2).mean()
    >>> dask.compute(a, b)
    (np.int64(45), np.float64(4.5))

    By default, dask objects inside python collections will also be computed:

    >>> dask.compute({'a': a, 'b': b, 'c': 1})
    ({'a': np.int64(45), 'b': np.float64(4.5), 'c': 1},)
    rk   )r}   r   r   N)r   r   r   r   r   __dask_postcompute__r"   zip)rk   rg   r}   r   r   ri   r   r   r   r   r   postcomputesr`   r   r   rt   r   s                    r/   r5   r5   V  s    Z -dFXFKH [.
CF
CCR,DAOO%&A2245  
	3// 
 S,-GH-G	6Aq1Q88-GHII 
	 Is   C&CCrw   F)re   rk   rg   maxvalenginec           
     n    t        |d|i\  }}t        t        ||            }t        d|| ||||d|S )a  
    Visualize several dask graphs simultaneously.

    Requires ``graphviz`` to be installed. All options that are not the dask
    graph(s) should be passed as keyword arguments.

    Parameters
    ----------
    args : object
        Any number of objects. If it is a dask collection (for example, a
        dask DataFrame, Array, Bag, or Delayed), its associated graph
        will be included in the output of visualize. By default, python builtin
        collections are also traversed to look for dask objects (for more
        information see the ``traverse`` keyword). Arguments lacking an
        associated graph will be ignored.
    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.
    format : {'png', 'pdf', 'dot', 'svg', 'jpeg', 'jpg'}, optional
        Format in which to write output file.  Default is 'png'.
    traverse : bool, optional
        By default, dask traverses builtin python collections looking for dask
        objects passed to ``visualize``. For large collections this can be
        expensive. If none of the arguments contain any dask objects, set
        ``traverse=False`` to avoid doing this traversal.
    optimize_graph : bool, optional
        If True, the graph is optimized before rendering.  Otherwise,
        the graph is displayed as is. Default is False.
    color : {None, 'order', 'ages', 'freed', 'memoryincreases', 'memorydecreases', 'memorypressure'}, optional
        Options to color nodes. colormap:

        - None, the default, no colors.
        - 'order', colors the nodes' border based on the order they appear in the graph.
        - 'ages', how long the data of a node is held.
        - 'freed', the number of dependencies released after running a node.
        - 'memoryincreases', how many more outputs are held after the lifetime of a node.
          Large values may indicate nodes that should have run later.
        - 'memorydecreases', how many fewer outputs are held after the lifetime of a node.
          Large values may indicate nodes that should have run sooner.
        - 'memorypressure', the number of data held when the node is run (circle), or
          the data is released (rectangle).
    maxval : {int, float}, optional
        Maximum value for colormap to normalize form 0 to 1.0. Default is ``None``
        will make it the max number of values
    collapse_outputs : bool, optional
        Whether to collapse output boxes, which often have empty labels.
        Default is False.
    verbose : bool, optional
        Whether to label output and input boxes even if the data aren't chunked.
        Beware: these labels can get very long. Default is False.
    engine : {"graphviz", "ipycytoscape", "cytoscape"}, optional.
        The visualization engine to use. If not provided, this checks the dask config
        value "visualization.engine". If that is not set, it tries to import ``graphviz``
        and ``ipycytoscape``, using the first one to succeed.
    **kwargs
       Additional keyword arguments to forward to the visualization engine.

    Examples
    --------
    >>> x.visualize(filename='dask.pdf')  # doctest: +SKIP
    >>> x.visualize(filename='dask.pdf', color='order')  # doctest: +SKIP

    Returns
    -------
    result : IPython.display.Image, IPython.display.SVG, or None
        See dask.dot.dot_graph for more information.

    See Also
    --------
    dask.dot.dot_graph

    Notes
    -----
    For more information on optimization see here:

    https://docs.dask.org/en/latest/optimize.html
    rk   )rg   )r   re   rk   rg   r   r   r-   )r   rP   r   visualize_dsk)	re   rk   rg   r   r   r   ri   r   r   s	            r/   r8   r8     sX    p !$::GD!
!$~F
GC %  r.   c                
   |j                  d      }	ddlm}
m} |	dv r*dd lm} 9 || d      }|j                         D ci c]  \  }}||j                   c}}nkt        t        t        j                                     t              r || d      }n0}j                         D ci c]  \  }}||j                   c}}	 |j                  d      }t        |t"              rdd lm} t%        |j                  |      }fd}d }|	d	k7  r |
|       d   }|	j'                  d
      r0|j                         D ci c]  \  }}||j(                   c}}n|	j'                  d      r0|j                         D ci c]  \  }}||j*                   c}}nk|	j'                  d      r\|j                         D ci c]  \  }}||j,                   c}}|j                         D ci c]  \  }}||j.                   }}}n|	j'                  d      rF|j                         D ci c])  \  }}|t1        d|j.                  |j,                  z
        + c}}n|	j'                  d      rF|j                         D ci c])  \  }}|t1        d|j,                  |j.                  z
        + c}}nP|	j3                  d      d   dv r/|j                         D ci c]  \  }}||j4                   c}}nt7        |	      |	j9                  d      r	fd}n|#t1        dt1        j                                     }j                         D ci c]3  \  }}|t;        t=        t?        t         |||z  d                        5 }}}||}nNj                         D ci c]3  \  }}|t;        t=        t?        t         |||z  d                        5 }}}|j                         D ci c]  \  }}|| ||      d c}}|d<   |j                         D ci c]
  \  }}|d|i c}}|d<   n|	rt7        d|	z        |xs tA        j                   dd       }|s	 dd l!}d}|dk(  rddl$m%}  || fd|i|S |dv rdd l$m&}  || fd|i|S |tO        d!      tQ        d"| d#      c c}}w c c}}w # t        $ r |j                  j                   }Y w xY wc c}}w c c}}w c c}}w c c}}w c c}}w c c}}w c c}}w c c}}w c c}}w c c}}w c c}}w # tD        $ r 	 dd l#}d}n# tD        $ r Y nw xY wY w xY w)$Ncolorr   )diagnosticsorder>   	order-ageorder-freedorder-memorypressureorder-memorydecreasesorder-memoryincreasesagecpathfreedr   criticalmemorypressurememorydecreasesmemoryincreasesT)return_statscmapc                     t        |          S rs   rM   )r`   valuess    r/   labelzvisualize_dsk.<locals>.label1  s    vay>!r.   r   r   r   r   r   r   ->   r   r   zorder-c                D    t        |          dz   t        |          z   S )Nr   r   )r`   or   s    r/   r   zvisualize_dsk.<locals>.labelQ  s"    qt9s?S^;;r.      )bytes)r   r   function_attributesdata_attributeszUnknown value color=%szvisualization.enginegraphviz	cytoscape)	dot_graphre   )r   ipycytoscape)cytoscape_graphzINo visualization engine detected, please install graphviz or ipycytoscapezVisualization engine z not recognized))r   
dask.orderr   r   matplotlib.pyplotpyplotr   rE   rI   nextiterr   intpopKeyErrorcmplasmarM   r^   endswithr   num_dependencies_freednum_data_when_runnum_data_when_releasedmaxr_   critical_pathNotImplementedError
startswith	_colorizerL   r   r   r   r,   r   dask.dotr   r   RuntimeError
ValueError)r   re   rk   rg   r   r   r   limitri   r   r   r   plto_statsr   r   r   r   data_valuesinfokeyr   colorsdata_colorsr   r   r   r   r   s        `                      @r/   r   r      sQ    JJwE-   	(9Cd3G+2==?;?41aAJJ?;AT!((*-.4Cd3GG+,7795941aAJJ95A	!::f%D dC +3664(D	" GsA&q)D~~e$7;zz|D|83#sww,|D(JN**,W,hc3#s999,W 01EIZZ\R\c#s444\RDHJJLDPSC333L    12 %)JJL$0S Q : :S=R=R RSS$0  12 %)JJL$0S Q 5 58R8R RSS$0 S!"%)>>AHQXS##s000Q)%00)< F>C01F 
&1 ys3QZt(DEFGG& 	 
  K #LLN*DAq 9U3sDV4,H#IJKK*   <B<<>)
;I41aAU1X..>)
$% BMARARAT$UATAQ!_AT$U !	!":U"BCC ?vzz"8$?F
	F &:x:6::	0	0,s@X@@@	W
 	
 0HIIO <
 6  	!66==D	! EWR

 R

)
 %V  	#$ 	s   S2SS S7	S=
T8T	7.T.T*T#8T!68T'T-4T38T9 S43S49	UU
	U
	UUUUU)rk   rg   r}   c                
   t        |d| i\  }}|s|S t        ||      }t        j                  |      r;	 ddlm} 	  |       }	|	j                  |k(  r |	j                  |fd|i|}
 ||
      S t        ||fi |}g g }}|D ]\  }t        t        |j                                     }|j                         \  }}|j                  |       |j!                  |||f       ^ t#               5   |||fi |}
ddd       t%        t'        |
            }|D cg c]!  \  }}} ||D ci c]  }|||   
 c}g| # }}}}} ||      S # t        $ r Y w xY w# t        $ r Y w xY w# 1 sw Y   vxY wc c}w c c}}}}w )aQ
  Persist multiple Dask collections into memory

    This turns lazy Dask collections into Dask collections with the same
    metadata, but now with their results fully computed or actively computing
    in the background.

    For example a lazy dask.array built up from many lazy calls will now be a
    dask.array of the same shape, dtype, chunks, etc., but now with all of
    those previously lazy tasks either computed in memory as many small :class:`numpy.array`
    (in the single-machine case) or asynchronously running in the
    background on a cluster (in the distributed case).

    This function operates differently if a ``dask.distributed.Client`` exists
    and is connected to a distributed scheduler.  In this case this function
    will return as soon as the task graph has been submitted to the cluster,
    but before the computations have completed.  Computations will continue
    asynchronously in the background.  When using this function with the single
    machine scheduler it blocks until the computations have finished.

    When using Dask on a single machine you should ensure that the dataset fits
    entirely within memory.

    Examples
    --------
    >>> df = dd.read_csv('/path/to/*.csv')  # doctest: +SKIP
    >>> df = df[df.name == 'Alice']  # doctest: +SKIP
    >>> df['in-debt'] = df.balance < 0  # doctest: +SKIP
    >>> df = df.persist()  # triggers computation  # doctest: +SKIP

    >>> df.value().min()  # future computations are now fast  # doctest: +SKIP
    -10
    >>> df.value().max()  # doctest: +SKIP
    100

    >>> from dask import persist  # use persist function on multiple collections
    >>> a, b = persist(a, b)  # doctest: +SKIP

    Parameters
    ----------
    *args: Dask collections
    scheduler : string, optional
        Which scheduler to use like "threads", "synchronous" or "processes".
        If not provided, the default is to check the global settings first,
        and then fall back to the collection defaults.
    traverse : bool, optional
        By default dask traverses builtin python collections looking for dask
        objects passed to ``persist``. For large collections this can be
        expensive. If none of the arguments contain any dask objects, set
        ``traverse=False`` to avoid doing this traversal.
    optimize_graph : bool, optional
        If True [default], the graph is optimized before computation.
        Otherwise the graph is run as is. This can be useful for debugging.
    **kwargs
        Extra keywords to forward to the scheduler function.

    Returns
    -------
    New dask collections backed by in-memory data
    rk   )r}   r   r   )default_clientrg   N)r   r   inspectismethoddistributed.clientr  r   r6   r  r,   r   rJ   r   r   r   extendr   r"   rP   r   )rk   rg   r}   r   ri   r   r   r   r  clientr   r   r   r   r   a_keysrebuildstatedr   ksr   r   results2s                           r/   r6   r6     s   x -dFXFKykJH!	+9	+') ::),fnn#4BFLG "'?*
[.
CF
CCR,Dgaoo/01//1FWfe45	  
	3// 
 	Sw A=IJ\BB'Bq1ad7B',!,\HJ(-    		, 
	 (JsF   E E ,E,E=
*E87
E=
	EE	E)(E),E58E=
c                      dd  t         fdt               D              }t        t        |            dd j	                         }ddt        |      z
  z  |z   }d|z   S )zConvert (r, g, b) triple to "#RRGGBB" string

    For use with ``visualize(color=...)``

    Examples
    --------
    >>> _colorize((255, 255, 255))
    '#FFFFFF'
    >>> _colorize((0, 32, 128))
    '#002080'
    N   c              3  R   K   | ]  \  }}|d t              |z
  dz
  z  z     yw)   r   N)r   )r   r   r   ts      r/   r   z_colorize.<locals>.<genexpr>  s,     ALDAqAA
Q''Ls   $'   0   #)sum	enumerater   r   upperr   )r%  r   hs   `  r/   r  r    s`     	
"1AAIaLAAACFABAq3q6zQA7Nr.   )syncsynchronouszsingle-threadedzdict[str, SchedulerGetCallable]named_schedulers)threaded)threads	threading)multiprocessing)	processesr4  a  
The get= keyword has been removed.

Please use the scheduler= keyword instead with the name of
the desired scheduler like 'threads' or 'processes'

    x.compute(scheduler='single-threaded')
    x.compute(scheduler='threads')
    x.compute(scheduler='processes')

or with a function that takes the graph and keys

    x.compute(scheduler=my_scheduler_function)

or with a Dask client

    x.compute(scheduler=client)
c                j     rt        t              |t        |      r|S dt        |      j                  v rt        |d      r|j                  S t        |t              r|j                         }d}t               r8t        J t        t              5  t        j                  d       d}ddd       |t        v r |rt!        j"                  d       t        |   S |dv r-|st%        d	| d
      t&        J t'               j                  S t        ddj)                  t+        t                    z        t        |t,              ret/        |dd      }|t1        j                  dt2              }t        |t4              r|dkD  sJ t7        t8        j:                  |j<                  |      S t        dt?        |      z        t1        j                  dd      r tA        t1        j                  dd            S t1        j                  dd      rt        t              	 ddl!m"}  |       j                  S # 1 sw Y   xY w# tF        t        f$ r Y nw xY w||jH                  S |r|D cg c]  }||	 nc c}w }}|r0|d   jH                   tK         fd|D              st        d       S y)a{  Get scheduler function

    There are various ways to specify the scheduler to use:

    1.  Passing in scheduler= parameters
    2.  Passing these into global configuration
    3.  Using a dask.distributed default Client
    4.  Using defaults of a dask collection

    This function centralizes the logic to determine the right scheduler to use
    from those many options
    Nr$   r   FT)allow_globalzkRunning on a single-machine scheduler when a distributed client is active might lead to unexpected results.)zdask.distributedr(   z
Requested z  scheduler but no Client active.z!Expected one of [distributed, %s]z, _max_workersnum_workersr   zUnexpected scheduler: %sr}   )r}   r%   c              3  <   K   | ]  }|j                   k(    y wrs   )__dask_scheduler__)r   cr   s     r/   r   z get_scheduler.<locals>.<genexpr>  s     D11''3.s   zCompute called on multiple collections with differing default schedulers. Please specify a scheduler=` parameter explicitly in compute or globally with `dask.config.set`.)&rO   get_err_msgrN   r\   rx   r]   r   rI   rM   lowerr0   r)   r
   r  currentr0  warningswarnr
  r+   joinsortedr   r^   r   r   r   r   r   	get_asyncsubmitreprr   r(   r&   r,   r;  all)r   r}   r   r~   client_availabler9  r&   r<  s   `       r/   r   r   /  s    $$Ii111gi6O== 	3'!)I$%')555j)&..D.A'+$ * ,,#MMF (	22AA'&$YK/OP  /:::.0444 7ii'7 89:  	8, ")^TBK"$jj	Bk84qHH5??I,<,<kJJ7$y/IJJ zz+t$vzz+t'DEEzz%%%*|Y *)Z $  %%%"-?+Qq+??!n//DDD3  
s*   H8!I 8III.I;6I;c                T    	 ddl m}  || ||      S # t        t        f$ r | cY S w xY w)zWait until computation has finished

    This is a compatibility alias for ``dask.distributed.wait``.
    If it is applied onto Dask collections without Dask Futures or if Dask
    distributed is not installed then it is a no-op
    r   )rq   )timeoutreturn_when)r(   rq   r,   r  )r`   rJ  rK  rq   s       r/   rq   rq     s2    $AwK@@$ s    ''c                    t        |       st        dt        |              t        | j	                               D ch c]  }t        |       c}S c c}w )a=  Infer the collection names from the dask keys, under the assumption that all keys
    are either tuples with matching first element, and that element is a string, or
    there is exactly one key and it is a string.

    Examples
    --------
    >>> a.__dask_keys__()  # doctest: +SKIP
    ["foo", "bar"]
    >>> get_collection_names(a)  # doctest: +SKIP
    {"foo", "bar"}
    >>> b.__dask_keys__()  # doctest: +SKIP
    [[("foo-123", 0, 0), ("foo-123", 0, 1)], [("foo-123", 1, 0), ("foo-123", 1, 1)]]
    >>> get_collection_names(b)  # doctest: +SKIP
    {"foo-123"}
    zExpected Dask collection; got )r4   rO   r\   r   r   r<   )
collectionr   s     r/   r;   r;     sS      j)8j9I8JKLL*1*2J2J2L*MN*MQa *MNNNs   Ac                    t        | t              r| rt        | d   t              r| d   S t        | t              r| S t        d|       )a  Given a dask collection's key, extract the collection name.

    Parameters
    ----------
    key: string or tuple
        Dask collection's key, which must be either a single string or a tuple whose
        first element is a string (commonly referred to as a collection's 'name'),

    Examples
    --------
    >>> get_name_from_key("foo")
    'foo'
    >>> get_name_from_key(("foo-123", 1, 2))
    'foo-123'
    r   /Expected str or a tuple starting with str; got )rI   rL   rM   rO   )r  s    r/   r<   r<     sH      #u#*SVS*A1v#s

EcWM
NNr.   	KeyOrStrTc                    t        | t              r4| r2t        | d   t              r|j                  | d   | d         f| dd z   S t        | t              r|j                  | |       S t	        d|       )a  Given a dask collection's key, replace the collection name with a new one.

    Parameters
    ----------
    key: string or tuple
        Dask collection's key, which must be either a single string or a tuple whose
        first element is a string (commonly referred to as a collection's 'name'),
    rename:
        Mapping of zero or more names from : to. Extraneous names will be ignored.
        Names not found in this mapping won't be replaced.

    Examples
    --------
    >>> replace_name_in_key("foo", {})
    'foo'
    >>> replace_name_in_key("foo", {"foo": "bar"})
    'bar'
    >>> replace_name_in_key(("foo-123", 1, 2), {"foo-123": "bar-456"})
    ('bar-456', 1, 2)
    r   r   NrO  )rI   rL   rM   r   rO   )r  renames     r/   r=   r=     sr    * #u#*SVS*A

3q63q6*,s12w66#szz#s##
EcWM
NNr.   c                    t        | t              r+| r)t        | d   t              rt        | d   |      f| dd z   S t        | t              rt	        |       }|dz   t        | |      z   S t        d|       )a'  Clone a key from a Dask collection, producing a new key with the same prefix and
    indices and a token which is a deterministic function of the previous key and seed.

    Examples
    --------
    >>> clone_key("x", 123)  # doctest: +SKIP
    'x-c4fb64ccca807af85082413d7ef01721'
    >>> clone_key("inc-cbb1eca3bafafbb3e8b2419c4eebb387", 123)  # doctest: +SKIP
    'inc-bc629c23014a4472e18b575fdaf29ee7'
    >>> clone_key(("sum-cbb1eca3bafafbb3e8b2419c4eebb387", 4, 3), 123)  # doctest: +SKIP
    ('sum-c053f3774e09bd0f7de6044dbc40e71d', 4, 3)
    r   r   Nr   rO  )rI   rL   rM   r>   r!   r9   rO   )r  seedprefixs      r/   r>   r>     sx     #u#*SVS*A#a&$')CG33#s3|hsD111
EcWM
NNr.   )returnrQ   )rV  zdict[str, Any])r   r   rV  zIterator[None])NN)Tr-   )r   z7Literal['cytoscape', 'ipycytoscape', 'graphviz'] | None)rw   TFNNNN)NNNN)NALL_COMPLETED)rV  zset[str])r  r   rV  rM   )r  rP  rR  zMapping[str, str]rV  rP  )r  rP  rT  r   rV  rP  )a
__future__r   r   r  r   r@  r   r   collections.abcr   r   r   concurrent.futuresr   
contextlibr	   r
   contextvarsr   	functoolsr   numbersr   r   operatorr   typingr   r   r   tlzr   r   daskr   r   dask._compatibilityr   	dask.corer   r   r   r   dask.systemr   dask.typingr   r   
dask.utilsr   r   r    r!   r"   r)   r+   r'   r0   __all__dask.tokenizer?   r:   r9   rA   __annotations__r3   r2   r4   r1   r   r   r   r   r   r   r7   r5   r8   r   r6   r  get_syncr0  r1  updater4  dask_multiprocessingstripr=  r   rq   r;   r<   rM   rP  r=   r>   r-   r.   r/   <module>ro     s0   "     # 7 7 ' / "  $  ( (   *  '  ! 1     "$ G F2<43/ 
$ m" m"`(*VK K\*:@$ (, S l " 3 n 4@JJ FJd DdR 
FJ
HJ DHJV ! `F( NN>>~~5 1  ||!	
 =-11377	
" 
EG# ([|O*O. Kc*	O8Or.   