
    &`i                     p    d dl Z d dlmZmZ  G d d          Z G d de          Z G d de          ZdS )	    N)AnyOptionalc                       e Zd ZdZ	 ddededee         fdZdded	ee         d
efdZdede	d
dfdZ
ded
efdZd Zd ZdS )SegmentTreeam  A Segment Tree data structure.

    https://en.wikipedia.org/wiki/Segment_tree

    Can be used as regular array, but with two important differences:

      a) Setting an item's value is slightly slower. It is O(lg capacity),
         instead of O(1).
      b) Offers efficient `reduce` operation which reduces the tree's values
         over some specified contiguous subsequence of items in the array.
         Operation could be e.g. min/max/sum.

    The data is stored in a list, where the length is 2 * capacity.
    The second half of the list stores the actual values for each index, so if
    capacity=8, values are stored at indices 8 to 15. The first half of the
    array contains the reduced-values of the different (binary divided)
    segments, e.g. (capacity=4):
    0=not used
    1=reduced-value over all elements (array indices 4 to 7).
    2=reduced-value over array indices (4 and 5).
    3=reduced-value over array indices (6 and 7).
    4-7: values of the tree.
    NOTE that the values of the tree are accessed by indices starting at 0, so
    `tree[0]` accesses `internal_array[4]` in the above example.
    Ncapacity	operationneutral_elementc                 "    |dk    r||dz
  z  dk    s
J d            | _         |7|t          j        u rdn&|t          u rt	          d          nt	          d          }| _         fdt          d	|z            D              _        | _        dS )
a>  Initializes a Segment Tree object.

        Args:
            capacity: Total size of the array - must be a power of two.
            operation: Lambda obj, obj -> obj
                The operation for combining elements (eg. sum, max).
                Must be a mathematical group together with the set of
                possible values for array elements.
            neutral_element (Optional[obj]): The neutral element for
                `operation`. Use None for automatically finding a value:
                max: float("-inf"), min: float("inf"), sum: 0.0.
        r      z+Capacity must be positive and a power of 2!Ng        z-infinfc                     g | ]	}j         
S  )r	   ).0_selfs     t/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/rllib/execution/segment_tree.py
<listcomp>z(SegmentTree.__init__.<locals>.<listcomp>=   s    HHHqd*HHH       )	r   operatoraddmaxfloatr	   rangevaluer   )r   r   r   r	   s   `   r   __init__zSegmentTree.__init__    s    " qLLXA6!;;;8 <;; " ,,  ## 6]]]5\\   /HHHHE!h,4G4GHHH
"r   r   startendreturnc                 H   || j         }n|dk     r
|| j         z  }| j        }|| j         z  }|| j         z  }||k     rf|dz  r&|                     || j        |                   }|dz  }|dz  r&|dz  }|                     || j        |                   }|dz  }|dz  }||k     f|S )a  Applies `self.operation` to subsequence of our values.

        Subsequence is contiguous, includes `start` and excludes `end`.

          self.operation(
              arr[start], operation(arr[start+1], operation(... arr[end])))

        Args:
            start: Start index to apply reduction to.
            end (Optional[int]): End index to apply reduction to (excluded).

        Returns:
            any: The result of reducing self.operation over the specified
                range of `self._value` elements.
        Nr   r   r   )r   r	   r   r   )r   r   r   results       r   reducezSegmentTree.reduce@   s      ;-CC1WW4= C %t}* ckk qy 
50ABB

 Qw Aq
3@@ aKEAIC% ckk, r   idxvalc                 (   d|cxk    r| j         k     sn J d| d| j                      || j         z  }|| j        |<   |dz	  }|dk    rId|z  }|                     | j        |         | j        |dz                      | j        |<   |dz	  }|dk    GdS dS )z
        Inserts/overwrites a value in/into the tree.

        Args:
            idx: The index to insert to. Must be in [0, `self.capacity`)
            val: The value to insert.
        r   zidx=z
 capacity=r   r   N)r   r   r   )r   r#   r$   
update_idxs       r   __setitem__zSegmentTree.__setitem__   s     C''''$-''''')N)N)Nt})N)N'''
 	t}
3 QhQhhSJ"nn
:&
:>(B DJsO (C Qhhhhhhr   c                 X    d|cxk    r| j         k     sn J | j        || j         z            S )Nr   )r   r   )r   r#   s     r   __getitem__zSegmentTree.__getitem__   s=    C''''$-''''''z#-..r   c                     | j         S N)r   )r   s    r   	get_statezSegmentTree.get_state   s
    zr   c                 N    t          |          | j        dz  k    sJ || _        d S )Nr   )lenr   r   )r   states     r   	set_statezSegmentTree.set_state   s+    5zzT]Q.....


r   r+   r   N)__name__
__module____qualname____doc__intr   r   r   r"   r   r'   r)   r,   r0   r   r   r   r   r      s         6 OS# ##(+#>Fsm# # # #@D DC D(3- D3 D D D DLs  4    4/s /s / / / /      r   r   c                   Z     e Zd ZdZdef fdZddedee         defd	Zd
e	defdZ
 xZS )SumSegmentTreez:A SegmentTree with the reduction `operation`=operator.add.r   c                 p    t          t          |                               |t          j                   d S N)r   r   )superr8   r   r   r   r   r   	__class__s     r   r   zSumSegmentTree.__init__   s.    nd##,,h(,,WWWWWr   r   Nr   r   r   c                 .    |                      ||          S )z/Returns the sum over a sub-segment of the tree.r"   r   r   r   s      r   sumzSumSegmentTree.sum       {{5#&&&r   	prefixsumc                 0   d|cxk    r|                                  dz   k    sn J d}|| j        |         k    r| j        |         dz
  }|| j        k     r9d|z  }| j        |         |k    r|}n|| j        |         z  }|dz   }|| j        k     9|| j        z
  S )zFinds highest i, for which: sum(arr[0]+..+arr[i - i]) <= prefixsum.

        Args:
            prefixsum: `prefixsum` upper bound in above constraint.

        Returns:
            int: Largest possible index (i) satisfying above constraint.
        r   gh㈵>r   r   )rA   r   r   )r   rC   r#   r&   s       r   find_prefixsum_idxz!SumSegmentTree.find_prefixsum_idx   s     I2222d!2222222 
3''
3$.I DM!!SJz*%	11 TZ
33	 1n DM!! T]""r   r1   )r2   r3   r4   r5   r6   r   r   r   rA   r   rE   __classcell__r=   s   @r   r8   r8      s        DDX X X X X X X' ' 'x} ' ' ' ' '#E #c # # # # # # # #r   r8   c                   F     e Zd Zdef fdZd	dedee         defdZ xZS )
MinSegmentTreer   c                 f    t          t          |                               |t                     d S r:   )r;   rI   r   minr<   s     r   r   zMinSegmentTree.__init__   s,    nd##,,h#,NNNNNr   r   Nr   r   r   c                 .    |                      ||          S )z'Returns min(arr[start], ...,  arr[end])r?   r@   s      r   rK   zMinSegmentTree.min   rB   r   r1   )	r2   r3   r4   r6   r   r   r   rK   rF   rG   s   @r   rI   rI      s}        O O O O O O O' ' 'x} ' ' ' ' ' ' ' ' 'r   rI   )r   typingr   r   r   r8   rI   r   r   r   <module>rN      s                    d d d d d d d dN$# $# $# $# $#[ $# $# $#N' ' ' ' '[ ' ' ' ' 'r   