
    &`i^)                         d dl Z d dlZd dlmZmZ d dlmZ d dlmZm	Z	m
Z
mZmZ d dlmZmZ d dlmZ e G d de	                      ZdS )
    N)ABCMetaabstractmethod)deque)AnyDictListOptionalUnion)OverrideToImplementCustomLogic5OverrideToImplementCustomLogic_CallToSuperRecommended)DeveloperAPIc                      e Zd ZU dZdZeed<   	 	 d+dedefdZe	d	efd
            Z
eded	dfd            Zed	efd            Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd Zd,dZd-dZedeee f         d	d fd            Z!e"	 d.de#eee f                  d	d fd            Z$e"d	eee f         fd            Z%e"deee f         d	dfd             Z&e"e'd/d	eee f         fd!                        Z(ed	efd"            Z)ed#e*d          d	dfd$            Z+ed%e d	dfd&            Z,e	 d0d'ed(ed	e-e e*e          f         fd)            Z.ed1d'ed	e-e d f         fd*            Z/dS )2	StatsBasea  A base class for Stats.

    Stats are meant to be used to log values to and then aggregate them in a tree.

    Therefore, we log to stats in two different ways:
    - On a leaf component, we log values directly by pushing.
    - On a non-leaf component, we only aggregate incoming values.

    Additionally, we pay special respect to Stats that live at the root of the tree.
    These may have a different behaviour (example: a lifetime sum).

    Note the tight coupling between StatsBase and MetricsLogger.
    Nstats_cls_identifierFTis_rootis_leafc                 n    || _         || _        i | _        | j        sd| _        | j        
J d            dS )a  Initializes a StatsBase object.

        Args:
            is_root: If True, the Stats object is a root stats object.
            is_leaf: If True, the Stats object is a leaf stats object.

        Note: A stats object can be both root and leaf at the same time.
        Note: A stats object can also be neither root nor leaf ("intermediate" stats that only aggregate from other stats but are not at the root).
        Nz0stats_cls_identifier must be set in the subclass)r   r   _start_timeslatest_mergedr   )selfr   r   s      v/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/rllib/utils/metrics/stats/base.py__init__zStatsBase.__init__"   sR       | 	=8<D %11= 21111    returnc                     dS )zReturns True if the Stats object has throughput tracking enabled.

        Some Stats classes may have throughput tracking enabled, such as SumStats.
        F r   s    r   has_throughputszStatsBase.has_throughputs>   s	     ur   timec                 2    | j         rt          d          dS )a   Sets the reference time for this Stats object.

        This is important because the component that tracks the time
        between reduce cycles is not Stats, but MetricsLogger.

        Args:
            time: The time to establish as the reference time for this Stats object.
        z`initialize_throughput_reference_time must be overridden for stats objects that have throughputs.N)r   
ValueError)r   r   s     r   $initialize_throughput_reference_timez.StatsBase.initialize_throughput_reference_timeF   s.      	r  	 	r   c                     dS )z/Returns the length of the internal values list.Nr   r   s    r   __len__zStatsBase.__len__U   s	     	r   c                     |                      d          }t          |t          t          t          f          rt          d|  d          t          |          S )NTcompileCan not convert z
 to float.)peek
isinstancelisttupler   r!   floatr   values     r   	__float__zStatsBase.__float__Z   sU    		$	''edE5122 	B@@@@AAAU||r   c                     |                      d          }t          |t          t          t          f          rt          d|  d          t          |          S )NTr&   r(   z to int.)r)   r*   r+   r,   r   r!   intr.   s     r   __int__zStatsBase.__int__`   sU    		$	''edE5122 	@>>>>???5zzr   c                 B    t          |           t          |          k    S Nr-   r   others     r   __eq__zStatsBase.__eq__f       T{{eEll**r   c                 B    t          |           t          |          k    S r5   r6   r7   s     r   __le__zStatsBase.__le__i   r:   r   c                 B    t          |           t          |          k    S r5   r6   r7   s     r   __ge__zStatsBase.__ge__l   r:   r   c                 B    t          |           t          |          k     S r5   r6   r7   s     r   __lt__zStatsBase.__lt__o       T{{U5\\))r   c                 B    t          |           t          |          k    S r5   r6   r7   s     r   __gt__zStatsBase.__gt__r   rA   r   c                 @    t          |           t          |          z   S r5   r6   r7   s     r   __add__zStatsBase.__add__u       T{{U5\\))r   c                 @    t          |           t          |          z
  S r5   r6   r7   s     r   __sub__zStatsBase.__sub__x   rF   r   c                 @    t          |           t          |          z  S r5   r6   r7   s     r   __mul__zStatsBase.__mul__{   rF   r   c                 &    t          |           | S r5   r6   )r   fmts     r   
__format__zStatsBase.__format__~   s    ++s%%%r   c                 b    t          j                    }t          j                    | j        |<   | S )zCalled when entering a context (with which users can measure a time delta).

        Returns:
            This stats instance.
        )	threading	get_identr   perf_counterr   )r   	thread_ids     r   	__enter__zStatsBase.__enter__   s-     '))	'+'8':':)$r   c                     t          j                    }| j        |         J t          j                    | j        |         z
  }|                     |           | j        |= dS )zCalled when exiting a context (with which users can measure a time delta).

        This pushes the time delta since __enter__ to this Stats object.
        N)rO   rP   r   r   rQ   push)r   exc_type	exc_valuetbrR   time_delta_ss         r   __exit__zStatsBase.__exit__   sd    
 '))	 +777(**T->y-II		,i(((r   statec                 l    |                      |          } | di |}|                    |           |S )a  Creates a stats object from a state dictionary.

        Any implementation of this should call this base classe's
        `stats_object.set_state()` to set the state of the stats object.

        Args:
            state: The state to set after instantiation.
        )r[   r   )_get_init_args	set_state)clsr[   	init_argsstatss       r   
from_statezStatsBase.from_state   sF     &&U&33	  i  r   init_overridesc                     | j                             |           }|r|                    |            | j         di |}|S )a4  Returns a new stats object with the same settings as `self`.

        Args:
            init_overrides: Optional dict of initialization arguments to override. Can be used to change is_root, is_leaf, etc.

        Returns:
            A new stats object similar to `self` but missing internal values.
        )stats_objectr   )	__class__r]   update)r   rc   r`   	new_statss       r   clonezStatsBase.clone   sU     N11t1DD	 	-^,,,"DN//Y//	r   c                 R    | j         | j        | j        d}| j        s
| j        |d<   |S )z&Returns the state of the stats object.)r   r   r   r   )r   r   r   r   r   r[   s     r   	get_statezStatsBase.get_state   s>     %)$=||
 

 | 	8%)%7E/"r   c                     |d         | _         |d         | _        | j        |d         k    sJ | j        s|d         | _        dS dS )zySets the state of the stats object.

        Args:
            state: The state to set on this StatsBase object.
        r   r   r   r   N)r   r   r   r   rk   s     r   r^   zStatsBase.set_state   s]     Y'Y'(E2H,IIIII| 	8!&!7D	8 	8r   c                 p    ||d         }|d         }||dS | | j         | j        dS t          d          )z;Returns the initialization arguments for this Stats object.Nr   r   )r   r   z-Either stats_object or state must be provided)r   r   r!   )re   r[   r   r   s       r   r]   zStatsBase._get_init_args   sg     I&GI&G""   %'/'/  
 LMMMr   c                     d S r5   r   r   s    r   __repr__zStatsBase.__repr__   s    r   incoming_statsc                     dS )zuMerges StatsBase objects.

        Args:
            incoming_stats: The list of StatsBase objects to merge.
        Nr   )r   rq   s     r   mergezStatsBase.merge         r   r/   c                 (    | j         s
J d            dS )zPushes a value into this Stats object.

        Args:
            value: The value to push. Can be of any type.
                GPU tensors are moved to CPU memory.
        zYCannot push values to non-leaf Stats. Non-leaf Stats can only receive values via merge().N)r   r.   s     r   rU   zStatsBase.push   s3     L	g 	gf	g 	g	g 	gr   r'   latest_merged_onlyc                     dS )a  Returns the result of reducing the internal values list.

        Note that this method does NOT alter the internal values list in this process.
        Thus, users can call this method to get an accurate look at the reduced value(s)
        given the current internal values list.

        Args:
            compile: If True, the result is compiled into a single value if possible.
            latest_merged_only: If True, only considers the latest merged values.
                This parameter only works on aggregation stats objects (is_leaf=False).
                When enabled, peek() will only use the values from the most recent merge operation.

        Returns:
            The result of reducing the internal values list on CPU memory.
        Nr   )r   r'   rv   s      r   r)   zStatsBase.peek  rt   r   c                     dS )a  Reduces the internal values.

        This method should NOT be called directly by users.
        It can be used as a hook to prepare the stats object for sending it to the root metrics logger and starting a new 'reduce cycle'.

        The reduction logic depends on the implementation of the subclass.
        Meaning that some classes may reduce to a single value, while others do not or don't even contain values.

        Args:
            compile: If True, the result is compiled into a single value if possible.
                If False, the result is a Stats object similar to itself, but with the internal values reduced.
        Returns:
            The reduced value or a Stats object similar to itself, but with the internal values reduced.
        Nr   )r   r'   s     r   reducezStatsBase.reduce  rt   r   )FT)r   r   )r   Nr5   )NN)TF)T)0__name__
__module____qualname____doc__r   str__annotations__boolr   propertyr   r   r-   r"   r   r2   r$   r0   r3   r9   r<   r>   r@   rC   rE   rH   rJ   rM   rS   rZ   classmethodr   r   rb   r   r	   ri   rl   r^   staticmethodr]   rp   r   rs   rU   r
   r)   ry   r   r   r   r   r      s           !%#$$$ > >> > > > >8     X $ 4    $#     ^    + + ++ + ++ + +* * ** * ** * ** * ** * *& & &   
) 
) 
) 
) tCH~ +    [ ; 48  c3h0 
   ;:$ ;	4S> 	 	 	 ;:	 ;8tCH~ 8$ 8 8 8 ;:8  ;N Nc3h N N N \ ;:N$ #    ^ D$5 $    ^ 	g# 	g$ 	g 	g 	g ^	g ?D 8<	sDI~	   ^&  d eC4D.E    ^  r   r   )	metaclass)rO   r   abcr   r   collectionsr   typingr   r   r   r	   r
   ray.rllib.utils.annotationsr   r   ray.util.annotationsr   r   r   r   r   <module>r      s         ' ' ' ' ' ' ' '       3 3 3 3 3 3 3 3 3 3 3 3 3 3        . - - - - - V V V V V' V V V V V Vr   