
    &`i>                        d Z ddlZddl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 ddlmZmZmZmZ erddlmZ  ej        e          Ze G d d	                      Ze G d
 dej                              Ze G d de                      Ze G d de                      Ze G d dej                              ZdS )zIThis file defines base types and common structures for RLlib connectors.
    N)TYPE_CHECKINGAnyDictListTupleUnion)ViewRequirement)OldAPIStack)ActionConnectorDataTypeAgentConnectorDataTypeAlgorithmConfigDict
TensorType)Policyc                       e Zd ZdZ	 	 	 	 	 	 ddedee         dej        dej        de	e
ef         d	efd
Zedd            ZdS )ConnectorContextzData bits that may be needed for running connectors.

    Note(jungong) : we need to be really careful with the data fields here.
    E.g., everything needs to be serializable, in case we need to fetch them
    in a remote setting.
    NFconfiginitial_statesobservation_spaceaction_spaceview_requirementsis_policy_recurrentc                 b    |pi | _         |pg | _        || _        || _        || _        || _        dS )a  Construct a ConnectorContext instance.

        Args:
            initial_states: States that are used for constructing
                the initial input dict for RNN models. [] if a model is not recurrent.
            action_space_struct: a policy's action space, in python
                data format. E.g., python dict instead of DictSpace, python tuple
                instead of TupleSpace.
        Nr   r   r   r   r   r   )selfr   r   r   r   r   r   s          r/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/rllib/connectors/connector.py__init__zConnectorContext.__init__%   sB    $ l,2!2(!2#6       policyr   returnc           	          t          | j        |                                 | j        | j        | j        |                                           S )zBuild ConnectorContext from a given policy.

        Args:
            policy: Policy

        Returns:
            A ConnectorContext instance.
        r   )r   r   get_initial_stater   r   r   is_recurrent)r   s    r   from_policyzConnectorContext.from_policy>   sP      =!3355$6,$6 & 3 3 5 5
 
 
 	
r   )NNNNNF)r   r   r   r   )__name__
__module____qualname____doc__r   r   r   gymSpacer   strr	   boolr   staticmethodr#    r   r   r   r      s          '++/'+"&8<$)7 7#7 Z(7 9	7
 i7  _ 457 "7 7 7 72 
 
 
 \
 
 
r   r   c                   x    e Zd ZdZdefdZd Zd ZddefdZ	d	e
eef         fd
Zededed	d fd            ZdS )	Connectora  Connector base class.

    A connector is a step of transformation, of either envrionment data before they
    get to a policy, or policy output before it is sent back to the environment.

    Connectors may be training-aware, for example, behave slightly differently
    during training and inference.

    All connectors are required to be serializable and implement to_state().
    ctxc                     d| _         d S NT_is_training)r   r0   s     r   r   zConnector.__init___   s     r   c                     d| _         d S r2   r3   r   s    r   in_trainingzConnector.in_trainingc   s     r   c                     d| _         d S )NFr3   r6   s    r   in_evalzConnector.in_evalf   s    !r   r   indentationc                 &    d|z  | j         j        z   S )N )	__class__r$   r   r:   s     r   __str__zConnector.__str__i   s    [ 4>#:::r   r   c                     t           S )a  Serialize a connector into a JSON serializable Tuple.

        to_state is required, so that all Connectors are serializable.

        Returns:
            A tuple of connector's name and its serialized states.
            String should match the name used to register the connector,
            while state can be any single data structure that contains the
            serialized state of the connector. If a connector is stateless,
            state can simply be None.
        NotImplementedErrorr6   s    r   to_statezConnector.to_statel   s
     #"r   paramsc                     t           S )aL  De-serialize a JSON params back into a Connector.

        from_state is required, so that all Connectors are serializable.

        Args:
            ctx: Context for constructing this connector.
            params: Serialized states of the connector to be recovered.

        Returns:
            De-serialized connector.
        rA   )r0   rD   s     r   
from_statezConnector.from_state{   s
     #"r   Nr   )r$   r%   r&   r'   r   r   r7   r9   intr?   r   r*   r   rC   r,   rF   r-   r   r   r/   r/   R   s        	 	!, ! ! ! !! ! !" " "; ;3 ; ; ; ;#%S/ # # # # #( ## #+ # # # \# # #r   r/   c                   b    e Zd ZdZdefdZdefdZdee	         dee	         fdZ
d	e	de	fd
ZdS )AgentConnectora
  Connector connecting user environments to RLlib policies.

    An agent connector transforms a list of agent data in AgentConnectorDataType
    format into a new list in the same AgentConnectorDataTypes format.
    The input API is designed so agent connectors can have access to all the
    agents assigned to a particular policy.

    AgentConnectorDataTypes can be used to specify arbitrary type of env data,

    Example:

        Represent a list of agent data from one env step() call.

        .. testcode::

            import numpy as np
            ac = AgentConnectorDataType(
                env_id="env_1",
                agent_id=None,
                data={
                    "agent_1": np.array([1, 2, 3]),
                    "agent_2": np.array([4, 5, 6]),
                }
            )

        Or a single agent data ready to be preprocessed.

        .. testcode::

            ac = AgentConnectorDataType(
                env_id="env_1",
                agent_id="agent_1",
                data=np.array([1, 2, 3]),
            )

        We can also adapt a simple stateless function into an agent connector by
        using register_lambda_agent_connector:

        .. testcode::

            import numpy as np
            from ray.rllib.connectors.agent.lambdas import (
                register_lambda_agent_connector
            )
            TimesTwoAgentConnector = register_lambda_agent_connector(
                "TimesTwoAgentConnector", lambda data: data * 2
            )

            # More complicated agent connectors can be implemented by extending this
            # AgentConnector class:

            class FrameSkippingAgentConnector(AgentConnector):
                def __init__(self, n):
                    self._n = n
                    self._frame_count = default_dict(str, default_dict(str, int))

                def reset(self, env_id: str):
                    del self._frame_count[env_id]

                def __call__(
                    self, ac_data: List[AgentConnectorDataType]
                ) -> List[AgentConnectorDataType]:
                    ret = []
                    for d in ac_data:
                        assert d.env_id and d.agent_id, "Skipping works per agent!"

                        count = self._frame_count[ac_data.env_id][ac_data.agent_id]
                        self._frame_count[ac_data.env_id][ac_data.agent_id] = (
                            count + 1
                        )

                        if count % self._n == 0:
                            ret.append(d)
                    return ret

    As shown, an agent connector may choose to emit an empty list to stop input
    observations from being further prosessed.
    env_idc                     dS )zReset connector state for a specific environment.

        For example, at the end of an episode.

        Args:
            env_id: required. ID of a user environment. Required.
        Nr-   )r   rK   s     r   resetzAgentConnector.reset   s	     	r   outputc                     dS )a  Callback on agent connector of policy output.

        This is useful for certain connectors, for example RNN state buffering,
        where the agent connect needs to be aware of the output of a policy
        forward pass.

        Args:
            ctx: Context for running this connector call.
            output: Env and agent IDs, plus data output from policy forward pass.
        Nr-   )r   rN   s     r   on_policy_outputzAgentConnector.on_policy_output   s	     	r   acd_listr   c                 l     t          |t          t          f          s
J d             fd|D             S )a  Transform a list of data items from env before they reach policy.

        Args:
            ac_data: List of env and agent IDs, plus arbitrary data items from
                an environment or upstream agent connectors.

        Returns:
            A list of transformed data items in AgentConnectorDataType format.
            The shape of a returned list does not have to match that of the input list.
            An AgentConnector may choose to derive multiple outputs for a single piece
            of input data, for example multi-agent obs -> multiple single agent obs.
            Agent connectors may also choose to skip emitting certain inputs,
            useful for connectors such as frame skipping.
        z=Input to agent connectors are list of AgentConnectorDataType.c                 :    g | ]}                     |          S r-   	transform).0dr   s     r   
<listcomp>z+AgentConnector.__call__.<locals>.<listcomp>	  s%    444aq!!444r   )
isinstancelisttuple)r   rQ   s   ` r   __call__zAgentConnector.__call__   sW    " tUm
 
 	K 	KJ	K 	K 
 544484444r   ac_datac                     t           )a  Transform a single agent connector data item.

        Args:
            data: Env and agent IDs, plus arbitrary data item from a single agent
                of an environment.

        Returns:
            A transformed piece of agent connector data.
        rA   r   r]   s     r   rU   zAgentConnector.transform  s
     "!r   N)r$   r%   r&   r'   r*   rM   r   rP   r   r   r\   rU   r-   r   r   rJ   rJ      s        M M^C    '>    5345	$	%5 5 5 5.
"!7 
"<R 
" 
" 
" 
" 
" 
"r   rJ   c                   2    e Zd ZdZdedefdZdedefdZdS )ActionConnectora  Action connector connects policy outputs including actions,
    to user environments.

    An action connector transforms a single piece of policy output in
    ActionConnectorDataType format, which is basically PolicyOutputType plus env and
    agent IDs.

    Any functions that operate directly on PolicyOutputType can be easily adapted
    into an ActionConnector by using register_lambda_action_connector.

    Example:

    .. testcode::

        from ray.rllib.connectors.action.lambdas import (
            register_lambda_action_connector
        )
        ZeroActionConnector = register_lambda_action_connector(
            "ZeroActionsConnector",
            lambda actions, states, fetches: (
                np.zeros_like(actions), states, fetches
            )
        )

    More complicated action connectors can also be implemented by sub-classing
    this ActionConnector class.
    r]   r   c                 ,    |                      |          S )zTransform policy output before they are sent to a user environment.

        Args:
            ac_data: Env and agent IDs, plus policy output.

        Returns:
            The processed action connector data.
        rT   r_   s     r   r\   zActionConnector.__call__6  s     ~~g&&&r   c                     t           )a  Implementation of the actual transform.

        Users should override transform instead of __call__ directly.

        Args:
            ac_data: Env and agent IDs, plus policy output.

        Returns:
            The processed action connector data.
        rA   r_   s     r   rU   zActionConnector.transformA  s
     "!r   N)r$   r%   r&   r'   r   r\   rU   r-   r   r   ra   ra     sf         8	' 7 	'<S 	' 	' 	' 	'"!8 "=T " " " " " "r   ra   c                       e Zd ZdZdedee         fdZd Zd Z	de
fdZde
d	efd
Zde
d	efdZd	efdZd	efdZddefdZdee
eef         fdZdS )ConnectorPipelinez=Utility class for quick manipulation of a connector pipeline.r0   
connectorsc                     || _         d S N)rf   )r   r0   rf   s      r   r   zConnectorPipeline.__init__S  s    $r   c                 B    | j         D ]}|                                 d S rh   )rf   r7   r   cs     r   r7   zConnectorPipeline.in_trainingV  s,     	 	AMMOOOO	 	r   c                 B    | j         D ]}|                                 d S rh   )rf   r9   rj   s     r   r9   zConnectorPipeline.in_evalZ  s,     	 	AIIKKKK	 	r   namec                    d}t          | j                  D ]\  }}|j        j        |k    r|} n|dk    r5| j        |= t                              d| d| j        j         d           dS t                              d| d           dS )zkRemove a connector by <name>

        Args:
            name: name of the connector to be removed.
        r   zRemoved connector z from .z*Trying to remove a non-existent connector N)	enumeraterf   r=   r$   loggerinfowarning)r   rm   idxirk   s        r   removezConnectorPipeline.remove^  s     do.. 	 	DAq{#t++ , !88$KKSTSS9PSSSTTTTTNNOOOOPPPPPr   	connectorc           	      8   d}t          | j                  D ]\  }}|j        j        |k    r n|dk     rt	          d|           | j                            ||           t                              d|j        j         d| d| j        j         d           dS )	zInsert a new connector before connector <name>

        Args:
            name: name of the connector before which a new connector
                will get inserted.
            connector: a new connector to be inserted.
        ro   r   Can not find connector 	Inserted z before  to rp   Nrq   rf   r=   r$   
ValueErrorinsertrr   rs   r   rm   rx   ru   rk   s        r   insert_beforezConnectorPipeline.insert_beforeo  s     00 	 	FC{#t++ ,77=t==>>>sI...-	+4 - -d - -.)- - -	
 	
 	
 	
 	
r   c           	      >   d}t          | j                  D ]\  }}|j        j        |k    r n|dk     rt	          d|           | j                            |dz   |           t                              d|j        j         d| d| j        j         d           d	S )
zInsert a new connector after connector <name>

        Args:
            name: name of the connector after which a new connector
                will get inserted.
            connector: a new connector to be inserted.
        ro   r   rz      r{   z after r|   rp   Nr}   r   s        r   insert_afterzConnectorPipeline.insert_after  s     00 	 	FC{#t++ ,77=t==>>>sQw	222-	+4 - -T - -.)- - -	
 	
 	
 	
 	
r   c                     | j                             d|           t                              d|j        j         d| j        j         d           dS )zAppend a new connector at the beginning of a connector pipeline.

        Args:
            connector: a new connector to be appended.
        r   Added z to the beginning of rp   N)rf   r   rr   rs   r=   r$   r   rx   s     r   prependzConnectorPipeline.prepend  sj     	q),,,*Y(1 * *~&* * *	
 	
 	
 	
 	
r   c                     | j                             |           t                              d|j        j         d| j        j         d           dS )zAppend a new connector at the end of a connector pipeline.

        Args:
            connector: a new connector to be appended.
        r   z to the end of rp   N)rf   appendrr   rs   r=   r$   r   s     r   r   zConnectorPipeline.append  sh     	y)))*Y(1 * *~&* * *	
 	
 	
 	
 	
r   r   r:   c                 x    d                     dz  | j        j        z   gfd| j        D             z             S )N
r<   c                 @    g | ]}|                     d z             S )   )r?   )rV   rk   r:   s     r   rX   z-ConnectorPipeline.__str__.<locals>.<listcomp>  s)    CCCaqyyq))CCCr   )joinr=   r$   rf   r>   s    `r   r?   zConnectorPipeline.__str__  sM    yy;!889CCCC4?CCCD
 
 	
r   keyc                    t          |t                    st          |t                    rt          d          t          |t                    r| j        |         gS t          |t                    r8g }| j        D ],}t          |j        |          r|	                    |           -|S t          d
                    t          |                              g }| j        D ]'}|j        j        |k    r|	                    |           (|S )a  Returns a list of connectors that fit 'key'.

        If key is a number n, we return a list with the nth element of this pipeline.
        If key is a Connector class or a string matching the class name of a
        Connector class, we return a list of all connectors in this pipeline matching
        the specified class.

        Args:
            key: The key to index by

        Returns: The Connector at index `key`.
        z8Slicing of ConnectorPipeline is currently not supported.z*Indexing by {} is currently not supported.)rY   r*   slicerB   rH   rf   type
issubclassr=   r   formatr$   )r   r   resultsrk   s       r   __getitem__zConnectorPipeline.__getitem__  s    #s## 	#u%% )N   C%% ,--C&& 	 * *A!!+s33 *q))))@GGS		RR    	" 	"A{#s**q!!!r   NrG   )r$   r%   r&   r'   r   r   r/   r   r7   r9   r*   rw   r   r   r   r   rH   r?   r   r   r   r-   r   r   re   re   O  s?       GG%, %$y/ % % % %    Q3 Q Q Q Q"
# 
) 
 
 
 
*
 
 
 
 
 
*
 
 
 
 

	 
 
 
 

 
3 
 
 
 
%uS#t^4 % % % % % %r   re   ) r'   abcloggingtypingr   r   r   r   r   r   	gymnasiumr(   !ray.rllib.policy.view_requirementr	   ray.rllib.utils.annotationsr
   ray.rllib.utils.typingr   r   r   r   ray.rllib.policy.policyr   	getLoggerr$   rr   r   ABCr/   rJ   ra   re   r-   r   r   <module>r      s    


  ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?     = = = = = = 3 3 3 3 3 3             /......		8	$	$ 5
 5
 5
 5
 5
 5
 5
 5
p 6# 6# 6# 6# 6# 6# 6# 6#r H" H" H" H" H"Y H" H" H"V 3" 3" 3" 3" 3"i 3" 3" 3"l N N N N N N N N N Nr   