
    &`ib*                         d Z ddlZddlmZm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 ddlmZ ddlmZ erddlmZ  ej        e          Zedd            ZddZddZddZd Z	 	 ddZd Zd ZdS )z,Common pre-checks for all RLlib experiments.    N)TYPE_CHECKINGSet)DeveloperAPI)ERR_MSG_OLD_GYM_APIUnsupportedSpaceException)get_base_struct_from_space)log_onceMultiAgentEnvenvr   returnc                 ,    ddl m} t           |          st          d          t	           d          r t	           d          rt	           d          s/t          d          rt                              d  d	           d
S 	                      di           }n5# t          $ r(}t          t          j         d                    |d
}~ww xY w|\  }}t           |d            fd|                                D             }t           |d           	                      |          }n5# t          $ r(}t          t          j         d                    |d
}~ww xY w|\  }}	}
}}t           |d           t           |	d           t           |
d           t           |d           t           |dd           t          d|	id j                   t#          d|
id|id j                   t%          d|id j                   d
S )zgChecking for common errors in RLlib MultiAgentEnvs.

    Args:
        env: The env to be checked.
    r   r
   z&The passed env is not a MultiAgentEnv.observation_spaceaction_space
_agent_idsma_env_super_ctor_calledzYour MultiAgentEnv z does not have some or all of the needed base-class attributes! Make sure you call `super().__init__()` from within your MutiAgentEnv's constructor. This will raise an error in the future.N*   )seedoptionsz7In particular, the `reset()` method seems to be faulty.zreset()c                 `    i | ]*}|                     |                                          +S  )get_action_spacesample).0aidr   s     r/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/rllib/utils/pre_checks/env.py
<dictcomp>z1check_multiagent_environments.<locals>.<dictcomp>9   sB       47S!!#&&--//      z&get_action_space(agent_id=..).sample()z6In particular, the `step()` method seems to be faulty.zstep, next_obszstep, rewardz
step, donezstep, truncatedz
step, infoT)allow_commondummy_env_id)base_env	agent_ids)ray.rllib.envr   
isinstance
ValueErrorhasattrr	   loggerwarningreset	Exceptionr   format"_check_if_element_multi_agent_dictkeysstep_check_rewardagents_check_done_and_truncated_check_info)r   r   obs_and_infose	reset_obsreset_infossampled_actionresultsnext_obsrewarddone	truncatedinfos   `            r   check_multiagent_environmentsr>      s    ,+++++c=)) ABBB())C(( C&&
 .// 	NN:c : : :   			r2	66   &N 
 
 		 +I{&sIyAAA   ;D>>;K;K  N '^E  ((>**   &M 
 
 		 /6+HfdIt&sH6FGGG&sFNCCC&sD,???&sI7HIII&sD,TRRRR>6*TSZPPPP		#*	    &LLLLLLs0   B 
C)#CCD2 2
E$<#EE$Fc                    |r|                                  D ]\  }}|                                 D ]\  }}t          j        |          rNt          |t                    s9t          j        |          sIt          |t          j                  r|j        dk    s$d| dt          |           }t          |          ||v s|dk    sd| }t          |          d S t          j        |           rNt          | t                    s9t          j        |           sVt          | t          j                  r| j        dk    s3d
                    t          |                     }t          |          d S d S )Nr   zJYour step function must return rewards that are integer or float. reward: z. Instead it was a __all__zrYour reward dictionary must have agent ids that belong to the environment. AgentIDs received from env.agents are: zUYour step function must return a reward that is integer or float. Instead it was a {})itemsnpisrealr$   boolisscalarndarrayshapetyper%   r+   )r:   r!   r"   _multi_agent_dictagent_idrewerrors           r   r/   r/   Y   s    $ #)<<>> 	, 	,A!1!7!7!9!9 , ,#IcNN,&sD11, C((	,
 'sBJ77,
 =@IOO'69' '99' ' 
 %U+++ I--Y1F1F7+47 7 
 %U++++,	, 	,0 		& 64((  K	 
 62:.. 
 4:<23E3E""(&f"6"6 	    
 4F3Er   c                    dD ]}|dk    r| n|}|r|                                 D ]\  }}|                                 D ]i\  }}	t          |	t          t          j        f          s"t          d| dt          |                     ||v s|dk    sd| d| }
t          |
          jt          |t          t          j        f          s$d| d	t          |           }
t          |
          d S )
N)r;   r<   r;   z Your step function must return `z's` that are boolean. But instead was a r@   zYour `zis` dictionary must have agent ids that belong to the environment. AgentIDs received from env.agents are: z"Your step function must return a `z'` that is a boolean. But instead was a )rA   r$   rD   rB   bool_r%   rH   )r;   r<   r!   r"   whatdatarI   rJ   rK   done_rM   s              r   r1   r1      sr   % $ $v~~tt9 	$'+zz|| 0 0##'7'='='?'? 0 0OHe%edBH-=>> (Gt G G:>t**G G   %	11X5J5J;T ; ;/8; ; 
 )///00 D4"233 	$.T . .!%d. .  U###	$#$ $r   c                    |r|                                  D ]z\  }}|                                 D ]`\  }}t          |t                    s"t          dt	          |           d|           ||v s |dk    s|dk    sd| }t          |          a{d S t          | t                    s$dt	          |            d|  }t          |          d S )NzDYour step function must return infos that are a dict. instead was a z: element: r@   
__common__zqYour dones dictionary must have agent ids that belong to the environment. AgentIDs received from env.agents are: zDYour step function must return a info that is a dict. element type: z. element: )rA   r$   dictr%   rH   )r=   r!   r"   rI   rJ   rK   infrM   s           r   r2   r2      sK     #'::<< 	, 	,A!1!7!7!9!9 , ,#!#t,, $E)-cE E?BE E  
 	))9,,<//7+47 7 
 %U+++!,	, 	,$ d##  F(,T

F F?CF F 	    r   c                 0    d| d|  d| d| d| d| d}|S )NzThe z collected from z% was not contained within your env's z@ space. Its possible that there was a typemismatch (for example z)s of np.float32 and a space ofnp.float64 zs), or that one of the sub-zs wasout of boundsr   )	func_name_type_errors      r   _not_contained_errorr[      sh    	u 	 	i 	 		 	!&	 	 	 	 9>	 	 	  Mr   c                 B   t          |t                    s<|rd| dt          |           }nd| dt          |           }t          |          t	          | j                                      d           |r                    d           t          fd|D                       sq|r0d| dt          |	                                           d| j         }n0d| d	t          |	                                           d| j         d
}t          |          d S )NzThe element returned by zJ contains values that are not MultiAgentDicts. Instead, they are of type: z3 is not a MultiAgentDict. Instead, it is of type:  r@   rT   c              3       K   | ]}|v V  	d S Nr   )r   kr"   s     r   	<genexpr>z5_check_if_element_multi_agent_dict.<locals>.<genexpr>   s'      //!qI~//////r   z_ has agent_ids that are not the names of the agents in the env.agent_ids in this
MultiEnvDict: z
AgentIDs in this env: zb has agent_ids that are not the names of the agents in the env. 
AgentIDs in this MultiAgentDict: z. You likely need to add the attribute `agents` to your env, which is a list containing the IDs of agents currently in your env/episode, as well as, `possible_agents`, which is a list of all possible agents that could ever show up in your env.)
r$   rU   rH   r%   setr0   addalllistr-   )r   elementfunction_stringr!   r   rM   r"   s         @r   r,   r,      s    gt$$   	)? ) )g) ) E$? $ $MM$ $ 
 __IMM) $l###////w/////   	 ?     ((    :	    EH? H H ''H H :	H H H  )   r   c                    t          | t          j        j        t          j        j        f          sd| | j        |t          |          fS t          |           }d }	 t          j	        |||           nz# t          $ rm}|j        d         d         |j        d         d         }} d                    |j        d         d                   | | j        |t          |          fcY d}~S d}~ww xY wdS )aC  Returns error, value, and space when offending `space.contains(value)` fails.

    Returns only the offending sub-value/sub-space in case `space` is a complex Tuple
    or Dict space.

    Args:
        space: The gym.Space to check.
        value: The actual (numpy) value to check for matching `space`.

    Returns:
        Tuple consisting of 1) key-sequence of the offending sub-space or the empty
        string if `space` is not complex (Tuple or Dict), 2) the offending sub-space,
        3) the offending sub-space's dtype, 4) the offending sub-value, 5) the offending
        sub-value's dtype.

    .. testcode::
        :skipif: True

        path, space, space_dtype, value, value_dtype = _find_offending_sub_space(
            gym.spaces.Dict({
           -2.0, 1.5, (2, ), np.int8), np.array([-1.5, 3.0])
        )

    Nc                 T    |                     |          st          | ||f          d S r^   )containsr   )psvs      r   map_fnz)_find_offending_sub_space.<locals>.map_fn  s2    zz!}} 	7+Q1I666	7 	7r   r         z->)NNNNN)r$   gymspacesDictTupledtype	_get_typer   treemap_structure_with_pathr   argsjoin)spacevaluestructured_spacerm   r4   s        r   _find_offending_sub_spacer}      s   2 ecjosz/?@AA AUEK	%0@0@@@1%887 7 7T$V-=uEEEE$ T T Tvay|QVAYq\uyy1&&u{E9UCSCSSSSSSSST
 ('s   A4 4
C+>A"C& C+&C+c                 N    t          | d          r| j        nt          |           S )Nrt   )r&   rt   rH   )vars    r   ru   ru     s#    W--<399499<r   )r   r   r   N)FN)FF) __doc__loggingtypingr   r   	gymnasiumrp   numpyrB   rv   ray.rllib.utils.annotationsr   ray.rllib.utils.errorr   r   "ray.rllib.utils.spaces.space_utilsr   ray.utilr	   r#   r   	getLogger__name__r'   r>   r/   r1   r2   r[   r,   r}   ru   r   r   r   <module>r      s   2 2  % % % % % % % %          4 4 4 4 4 4 P P P P P P P P I I I I I I       ,++++++		8	$	$ AM AM AM AMH%  %  %  % P$ $ $ $4       8   .  .  .  . b)( )( )(X= = = = =r   