
    &`i[              
       P   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	m
Z
mZmZ d dlZd dlmZ d dlmZmZ  ed          Z ed          Ze	 d#d
ee         dededdfd            Ze	 d#dedededdfd            Ze	 d$dee
e                  deddfd            Ze	 d%ded         ddfd            Ze G d de	e                               Ze G d de	e                               Ze G d de                      Zd Z G d d e           Z! G d! d"e          Z"dS )&    N)contextmanager)AnyCallableGenericIterableListTypeVar)
Deprecated)MetricsContextSharedMetricsTU   Fitems
num_shardsrepeatreturnParallelIterator[T]c                 H   d t          |          D             }t          |           D ]#\  }}|||z                               |           $d                    | rt	          | d                   j        pdt          |           ||rdnd          }t          |||          S )a:  Create a parallel iterator from an existing set of objects.

    The objects will be divided round-robin among the number of shards.

    Args:
        items: The list of items to iterate over.
        num_shards: The number of worker actors to create.
        repeat: Whether to cycle over the items forever.
    c                     g | ]}g S  r   ).0_s     a/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/util/iter.py
<listcomp>zfrom_items.<locals>.<listcomp>   s    ,,,Qb,,,    zfrom_items[{}, {}, shards={}{}]r   None, repeat=True r   name)range	enumerateappendformattype__name__lenfrom_iterators)r   r   r   shardsiitemr!   s          r   
from_itemsr-      s     -,%
++,,,FU## , ,4q:~%%d++++,33)$uQx..)3VE

!)r	 D &d;;;;r   nzParallelIterator[int]c                     g }| |z  }t          |          D ]>}||z  }||dz
  k    r| }n|dz   |z  }|                    t          ||                     ?d|  d| |rdnd d}t          |||          S )a/  Create a parallel iterator over the range 0..n.

    The range will be partitioned sequentially among the number of shards.

    Args:
        n: The max end of the range of numbers.
        num_shards: The number of worker actors to create.
        repeat: Whether to cycle over the range forever.
       zfrom_range[z	, shards=r   r   ]r    )r"   r$   r)   )	r.   r   r   
generators
shard_sizer+   startendr!   s	            r   
from_ranger6   *   s     JjJ: - -J
QCCq5J&C%s++,,,,VaVV*VV2S//QSVVV 	    r   r2   c                     t          j        t                    fd| D             }|s'd                    t	          |           rdnd          }t          ||          S )a*  Create a parallel iterator from a list of iterables.
    An iterable can be a conatiner (list, str, tuple, set, etc.),
    a generator, or a custom class that implements __iter__ or __getitem__.

    An actor will be created for each iterable.

    Examples:
        >>> # Create using a list of generators.
        >>> from_iterators([range(100), range(100)])

        >>> # Certain generators are not serializable.
        >>> from_iterators([(x for x in range(100))])
        ... TypeError: can't pickle generator objects

        >>> # So use lambda functions instead.
        >>> # Lambda functions are serializable.
        >>> from_iterators([lambda: (x for x in range(100))])

    Args:
        generators: A list of Python iterables or lambda
            functions that produce an iterable when called. We allow lambda
            functions since certain generators might not be serializable,
            but a lambda that returns it can be.
        repeat: Whether to cycle over the iterators forever.
        name: Optional name to give the iterator.
    c                 <    g | ]}                     |          S r   remote)r   gr   
worker_clss     r   r   z"from_iterators.<locals>.<listcomp>i   s)    ???qj6**???r   zfrom_iterators[shards={}{}]r   r   r!   )rayr:   ParallelIteratorWorkerr%   r(   from_actors)r2   r   r!   actorsr<   s    `  @r   r)   r)   J   sx    < 233J?????J???F 
,33
OO>__B
 
 vD))))r   rA   ray.actor.ActorHandlec                 n    |sdt          |            d}t          t          | g           g|g           S )a  Create a parallel iterator from an existing set of actors.

    Each actor must subclass the ParallelIteratorWorker interface.

    Args:
        actors: List of actors that each implement
            ParallelIteratorWorker.
        name: Optional name to give the iterator.
    zfrom_actors[shards=r1   parent_iterators)r(   ParallelIterator	_ActorSet)rA   r!   s     r   r@   r@   q   sD      43S[[333Yvr223TBOOOOr   c            	          e Zd ZdZded         deded         fdZd Zd	 Zd
 Z	d Z
deee         gee         f         ddfdZ	 d3deegef         ddfdZdeegef         ddfdZdeddfdZd4dZdeegee         f         ddfdZ	 d5dededdfdZ	 d6ded eddfd!Zd7d#Zd8d%Zd9d7d&Zdedee         fd'Zd:defd)Zd;d+Zd,ee         ddfd-Zdefd.Z ded"         fd/Z!	 d9d0ed ed1edd"fd2Z"dS )<rF   a0  A parallel iterator over a set of remote actors.

    This can be used to iterate over a fixed set of task results
    (like an actor pool), or a stream of data (e.g., a fixed range of numbers,
    an infinite stream of RLlib rollout results).

    This class is **serializable** and can be passed to other remote
    tasks and actors. However, each shard should be read from at most one
    process at a time.

    Examples:
        >>> # Applying a function over items in parallel.
        >>> it = ray.util.iter.from_items([1, 2, 3], num_shards=2)
        ... <__main__.ParallelIterator object>
        >>> it = it.for_each(lambda x: x * 2).gather_sync()
        ... <__main__.LocalIterator object>
        >>> print(list(it))
        ... [2, 4, 6]

        >>> # Creating from generators.
        >>> it = ray.util.iter.from_iterators([range(3), range(3)])
        ... <__main__.ParallelIterator object>
        >>> print(list(it.gather_sync()))
        ... [0, 0, 1, 1, 2, 2]

        >>> # Accessing the individual shards of an iterator.
        >>> it = ray.util.iter.from_range(10, num_shards=2)
        ... <__main__.ParallelIterator object>
        >>> it0 = it.get_shard(0)
        ... <__main__.LocalIterator object>
        >>> print(list(it0))
        ... [0, 1, 2, 3, 4]
        >>> it1 = it.get_shard(1)
        ... <__main__.LocalIterator object>
        >>> print(list(it1))
        ... [5, 6, 7, 8, 9]

        >>> # Gathering results from actors synchronously in parallel.
        >>> it = ray.util.iter.from_actors(workers)
        ... <__main__.ParallelIterator object>
        >>> it = it.batch_across_shards()
        ... <__main__.LocalIterator object>
        >>> print(next(it))
        ... [worker_1_result_1, worker_2_result_1]
        >>> print(next(it))
        ... [worker_1_result_2, worker_2_result_2]
    
actor_setsrG   r!   rE   zParallelIterator[Any]c                 0    || _         || _        || _        dS )z:Create a parallel iterator (this is an internal function).N)rI   r!   rE   )selfrI   r!   rE   s       r   __init__zParallelIterator.__init__   s"     %	 !1r   c                      t          d          )NzeYou must use it.gather_sync() or it.gather_async() to iterate over the results of a ParallelIterator.)	TypeErrorrK   s    r   __iter__zParallelIterator.__iter__   s    >
 
 	
r   c                      t          |           S NreprrO   s    r   __str__zParallelIterator.__str__       Dzzr   c                     d| j          dS )NzParallelIterator[r1   r=   rO   s    r   __repr__zParallelIterator.__repr__   s    /49////r   c                 d    t          fd| j        D             | j        |z   | j                  S )z/Helper function to create new Parallel Iteratorc                 :    g | ]}|                               S r   )with_transform)r   alocal_it_fns     r   r   z4ParallelIterator._with_transform.<locals>.<listcomp>   s'    DDDqQk**DDDr   )r!   rE   )rF   rI   r!   rE   )rK   r]   r!   s    ` r   _with_transformz ParallelIterator._with_transform   sC    DDDDDODDDT!!2
 
 
 	
r   fnr   zParallelIterator[U]c                 6    |                      fdd          S )a\  Remotely transform the iterator.

        This is advanced version of for_each that allows you to apply arbitrary
        generator transformations over the iterator. Prefer to use .for_each()
        when possible for simplicity.

        Args:
            fn: function to use to transform the iterator. The function
                should pass through instances of _NextValueNotReady that appear
                in its input iterator. Note that this function is only called
                **once** over the input iterator.

        Returns:
            ParallelIterator[U]: a parallel iterator.

        Examples:
            >>> def f(it):
            ...     for x in it:
            ...         if x % 2 == 0:
            ...            yield x
            >>> from_range(10, 1).transform(f).gather_sync().take(5)
            ... [0, 2, 4, 6, 8]
        c                 .    |                                S rR   )	transformlocal_itr_   s    r   <lambda>z,ParallelIterator.transform.<locals>.<lambda>   s    X//33 r   .transform()r^   rK   r_   s    `r   rb   zParallelIterator.transform   s+    4 ##3333^
 
 	
r   r0   Nc                 ^    dk    s
J d            |                      fdd          S )a  Remotely apply fn to each item in this iterator.

        If `max_concurrency` == 1 then `fn` will be executed serially by each
        shards

        `max_concurrency` should be used to achieve a high degree of
        parallelism without the overhead of increasing the number of shards
        (which are actor based). If `max_concurrency` is not 1, this function
        provides no semantic guarantees on the output order.
        Results will be returned as soon as they are ready.

        A performance note: When executing concurrently, this function
        maintains its own internal buffer. If `num_async` is `n` and
        max_concur is `k` then the total number of buffered objects could be up
        to `n + k - 1`

        Args:
            fn: function to apply to each item.
            max_concurrency: max number of concurrent calls to fn per
                shard. If 0, then apply all operations concurrently.
            resources: resources that the function requires to execute.
                This has the same default as `ray.remote` and is only used
                when `max_concurrency > 1`.

        Returns:
            ParallelIterator[U]: a parallel iterator whose elements have `fn`
            applied.

        Examples:
            >>> next(from_range(4).for_each(
                        lambda x: x * 2,
                        max_concur=2,
                        resources={"num_cpus": 0.1}).gather_sync()
                )
            ... [0, 2, 4, 8]

        r   z%max_concurrency must be non-negative.c                 2    |                                S rR   )for_each)rd   r_   max_concurrency	resourcess    r   re   z+ParallelIterator.for_each.<locals>.<lambda>   s    X..r?INN r   .for_each()rg   )rK   r_   rl   rm   s    ```r   rk   zParallelIterator.for_each   sO    P !###%L#####NNNNNN
 
 	
r   r   c                 6    |                      fdd          S )a  Remotely filter items from this iterator.

        Args:
            fn: returns False for items to drop from the iterator.

        Examples:
            >>> it = from_items([0, 1, 2]).filter(lambda x: x > 0)
            >>> next(it.gather_sync())
            ... [1, 2]
        c                 .    |                                S rR   )filterrc   s    r   re   z)ParallelIterator.filter.<locals>.<lambda>/  s    X__R5H5H r   	.filter()rg   rh   s    `r   rq   zParallelIterator.filter$  s%     ##$H$H$H$H+VVVr   r.   zParallelIterator[List[T]]c                 >    |                      fdd d          S )zRemotely batch together items in this iterator.

        Args:
            n: Number of items to batch together.

        Examples:
            >>> next(from_range(10, 1).batch(4).gather_sync())
            ... [0, 1, 2, 3]
        c                 .    |                                S rR   )batch)rd   r.   s    r   re   z(ParallelIterator.batch.<locals>.<lambda>;  s    X^^A5F5F r   .batch()rg   rK   r.   s    `r   ru   zParallelIterator.batch1  s.     ##$F$F$F$FRSWWWr   ParallelIterator[T[0]]c                 0    |                      d d          S )zFlatten batches of items into individual items.

        Examples:
            >>> next(from_range(10, 1).batch(4).flatten())
            ... 0
        c                 *    |                                  S rR   )flatten)rd   s    r   re   z*ParallelIterator.flatten.<locals>.<lambda>D  s    X5E5E5G5G r   
.flatten()rg   rO   s    r   r|   zParallelIterator.flatten=  s     ##$G$GVVVr   c                 r    |                      |                                          }| j        dz   |_        |S )z}Transform and then combine items horizontally.

        This is the equivalent of for_each(fn).flatten() (flat map).
        
.combine()rk   r|   r!   rK   r_   its      r   combinezParallelIterator.combineF  s4    
 ]]2&&(()l*	r   shuffle_buffer_sizeseedc           	          |                      fdd                    t                    nd                    S )a  Remotely shuffle items of each shard independently

        Args:
            shuffle_buffer_size: The algorithm fills a buffer with
                shuffle_buffer_size elements and randomly samples elements from
                this buffer, replacing the selected elements with new elements.
                For perfect shuffling, this argument should be greater than or
                equal to the largest iterator size.
            seed: Seed to use for
                randomness. Default value is None.

        Returns:
            A ParallelIterator with a local shuffle applied on the base
            iterator

        Examples:
            >>> it = from_range(10, 1).local_shuffle(shuffle_buffer_size=2)
            >>> it = it.gather_sync()
            >>> next(it)
            0
            >>> next(it)
            2
            >>> next(it)
            3
            >>> next(it)
            1
        c                 0    |                                S rR   )shuffle)rd   r   r   s    r   re   z0ParallelIterator.local_shuffle.<locals>.<lambda>n  s    X--.A4HH r   z/.local_shuffle(shuffle_buffer_size={}, seed={})Nr   )r^   r%   str)rK   r   r   s    ``r   local_shufflezParallelIterator.local_shuffleO  sT    < ##HHHHH=DD#$2BSYYY 
 
 	
r   r   num_partitionsbatch_msc                   	
 g | j         D ]0}|                                                     |j                   1d	fd	fd	| j        d dz   }	fdt                    D             }t          j        t                    

fd|D             }t          t          |g           g|| g          S )
a  Returns a new ParallelIterator instance with num_partitions shards.

        The new iterator contains the same data in this instance except with
        num_partitions shards. The data is split in round-robin fashion for
        the new ParallelIterator.

        Args:
            num_partitions: The number of shards to use for the new
                ParallelIterator
            batch_ms: Batches items for batch_ms milliseconds
                on each shard before retrieving it.
                Increasing batch_ms increases latency but improves throughput.

        Returns:
            A ParallelIterator with num_partitions number of shards and the
            data of this ParallelIterator split round-robin among the new
            number of shards.

        Examples:
            >>> it = from_range(8, 2)
            >>> it = it.repartition(3)
            >>> list(it.get_shard(0))
            [0, 4, 3, 7]
            >>> list(it.get_shard(1))
            [1, 5]
            >>> list(it.get_shard(2))
            [2, 6]
        Nc              3   P  K   i }D ]"}|||j                             | |          <   #|rt          |          }|Ct          j        |t          |          d          \  }}|st          j        |d          \  }}n't          j        |t          |          |          \  }}|D ]e}|                    |          }		 t          j        |          }
|	||	j                             | |          <   |
D ]}|V  V# t          $ r Y bw xY w|t                      V  |d S d S )N)stepr4   r   r   num_returnstimeoutr0   r   )
par_iter_slice_batchr:   listr>   waitr(   popgetStopIteration_NextValueNotReady)r   partition_indexr   futuresr\   pendingreadyr   obj_refactorru   r,   
all_actorsr   s               r   base_iteratorz3ParallelIterator.repartition.<locals>.base_iterator  s     G  
 	 *11+?X 2   
  /w--?"xS\\STUUUHE1  D#&8G#C#C#Cq"xS\\7     HE1  %  G#KK00E # 0 0 "  !6==%3&5)1 >   %* ' 'D"&JJJJ'(    &,.....;  / / / / /s   =D  
DDc                       fdS )Nc                                  S rR   r   )r   r+   r   s   r   re   zBParallelIterator.repartition.<locals>.make_gen_i.<locals>.<lambda>  s    ==;; r   r   )r+   r   r   s   `r   
make_gen_iz0ParallelIterator.repartition.<locals>.make_gen_i  s    ;;;;;;;r   z.repartition[num_partitions=r1   c                 &    g | ]} |          S r   r   )r   sr   s     r   r   z0ParallelIterator.repartition.<locals>.<listcomp>  s!    CCCjjmmCCCr   c                 >    g | ]}                     |d           S )F)r   r9   )r   r;   r<   s     r   r   z0ParallelIterator.repartition.<locals>.<listcomp>  s,    III*##Ae#44IIIr   rD   rR   )rI   init_actorsextendrA   r!   r"   r>   r:   r?   rF   rG   )rK   r   r   	actor_setr!   r2   rA   r   r   r   r<   s    ``    @@@@r   repartitionzParallelIterator.repartitiont  s   B 
 	0 	0I!!###i.////%	/ %	/ %	/ %	/ %	/ %	/ %	/N	< 	< 	< 	< 	< 	< yK.KKKKCCCCU>-B-BCCC
Z 677
IIIIjIII62!6!6 7QUPVWWWWr   LocalIterator[T]c                 f    |                                                                  }|  d|_        |S )a  Returns a local iterable for synchronous iteration.

        New items will be fetched from the shards on-demand as the iterator
        is stepped through.

        This is the equivalent of batch_across_shards().flatten().

        Examples:
            >>> it = from_range(100, 1).gather_sync()
            >>> next(it)
            ... 0
            >>> next(it)
            ... 1
            >>> next(it)
            ... 2
        z.gather_sync())batch_across_shardsr|   r!   )rK   r   s     r   gather_synczParallelIterator.gather_sync  s6    " %%''//11)))	r   LocalIterator[List[T]]c                 V     d fd	}  d}t          |t                      |          S )zIterate over the results of multiple shards in parallel.

        Examples:
            >>> it = from_iterators([range(3), range(3)])
            >>> next(it.batch_across_shards())
            ... [0, 0]
        Nc              3   r  K   g }j         D ]0}|                                 |                    |j                   1d |D             }|r	 t	          j        ||           V  d |D             }| t                      V  n# t          $ r t                      V  Y nt          $ r g }t          t          |          |          D ]R\  }}	 |                    t	          j        |                     .# t          $ r |                    |           Y Ow xY w|r|V  d |D             }Y nw xY w|d S d S )Nc                 @    g | ]}|j                                         S r   par_iter_nextr:   r   r\   s     r   r   zOParallelIterator.batch_across_shards.<locals>.base_iterator.<locals>.<listcomp>  s&    @@@Aq--//@@@r   r   c                 @    g | ]}|j                                         S r   r   r   s     r   r   zOParallelIterator.batch_across_shards.<locals>.base_iterator.<locals>.<listcomp>  &    HHHAq5577HHHr   c                 @    g | ]}|j                                         S r   r   r   s     r   r   zOParallelIterator.batch_across_shards.<locals>.base_iterator.<locals>.<listcomp>  r   r   )rI   r   r   rA   r>   r   r   TimeoutErrorr   zipr   r$   remove)r   activer   r   resultsr\   frK   s          r   r   z;ParallelIterator.batch_across_shards.<locals>.base_iterator  s     F!_ 0 0	%%'''i.////@@@@@G II''7;;;;;;HHHHHG*022222# / / /,.......$ 
I 
I 
I G #DLL' : : - -1-#NN371::6666, - - -"MM!,,,,,- &%HHHHHGGG
I  I I I I Is<   6B D0 -D0'C65D06DD0DD0/D0z.batch_across_shards()r=   rR   )LocalIteratorr   )rK   r   r!   s   `  r   r   z$ParallelIterator.batch_across_shards  sP    	I 	I 	I 	I 	I 	I6 ...]MOO$GGGGr   c                      dk     rt          d          dk     rt          d          dd	 fd	}  d}t          |t                      |          S )
a|  Returns a local iterable for asynchronous iteration.

        New items will be fetched from the shards asynchronously as soon as
        the previous one is computed. Items arrive in non-deterministic order.

        Arguments:
            batch_ms: Batches items for batch_ms milliseconds
                on each shard before retrieving it.
                Increasing batch_ms increases latency but improves throughput.
                If this value is 0, then items are returned immediately.
            num_async: The max number of async requests in flight
                per actor. Increasing this improves the amount of pipeline
                parallelism in the iterator.

        Examples:
            >>> it = from_range(100, 1).gather_async()
            >>> next(it)
            ... 3
            >>> next(it)
            ... 0
            >>> next(it)
            ... 1
        r0   zqueue depth must be positiver   batch time must be positiveNc              3     K   g }j         D ]0}|                                 |                    |j                   1i }t	                    D ]$}|D ]}|||j                                      <    %|rt          |          }| Ct          j	        |t          |          d          \  }}|st          j	        |d          \  }}n't          j	        |t          |          |           \  }}|D ]}|                    |          }		 |	j                                        _        t          j        |          }
|	||	j                                      <   |
D ]}|V  q# t          $ r Y }w xY w| t!                      V  |d S d S )Nr   r   r0   r   )rI   r   r   rA   r"   par_iter_next_batchr:   r   r>   r   r(   r   shared_metricsr   current_actorr   r   )r   r   r   r   r   r\   r   r   r   r   ru   r,   r   
local_iter	num_asyncrK   s               r   r   z4ParallelIterator.gather_async.<locals>.base_iterator)  s     J!_ 4 4	%%'''!!)"23333G9%% H H# H HAFGGA188BBCCH /w--?"xS\\STUUUHE1  D#&8G#C#C#Cq"xS\\7     HE1  % 	 	G#KK00EHM
15577E # 0 0NS 9 @ @ J JK$) ' 'D"&JJJJ'(    &,.....1  / / / / /s   AE%%
E21E2z.gather_async()r=   rR   )
ValueErrorr   r   )rK   r   r   r   r!   r   s   ```  @r   gather_asynczParallelIterator.gather_async  s    2 q==;<<<a<<:;;; 
!	/ !	/ !	/ !	/ !	/ !	/ !	/ !	/ !	/F '''"=-//MMM
r   c                 P    |                                                      |          S z2Return up to the first n items from this iterator.)r   takerx   s     r   r   zParallelIterator.takeP  "    !!&&q)))r      c                 P    |                                                      |          S )1Print up to the first n items from this iterator.)r   showrx   s     r   r   zParallelIterator.showT  r   r   otherc                 "   t          |t                    st          dt          |                     g }|                    | j                   |                    |j                   t          |d|  d| d| j        |j        z             S )z;Return an iterator that is the union of this and the other.z,other must be of type ParallelIterator, got zParallelUnion[, r1   rD   )
isinstancerF   rN   r&   r   rI   rE   )rK   r   rI   s      r   unionzParallelIterator.unionX  s    %!122 	LtE{{LL   
$/***%*+++  -T--U---!2U5KK
 
 
 	
r   shards_to_keepc                    t          | j                  dk    rt          d          t                    dk    rt          d          | j        d         }fdt          |j                  D             }t          |          t                    k    s
J d            t          ||j                  }t          |g|  dt                     d| j        	          S )
zReturn a child iterator that only iterates over given shards.

        It is the user's responsibility to ensure child iterators are operating
        over disjoint sub-sets of this iterator's shards.
        r0   z,select_shards() is not allowed after union()r   z#at least one shard must be selectedc                 "    g | ]\  }}|v 	|S r   r   )r   r+   r\   r   s      r   r   z2ParallelIterator.select_shards.<locals>.<listcomp>t  s.     
 
 
1aqN?R?RA?R?R?Rr   zInvalid actor indexz.select_shards(z total)rD   )	r(   rI   r   r#   rA   rG   
transformsrF   rE   )rK   r   old_actor_set
new_actorsnew_actor_sets    `   r   select_shardszParallelIterator.select_shardsi  s    t!##KLLL~!##BCCC*
 
 
 
%m&:;;
 
 

 :#n"5"55557L555!*m.FGGO@@C$7$7@@@!2
 
 
 	
r   c                 >    t          d | j        D                       S )z9Return the number of worker actors backing this iterator.c              3   >   K   | ]}t          |j                  V  d S rR   )r(   rA   r   s     r   	<genexpr>z.ParallelIterator.num_shards.<locals>.<genexpr>  s*      ::Q3qx==::::::r   )sumrI   rO   s    r   r   zParallelIterator.num_shards  s!    ::$/::::::r   c                 ^      fdt                                                     D             S )zReturn the list of all shards.c                 :    g | ]}                     |          S r   )	get_shard)r   r+   rK   s     r   r   z+ParallelIterator.shards.<locals>.<listcomp>  s%    DDDaq!!DDDr   )r"   r   rO   s   `r   r*   zParallelIterator.shards  s/    DDDD51B1B+C+CDDDDr   shard_indexr   c                   	 dk     rt          d          dk     rt          d          d\  	|}| j        D ]G}|t          |j                  k     r|j        |         |j        	 n|t          |j                  z  }H#t          d||                                           d	fd	}| j        d	| d
z   }t          |t                      |          S )a  Return a local iterator for the given shard.

        The iterator is guaranteed to be serializable and can be passed to
        remote tasks or actors.

        Arguments:
            shard_index: Index of the shard to gather.
            batch_ms: Batches items for batch_ms milliseconds
                before retrieving it.
                Increasing batch_ms increases latency but improves throughput.
                If this value is 0, then items are returned immediately.
            num_async: The max number of requests in flight.
                Increasing this improves the amount of pipeline
                parallelism in the iterator.
        r0   znum async must be positiver   r   )NNNzShard index out of rangec              3   D  K   t          j                    }t          j        j                                                 t                    D ]/}|                    j                                                 0	 	 t          j        |	                                |           }|                    j                                                 |D ]}|V  | t                      V  n,# t          $ r t                      V  Y nt          $ r Y d S w xY w)NTr   )collectionsdequer>   r   par_iter_initr:   r"   r$   r   popleftr   r   r   )	r   queuer   ru   r,   r\   r   r   ts	        r   r   z1ParallelIterator.get_shard.<locals>.base_iterator  sA     %''EGAO**1--...9%% E EQ299(CCDDDDGEMMOOWEEEELL!6!=!=h!G!GHHH % # #"



*022222# / / /,.......$   EEs   A0C5 5D	DDz.shard[r1   r=   rR   )	r   rI   r(   rA   r   r   r!   r   r   )
rK   r   r   r   r+   r   r   r!   r\   r   s
     ``    @@r   r   zParallelIterator.get_shard  s    $ q==9:::a<<:;;;1 	+ 	+I3y'(((($Q'(S)***97dooFWFWXXX	 	 	 	 	 	 	 	 	& y3[3333]MOO$GGGGr   r0   N)r   ry   rR   )r   )r   r   )r   r   )r   r0   r   )r   r   r   r   )#r'   
__module____qualname____doc__r   r   rL   rP   rU   rX   r^   r   r   r   r   rb   rk   boolrq   intru   r|   r   r   r   r   r   r   r   r   r   r   r   r*   r   r   r   r   rF   rF      s       . .`1%1 1 67	1 1 1 1
 
 
  0 0 0
 
 

HQK=(1+56
	
 
 
 
> BF,
 ,
A36",
	,
 ,
 ,
 ,
\W1#t), W1F W W W W
Xs 
X: 
X 
X 
X 
XW W W W(A3Q<0 5J     59#
 #
#&#
.1#
	#
 #
 #
 #
L 45VX VX!VX-0VX	VX VX VX VXp   *%H %H %H %HNF F F F FP*c *d1g * * * ** *c * * * *
 
 
 
"
DI 
:O 
 
 
 
,;C ; ; ; ;E/0 E E E E
 EF6H 6H6H*-6H>A6H	6H 6H 6H 6H 6H 6Hr   rF   c            
       0   e Zd ZdZdZ ej                    Z	 	 	 d,deg e	e
         f         dedeee	gef                  defdZed	efd
            Zd Zed             Zd Zd Zd Zd Zdee	e
         ge	e         f         d	dfdZ	 d-dee
gef         d	dfdZdee
gef         d	dfdZded	dfdZd.dZ d/deded	dfdZ!dee
gee         f         d	dfd Z"d! Z#ded	ee
         fd"Z$d0defd$Z%d	ed         fd%Z&d&dd'd(dd)ed*ee'         d	dfd+Z(dS )1r   aW  An iterator over a single shard of data.

    It implements similar transformations as ParallelIterator[T], but the
    transforms will be applied locally and not remotely in parallel.

    This class is **serializable** and can be passed to other remote
    tasks and actors. However, it should be read from at most one process at
    a time._on_fetch_startNr   r   local_transformsr   c                     t          |t                    sJ || _        d| _        |pg | _        || _        || _        |pd| _        dS )a  Create a local iterator (this is an internal function).

        Args:
            base_iterator: A function that produces the base iterator.
                This is a function so that we can ensure LocalIterator is
                serializable.
            shared_metrics: Existing metrics context or a new
                context. Should be the same for each chained iterator.
            local_transforms: A list of transformation functions to be
                applied on top of the base iterator. When iteration begins, we
                create the base iterator and apply these functions. This lazy
                creation ensures LocalIterator is serializable until you start
                iterating over it.
            timeout: Optional timeout in seconds for this iterator, after
                which _NextValueNotReady will be returned. This avoids
                blocking.
            name: Optional name for this iterator.
        Nunknown)r   r   r   built_iteratorr   r   r   r!   )rK   r   r   r   r   r!   s         r   rL   zLocalIterator.__init__  sV    4 .-88888*" 0 6B,%I			r   r   c                      t          t          j        d          rt          j        j        t	          d          t          j        j        S )zaReturn the current metrics context.

        This can only be called within an iterator function.metricsNz*Cannot access context outside an iterator.)hasattrr   thread_localr   r   r   r   r   get_metricszLocalIterator.get_metrics  sA     2I>>	K)19IJJJ)11r   c                     | j         Et          |                     | j                            }| j        D ]} ||          }|| _         d S d S rR   )r   iterr   r   r   )rK   r   r_   s      r   _build_oncezLocalIterator._build_once   s_    &d((6677B+  RVV"$D	 '&r   c              #   X   K   | j                                         | j        _        d V  d S rR   )r   r   r  r   rO   s    r   _metrics_contextzLocalIterator._metrics_context  s-      $($7$;$;$=$=!r   c                 8    |                                   | j        S rR   )r  r   rO   s    r   rP   zLocalIterator.__iter__  s    ""r   c                 R    |                                   t          | j                  S rR   )r  nextr   rO   s    r   __next__zLocalIterator.__next__  s%    D'(((r   c                      t          |           S rR   rS   rO   s    r   rU   zLocalIterator.__str__  rV   r   c                     d| j          dS )NzLocalIterator[r1   r=   rO   s    r   rX   zLocalIterator.__repr__  s    ,	,,,,r   r_   zLocalIterator[U]c                 j    fd}t          | j        | j        | j        |gz   | j        dz             S )Nc              3   0   K    |           D ]}|V  d S rR   r   )r   r,   r_   s     r   apply_transformz0LocalIterator.transform.<locals>.apply_transform  s3      2  



 r   rf   r=   r   r   r   r   r!   )rK   r_   r  s    ` r   rb   zLocalIterator.transform  sY    	 	 	 	 	 !_$55^+	
 
 
 	
r   r0   c                      dk    r fd}ni fd}t          t          j                  r| fd}|}t           j         j         j        |gz    j        dz             S )Nr0   c              3      K   | D ]o}t          |t                    r|V  	                                 5   |          }d d d            n# 1 swxY w Y   |V  t          |t                    snRpd S rR   )r   r   r  )r   r,   resultr_   rK   s      r   apply_foreachz-LocalIterator.for_each.<locals>.apply_foreach-  s       & &D!$(:;; 
&"



&!%!6!6!8!8 2 2)+D2 2 2 2 2 2 2 2 2 2 2 2 2 2 2"(LLL#-f6H#I#I & %&
 !&& &s   AA	A	c              3     K   g } t          j                  j        di }|j        }| D ]}t          |t                    r|V  rDt          |          k    r1t          j        |          \  }}t          j        |          E d {V  |                     ||                     |r5t          j        |          \  }}t          j        |          E d {V  |3d S d S )Nr   )	r>   r:   optionsr   r   r(   r   r   r$   )	r   curr:   	remote_fnr,   finishedr_   rl   rm   s	         r   r  z-LocalIterator.for_each.<locals>.apply_foreach?  s!     /B/<<)<<"M	 4 4D!$(:;; 4"



* 9s3xx?/J/J,/HSMMMHc'*wx'8'88888888

99T??3333 1$'HSMMMHc"wx000000000  1 1 1 1 1r   c              3     K    |           } d}	 |rB                                 5                                   d d d            n# 1 swxY w Y   d}t          |           }t          |t                    sd}|V  o)NTF)r  r   r  r   r   )r   new_itemr,   r_   rK   	unwrappeds      r   add_wait_hooksz.LocalIterator.for_each.<locals>.add_wait_hooksR  s      Yr]]
   )!2244 1 1..0001 1 1 1 1 1 1 1 1 1 1 1 1 1 1#(88D%d,>?? (#'JJJ
s   A		AArn   r=   )r  r   ON_FETCH_START_HOOK_NAMEr   r   r   r!   )rK   r_   rl   rm   r  r  r  s   ````  @r   rk   zLocalIterator.for_each(  s     a& & & & & & &  	1 1 1 1 1 1 1  2}=>> 	+%I       +M!]O3]*	
 
 
 	
r   r   c                 n      fd}t           j         j         j        |gz    j        dz             S )Nc              3      K   | D ]R}                                 5  t          |t                    s |          r|V  d d d            n# 1 swxY w Y   Sd S rR   )r  r   r   )r   r,   r_   rK   s     r   apply_filterz*LocalIterator.filter.<locals>.apply_filterk  s       # #**,, # #!$(:;; #rr$xx #"


# # # # # # # # # # # # # # ## #s   %AA	A	rr   r=   r  )rK   r_   r#  s   `` r   rq   zLocalIterator.filterj  s^    	# 	# 	# 	# 	# 	# !\N2[(	
 
 
 	
r   r.   r   c           	      r    fd}t          | j        | j        | j        |gz   | j        d dz             S )Nc              3      K   g }| D ]J}t          |t                    r|V  |                    |           t          |          k    r|V  g }K|r|V  d S d S rR   )r   r   r$   r(   )r   ru   r,   r.   s      r   apply_batchz(LocalIterator.batch.<locals>.apply_batchy  s      E # #d$677 #JJJJLL&&&5zzQ# "  r   rv   rw   r=   r  )rK   r.   r&  s    ` r   ru   zLocalIterator.batchx  s`    	 	 	 	 	 ![M1^q^^^+	
 
 
 	
r   LocalIterator[T[0]]c                 d    d }t          | j        | j        | j        |gz   | j        dz             S )Nc              3   Z   K   | D ]%}t          |t                    r|V  |D ]}|V  &d S rR   )r   r   )r   r,   subitems      r   apply_flattenz,LocalIterator.flatten.<locals>.apply_flatten  s\       & &d$677 &JJJJ#' & &%&	& &r   r}   r=   r  )rK   r+  s     r   r|   zLocalIterator.flatten  sM    	& 	& 	& !]O3\)	
 
 
 	
r   r   r   c                     t          j        |          fd}t          | j        | j        | j        |gz   | j        d                    |t          |          nd          z             S )a:  Shuffle items of this iterator

        Args:
            shuffle_buffer_size: The algorithm fills a buffer with
                shuffle_buffer_size elements and randomly samples elements from
                this buffer, replacing the selected elements with new elements.
                For perfect shuffling, this argument should be greater than or
                equal to the largest iterator size.
            seed: Seed to use for
                randomness. Default value is None.

        Returns:
            A new LocalIterator with shuffling applied
        c           	   3     K   g }| D ]}t          |t                    r|V  |                    |           t          |          k    r;|                                        dt          |          dz
                      V  t          |          dk    rP|                                        dt          |          dz
                      V  t          |          dk    Nd S d S )Nr   r0   )r   r   r$   r(   r   randint)r   bufferr,   r   shuffle_randoms      r   apply_shufflez,LocalIterator.shuffle.<locals>.apply_shuffle  s      F U Ud$677 UJJJJMM$'''6{{&999$jj)?)?3v;;QR?)S)STTTTTf++//jj!7!73v;;?!K!KLLLLL f++//////r   z).shuffle(shuffle_buffer_size={}, seed={})Nr   r=   )	randomRandomr   r   r   r   r!   r%   r   )rK   r   r   r1  r0  s    `  @r   r   zLocalIterator.shuffle  s      t,,
	M 
	M 
	M 
	M 
	M 
	M !]O39@@#$2BSYYY 	
 
 
 	
r   c                 r    |                      |                                          }| j        dz   |_        |S )Nr   r   r   s      r   r   zLocalIterator.combine  s2    ]]2&&(()l*	r   c                 T    d }|                      |          }| j        dz   |_        |S )Nc                 r    t                                           }|j        t          d          |j        | fS )Nz'Could not identify source actor of item)r   r  r   r   )r,   r   s     r   zip_with_sourcez<LocalIterator.zip_with_source_actor.<locals>.zip_with_source  s9    #//11G$, !JKKK($..r   z.zip_with_source_actor())rk   r!   )rK   r7  r   s      r   zip_with_source_actorz#LocalIterator.zip_with_source_actor  s8    	/ 	/ 	/ ]]?++)88	r   c                 h    g }| D ],}|                     |           t          |          |k    r n-|S r   )r$   r(   )rK   r.   outr,   s       r   r   zLocalIterator.take  sF     	 	DJJt3xx1}} 
r   r   c                 N    d}| D ]}t          |           |dz  }||k    r dS  dS )r   r   r0   N)print)rK   r.   r+   r,   s       r   r   zLocalIterator.show  sI     	 	D$KKKFAAvv 	 	r   c                 j    |dk     rt          d          g t          |          D ](}                    t          j                               ) fdfd}g }t          |          D ]B}|                    t           ||           j        g  j        d| dz                        C|S )a  Copy this iterator `n` times, duplicating the data.

        The child iterators will be prioritized by how much of the parent
        stream they have consumed. That is, we will not allow children to fall
        behind, since that can cause infinite memory buildup in this operator.

        Returns:
            List[LocalIterator[T]]: child iterators that each have a copy
                of the data of this iterator.
        r   zNumber of copies must be >= 2c                 h    | _         t                    }D ]}|                    |           d S rR   )r   r  r$   )r   r,   qqueuesrK   s      r   	fill_nextz*LocalIterator.duplicate.<locals>.fill_next  s?    "DL::D   r   c                       fd}|S )Nc              3   <  K   	 t                             }t          d D                       }||k     rt                      V  nSt                             dk    r	  |            n# t          $ r Y d S w xY w                                         V  )NTc              3   4   K   | ]}t          |          V  d S rR   )r(   )r   r?  s     r   r   zJLocalIterator.duplicate.<locals>.make_next.<locals>.gen.<locals>.<genexpr>  s(      !9!9Q#a&&!9!9!9!9!9!9r   r   )r(   maxr   r   r   )r   my_lenmax_lenrA  r+   r@  s      r   genz7LocalIterator.duplicate.<locals>.make_next.<locals>.gen   s      2 ^^F!!9!9&!9!9!999G ''0222222vay>>Q..' )	' 2 2 2 2#0 ' ' ' &'$Qi//111112s   $A0 0
A>=A>r   )r+   rH  rA  r@  s   ` r   	make_nextz*LocalIterator.duplicate.<locals>.make_next  s.    2 2 2 2 2 2 2  Jr   z.duplicate[r1   r=   )r   r"   r$   r   r   r   r   r!   )rK   r.   r   rI  	iteratorsr+   rA  r@  s   `     @@r   	duplicatezLocalIterator.duplicate  s    q55<===q 	/ 	/AMM++--....	 	 	 	 	 		 	 	 	 	 	& 	q 	 	AIaLL'%71%7%7%77	      r   F)deterministicround_robin_weightsothersrL  rM  c                   |D ]6}t          |t                    st          dt          |                     7g | gt	          |          z   }t          d |D                       }|rdnd}|r<t          |          t          |          k    rt          d          d |D             }n&|gt          |          z  }dgt          |          z  }t          |          D ];\  }	}                    t          |j	        ||j
        ||	         	                     <t	          t          |                    dfd
	}
t          |
|g d|  dd                    t          t          |                     d          S )a  Return an iterator that is the union of this and the others.

        Args:
            deterministic: If deterministic=True, we alternate between
                reading from one iterator and the others. Otherwise we return
                items from iterators as they become ready.
            round_robin_weights: List of weights to use for round robin
                mode. For example, [2, 1] will cause the iterator to pull twice
                as many items from the first iterator as the second.
                [2, 1, "*"] will cause as many items to be pulled as possible
                from the third iterator without blocking. This overrides the
                deterministic flag.
        z)other must be of type LocalIterator, got c                     g | ]	}|j         
S r   )r   )r   ps     r   r   z'LocalIterator.union.<locals>.<listcomp>9  s    /W/W/WQ0@/W/W/Wr   )parentsNr   zCLength of round robin weights must equal number of iterators total.c                 "    g | ]}|d k    rdndS )*r   Nr   )r   ws     r   r   z'LocalIterator.union.<locals>.<listcomp>B  s$    MMMAQ#XX4MMMr   r0   r   c              3   B  K   	 t                    D ]\  }}|dk    rd}nt          |          }	 t          |          D ]2}t          |          }t	          |t
                    r| |V   n|V  3a# t          $ r                     ||f           Y w xY wsd S )NTrT  d   )r   _randomized_int_castr"   r  r   r   r   r   )r   weightr   max_pullr   r,   r   s         r   build_unionz(LocalIterator.union.<locals>.build_unionR  s      "&v,, 4 4JFB}}#&#7#?#?
4!&x + +A#'88D)$0BCC +#*#6*.JJJ %&*



( 4 4 4vrl333334 E%s   AA55!BBzLocalUnion[r   r1   r=   rR   )r   r   r   r&   r   r   r(   r#   r$   r   r   r   joinmapr   )rK   rL  rM  rN  r   parent_itersr   r   timeoutsr+   r[  r   s              @r   r   zLocalIterator.union  s   (  	Y 	YBb-00 Y !WTRTXX!W!WXXXY vV,&/W/W,/W/W/WXXX'.$$Q 		:&''3|+<+<<< '   NM9LMMMHHy3|#4#44H#$#L(9(9"9|,, 	 	EArMM$"'$QK	      c-v6677	 	 	 	 	 	* EtEEtyyS&1A1A'B'BEEE	
 
 
 	
r   )NNNr   )r   r'  rR   r   ))r'   r   r   r   r   	threadinglocalr  r   r   r   r   r   r   r   rL   staticmethodr   r  r  r   r  rP   r  rU   rX   r   rb   rk   r   rq   ru   r|   r   r   r8  r   r   rK  floatr   r   r   r   r   r     s?          1"9?$$L =A &  &HQK0 & & & x
C89	 &
  &  &  &  &D 	2 	2 	2 	2 \	2% % %   ^# # #) ) )  - - -
Hhqk]HQK%?@ 
EW 
 
 
 
 BF@
 @
A36"@
	@
 @
 @
 @
D
1#t), 
1C 
 
 
 

s 
7 
 
 
 
*
 
 
 
 %
 %
3 %
c %
EW %
 %
 %
 %
N(A3Q<0 5G    
	 	 	c d1g     c    7d#56 7 7 7 7x $+/	M
 M
 M
#M
 M
 "%[	M

 
M
 M
 M
 M
 M
 M
r   r   c                   ^    e Zd ZdZdedefdZd Zd Zde	fdZ
d	e	d
e	fdZd	e	d
e	de	fdZdS )r?   zyWorker actor for a ParallelIterator.

    Actors that are passed to iter.from_actors() must subclass this interface.
    item_generatorr   c                     fd|rfd} |            | _         n             | _         g | _        d| _        d| _        dS )a  Create an iterator worker.

        Subclasses must call this init function.

        Args:
            item_generator: A Python iterable or lambda function
                that produces a generator when called. We allow lambda
                functions since the generator itself might not be serializable,
                but a lambda that returns it can be.
            repeat: Whether to loop over the iterator forever.
        c                  :    t                     r
              S  S rR   )callablere  s   r   make_iteratorz6ParallelIteratorWorker.__init__.<locals>.make_iterator  s'    '' &%~'''%%r   c               3      K   	 t                                 } | u r%t          dd                              z             | D ]}|V  J)NTzJCannot iterate over {0} multiple times.Please pass in the base iterable orzlambda: {0} instead.)r  r   r%   )r   r,   re  rj  s     r   cyclez.ParallelIteratorWorker.__init__.<locals>.cycle  sz      	#mmoo..B^++(D4;;NKKL  
 !# # #"



	#r   N)re  r   rd   next_ith_buffer)rK   re  r   rl  rj  s    `  @r   rL   zParallelIteratorWorker.__init__v  s    	& 	& 	& 	& 	&  	2
# 
# 
# 
# 
# 
# #(%''D"/-//D#r   c                      t           fdt                                }|D ]} ||          }|
J |            t          |           _        dS )z(Implements ParallelIterator worker init.c                     j         S rR   ri  )r   rK   s    r   re   z6ParallelIteratorWorker.par_iter_init.<locals>.<lambda>  s
    4+> r   N)r   r   r  rd   )rK   r   r   r_   s   `   r   r   z$ParallelIteratorWorker.par_iter_init  s^    >>>>PP 	& 	&BBB>>2>>>>Rr   c                 L    | j         
J d            t          | j                   S )z.Implements ParallelIterator worker item fetch.Nmust call par_iter_init())rd   r  rO   s    r   r   z$ParallelIteratorWorker.par_iter_next  s)    }((*E(((DM"""r   r   c                    g }|dk    r)|                     |                                            |S t          j                    d|z  z   }t          j                    |k     rj	 |                     |                                            n*# t          $ r t	          |          dk    rt          Y nw xY wt          j                    |k     j|S )zBatches par_iter_next.r   MbP?)r$   r   timer   r(   )rK   r   ru   t_ends       r   r   z*ParallelIteratorWorker.par_iter_next_batch  s    q==LL++--...L	ux/0ikkE!!T//112222    u::??''D	 ikkE!! s   #'B $B21B2r   r4   c                    | j         
J d            | j        t          j        t                    | _        | j        |         }t          |          dk    r|                    d          S t          |          D ]G}	 t          | j                   }| j        |         	                    |           8# t          $ r Y Dw xY w| j        |         st          | j        |                             d          S )z3Iterates in increments of step starting from start.Nrq  r   )rd   rm  r   defaultdictr   r(   r   r"   r  r$   r   )rK   r   r4   index_bufferjvals         r   par_iter_slicez%ParallelIteratorWorker.par_iter_slice  s   }((*E((('#.#:4#@#@D +E2|q  ##A&&&4[[  t}--C(+2237777$   D '. $###E*..q111s   >4B33
C ?C c                    g }|dk    r+|                     |                     ||                     |S t          j                    d|z  z   }t          j                    |k     rl	 |                     |                     ||                     n*# t          $ r t	          |          dk    rt          Y nw xY wt          j                    |k     l|S )zBatches par_iter_slice.r   rs  )r$   r{  rt  r   r(   )rK   r   r4   r   ru   ru  s         r   r   z+ParallelIteratorWorker.par_iter_slice_batch  s    q==LL,,T599:::L	ux/0ikkE!!T00u==>>>>    u::??''D	 ikkE!! s   %)B $B65B6N)r'   r   r   r   r   r   rL   r   r   r   r   r{  r   r   r   r   r?   r?   o  s         
'$s '$D '$ '$ '$ '$R! ! !# # #
C    "23 2s 2 2 2 2. S C      r   r?   c                 f    t          |           }| |z
  }t          j                    |k     r|dz  }|S )Nr0   )r   r2  )float_valuebase	remainders      r   rX  rX    s8    {Dd"I}""	Kr   c                       e Zd ZdZdS )r   zIndicates that a local iterator has no value currently available.

    This is used internally to implement the union() of multiple blocking
    local generators.N)r'   r   r   r   r   r   r   r   r     s         
 	Dr   r   c                   X    e Zd ZdZded         deedgdf                  fdZd Zd Zd	S )
rG   z<Helper class that represents a set of actors and transforms.rA   rB   r   r   c                 "    || _         || _        d S rR   )rA   r   )rK   rA   r   s      r   rL   z_ActorSet.__init__  s    
 $r   c                 R     t          j         fd j        D                        d S )Nc                 N    g | ]!}|j                             j                  "S r   )r   r:   r   )r   r\   rK   s     r   r   z)_ActorSet.init_actors.<locals>.<listcomp>  s+    NNNQ''88NNNr   )r>   r   rA   rO   s   `r   r   z_ActorSet.init_actors  s0    NNNN$+NNNOOOOOr   c                 >    t          | j        | j        |gz             S rR   )rG   rA   r   rh   s     r   r[   z_ActorSet.with_transform  s    do&<===r   N)	r'   r   r   r   r   r   rL   r   r[   r   r   r   rG   rG     sy        FF%,-% ?"3_"DEF% % % %P P P> > > > >r   rG   )r   F)FNrR   )#r   r2  r`  rt  
contextlibr   typingr   r   r   r   r   r	   r>   ray.util.annotationsr
   ray.util.iter_metricsr   r   r   r   r   r   r-   r6   r)   r@   rF   r   objectr?   rX  	Exceptionr   rG   r   r   r   <module>r     s             % % % % % % B B B B B B B B B B B B B B B B 



 + + + + + + ? ? ? ? ? ? ? ? GCLLGCLL 8=< <7< #<15<< < < <0 05 
)-   > >B#* #*Xa[!#*+/#*#* #* #* #*L 04P P()PP P P P" yH yH yH yH yHwqz yH yH yHx k
 k
 k
 k
 k
GAJ k
 k
 k
\ s s s s sV s s sl  	 	 	 	 	 	 	 	> > > > > > > > > >r   