
    &`i@                        d dl Z d dlmZ d dlmZmZ 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 d dlmZ d dlmZ d	Zd
ZdZ e j        e          Ze G d d                      Ze G d de                      Ze G d de                      Ze G d de                      Ze G d de                      Ze G d de                      Z e G d de                      Z!e G d de                      Z"e G d de                      Z#ed#dej$        d e%fd!            Z&dej$        d ee'         fd"Z(dS )$    N)OrderedDict)AnyList)OldAPIStackoverride)resize)Repeated)convert_element_to_space_type)
TensorType)            d   c                       e Zd ZdZddej        defdZdej        dedee	         fdZ
dedej        fd	Zded
ej        de	ddfdZdeddfdZede	fd            Zedej        fd            ZdS )PreprocessorzDefines an abstract observation preprocessor function.

    Attributes:
        shape (List[int]): Shape of the preprocessed output.
    N	obs_spaceoptionsc                 d   t          |           || _        |s ddlm} |                                | _        n|| _        |                     || j                  | _        t          t          j
        | j                            | _        d| _        | j                                        | _        d S )Nr   )MODEL_DEFAULTS)_legacy_patch_shapes
_obs_spaceray.rllib.models.catalogr   copy_options_init_shapeshapeintnpprod_size_isample_obs_for_type_matching)selfr   r   r   s       r/home/jaya/work/projects/VOICE-AGENT/VIET/agent-env/lib/python3.11/site-packages/ray/rllib/models/preprocessors.py__init__zPreprocessor.__init__    s    Y'''# 	$??????*//11DMM#DM%%i??
,,--
&*o&<&<&>&>###    returnc                     t           )z&Returns the shape after preprocessing.NotImplementedErrorr&   r   r   s      r'   r   zPreprocessor._init_shape.       !!r)   observationc                     t           )z%Returns the preprocessed observation.r,   r&   r0   s     r'   	transformzPreprocessor.transform2   r/   r)   arrayoffsetc                 J    |                      |          |||| j        z   <   dS )z7Alternative to transform for more efficient flattening.N)r3   r"   r&   r0   r4   r5   s       r'   writezPreprocessor.write6   s*    .2nn[.I.Ifv
**+++r)   c           	         | j         t          z  dk    r-t          |          t          u rUt	          | j        t          j        j                  r1t          j
        |                              t          j                  }| j                            |          st          || j                  }	 | j                            |          sTt!          d                    |t	          | j        t          j        j                  r|j        nd| j                            n## t&          $ r}t!          d|          |d}~ww xY w| xj         dz  c_         dS )z*Checks the shape of the given observation.r   z3Observation ({} dtype={}) outside given space ({})!Nz_Observation for a Box/MultiBinary/MultiDiscrete space should be an np.array, not a Python list.   )r#   OBS_VALIDATION_INTERVALtypelist
isinstancer   gymspacesBoxr    r4   astypefloat32containsr
   r%   
ValueErrorformatdtypeAttributeError)r&   r0   es      r'   check_shapezPreprocessor.check_shape:   sZ   7,,11K  D((Z. .( !h{33::2:FF?++K88 ;!< //<< 	$MTT')$/3:>JJ&K--!% O   	 "    @  	 	1s   0A.D 
D?)D::D?c                     | j         S N)r"   r&   s    r'   sizezPreprocessor.sizeY   s
    zr)   c                     t           j                            dd| j        t          j                  }t          t          t          t          t          t          f}t          | |          r| j        |_        |S )Ng            ?rG   )r?   r@   rA   r   r    rC   DictFlatteningPreprocessorOneHotPreprocessorRepeatedValuesPreprocessorTupleFlatteningPreprocessorAtariRamPreprocessorGenericPixelPreprocessorr>   r   original_space)r&   r   classess      r'   observation_spacezPreprocessor.observation_space]   s`    JNN4dj
NKK	 '&' $
 dG$$ 	7'+I$r)   rL   )__name__
__module____qualname____doc__r?   Spacedictr(   r   r   r   r   r    ndarrayr3   r8   r   rJ   propertyrN   rZ    r)   r'   r   r      sG        ? ?#) ?d ? ? ? ?"SY " "$s) " " " ""Z "BJ " " " "J JBJ J JPT J J J Js t    > c    X 39    X  r)   r   c                       e Zd ZdZ ee          dej        dede	e
         fd            Z ee          dedej        fd            ZdS )	rW   zGeneric image preprocessor.

    Note: for Atari games, use config {"preprocessor_pref": "deepmind"}
    instead for deepmind-style Atari preprocessing.
    r   r   r*   c                     |                     d          | _        |                     d          | _        |                     d          | _        | j        r| j        | j        df}n| j        | j        df}|S )N	grayscale	zero_meandimr:   r   )get
_grayscale
_zero_mean_dim)r&   r   r   r   s       r'   r   z$GenericPixelPreprocessor._init_shapew   sl    !++k22!++k22KK&&	? 	.Y	1-EEY	1-Er)   r0   c                    |                      |           |ddddddf         }| j        dk     rt          |dd          }t          || j        | j                  }| j        rV|                    d          }|                    t          j                  }t          j        || j        | j        dg          }| j	        r	|dz
  dz  }n|d	z  }|S )
z?Downsamples images from (210, 160, 3) by the configured factor.   iNT   )heightwidth   r:   r   gp?)
rJ   rl   r   rj   meanrB   r    rC   reshaperk   )r&   r0   scaleds      r'   r3   z"GenericPixelPreprocessor.transform   s     	%%%RVQQQ\*9r>>F2R888F ty	BBB? 	C[[^^F]]2:..FZDIq(ABBF? 	"slc)FFk!Fr)   N)r[   r\   r]   r^   r   r   r?   r_   r`   r   r   r   r   r    ra   r3   rc   r)   r'   rW   rW   o   s          Xl	SY 	 	$s) 	 	 	 	 XlZ BJ      r)   rW   c                       e Zd Z ee          dej        dedee	         fd            Z
 ee          dedej        fd            ZdS )rV   r   r   r*   c                     dS )Nr   rc   r.   s      r'   r   z AtariRamPreprocessor._init_shape   s    vr)   r0   c                 b    |                      |           |                    d          dz
  dz  S )NrC   r   )rJ   rB   r2   s     r'   r3   zAtariRamPreprocessor.transform   s4    %%%""9--3s::r)   N)r[   r\   r]   r   r   r?   r_   r`   r   r   r   r   r    ra   r3   rc   r)   r'   rV   rV      s        XlSY  $s)     Xl;Z ;BJ ; ; ; ; ; ;r)   rV   c            	           e Zd ZdZ ee          dej        dede	e
         fd            Z ee          dedej        fd            Z ee          dedej        d	e
dd
fd            Zd
S )rS   ar  One-hot preprocessor for Discrete and MultiDiscrete spaces.

    .. testcode::
        :skipif: True

        self.transform(Discrete(3).sample())

    .. testoutput::

        np.array([0.0, 1.0, 0.0])

    .. testcode::
        :skipif: True

        self.transform(MultiDiscrete([2, 3]).sample())

    .. testoutput::

        np.array([0.0, 1.0, 0.0, 0.0, 1.0])
    r   r   r*   c                     t          |t          j        j                  r| j        j        fS t          j        | j        j                  fS rL   )	r>   r?   r@   Discreter   nr    sumnvecr.   s      r'   r   zOneHotPreprocessor._init_shape   s?    i!455 	3O%''F4?/0022r)   r0   c                     |                      |           t          j        j                            | j        |                              t          j                  S rL   )	rJ   r?   r@   utilsflattenr   rB   r    rC   r2   s     r'   r3   zOneHotPreprocessor.transform   sC    %%%z''EELLRZXXXr)   r4   r5   Nc                 J    |                      |          |||| j        z   <   d S rL   )r3   rN   r7   s       r'   r8   zOneHotPreprocessor.write   s*    -1^^K-H-Hfv	))***r)   r[   r\   r]   r^   r   r   r?   r_   r`   r   r   r   r   r    ra   r3   r8   rc   r)   r'   rS   rS      s         * Xl3SY 3 3$s) 3 3 3 3 XlYZ YBJ Y Y Y Y XlI IBJ I IPT I I I I I Ir)   rS   c            	       "   e Zd Z ee          dej        dedee	         fd            Z
 ee          dedej        fd            Z ee          dedej        de	dd	fd
            Ze ee          dej        fd                        Zd	S )NoPreprocessorr   r   r*   c                     | j         j        S rL   r   r   r.   s      r'   r   zNoPreprocessor._init_shape       $$r)   r0   c                 0    |                      |           |S rL   )rJ   r2   s     r'   r3   zNoPreprocessor.transform   s    %%%r)   r4   r5   Nc                 p    t          j        |d                                          |||| j        z   <   d S NF)r   r    r4   ravelr"   r7   s       r'   r8   zNoPreprocessor.write   9    .0h{.O.O.O.U.U.W.Wfv
**+++r)   c                     | j         S rL   )r   rM   s    r'   rZ   z NoPreprocessor.observation_space   s     r)   )r[   r\   r]   r   r   r?   r_   r`   r   r   r   r   r    ra   r3   r8   rb   rZ   rc   r)   r'   r   r      s#       Xl%SY % %$s) % % % % XlZ BJ     XlX XBJ X XPT X X X X Xl39     X  r)   r   c            	       &   e Zd ZdZ ee          dej        dede	e
         fd            Z ee          dedej        fd            Z ee          dedej        d	e
dd
fd            Ze ee          dej        fd                        Zd
S )MultiBinaryPreprocessora  Preprocessor that turns a MultiBinary space into a Box.

    Note: Before RLModules were introduced, RLlib's ModelCatalogV2 would produce
    ComplexInputNetworks that treat MultiBinary spaces as Boxes. This preprocessor is
    needed to get rid of the ComplexInputNetworks and use RLModules instead because
    RLModules lack the logic to handle MultiBinary or other non-Box spaces.
    r   r   r*   c                     | j         j        S rL   r   r.   s      r'   r   z#MultiBinaryPreprocessor._init_shape   r   r)   r0   c                 j    |                      |           |                    t          j                  S rL   )rJ   rB   r    rC   r2   s     r'   r3   z!MultiBinaryPreprocessor.transform   s.     	%%%!!"*---r)   r4   r5   Nc                 p    t          j        |d                                          |||| j        z   <   d S r   r   r7   s       r'   r8   zMultiBinaryPreprocessor.write   r   r)   c                     t           j                            dd| j        t          j                  }| j        |_        |S )Ng        rP   rQ   )r?   r@   rA   r   r    rC   r   rX   )r&   r   s     r'   rZ   z)MultiBinaryPreprocessor.observation_space   s3     JNN3TZrzNJJ	#'?	 r)   )r[   r\   r]   r^   r   r   r?   r_   r`   r   r   r   r   r    ra   r3   r8   rb   rZ   rc   r)   r'   r   r      s/         Xl%SY % %$s) % % % % Xl.Z .BJ . . . .
 XlX XBJ X XPT X X X X Xl39     X  r)   r   c            	           e Zd ZdZ ee          dej        dede	e
         fd            Z ee          dedej        fd            Z ee          dedej        d	e
dd
fd            Zd
S )rU   zPreprocesses each tuple element, then flattens it all into a vector.

    RLlib models will unpack the flattened output before _build_layers_v2().
    r   r   r*   c                    t          | j        t          j        j                  sJ d}g | _        t          t          | j        j                            D ]}| j        j        |         }t          	                    d
                    |                     t          |          }| ||| j                  }||j        z  }n+d }|t          t          j        |j                            z  }| j                            |           |fS Nr   z Creating sub-preprocessor for {})r>   r   r?   r@   TuplepreprocessorsrangelenloggerdebugrF   get_preprocessorr   rN   r   r    r!   r   append)r&   r   r   rN   ispacepreprocessor_classpreprocessors           r'   r   z'TupleFlatteningPreprocessor._init_shape
  s    $/3:+;<<<<<s4?12233 
	4 
	4AO*1-ELL;BB5IIJJJ!1%!8!8!-11%GG))#BGEK00111%%l3333wr)   r0   c                     |                      |           t          j        | j        t          j                  }|                     ||d           |S NrQ   r   rJ   r    zerosr   rC   r8   r&   r0   r4   s      r'   r3   z%TupleFlatteningPreprocessor.transform  I    %%%2:666

;q)))r)   r4   r5   Nc                     t          |          t          | j                  k    s
J |            t          || j                  D ]&\  }}|                    |||           ||j        z  }'d S rL   )r   r   zipr8   rN   r&   r0   r4   r5   ops         r'   r8   z!TupleFlatteningPreprocessor.write#  s|    ;3t'9#:#::::K:::T%788 	 	DAqGGAuf%%%afFF	 	r)   r   rc   r)   r'   rU   rU     s         
 XlSY  $s)    " XlZ BJ     Xl BJ  PT      r)   rU   c            	           e Zd ZdZ ee          dej        dede	e
         fd            Z ee          dedej        fd            Z ee          dedej        d	e
dd
fd            Zd
S )rR   zPreprocesses each dict value, then flattens it all into a vector.

    RLlib models will unpack the flattened output before _build_layers_v2().
    r   r   r*   c                    t          | j        t          j        j                  sJ d}g | _        | j        j                                        D ]}t                              d	                    |                     t          |          }| ||| j                  }||j        z  }n+d }|t          t          j        |j                            z  }| j                            |           |fS r   )r>   r   r?   r@   Dictr   valuesr   r   rF   r   r   rN   r   r    r!   r   r   )r&   r   r   rN   r   r   r   s          r'   r   z&DictFlatteningPreprocessor._init_shape2  s    $/3:?;;;;;_+2244 		4 		4ELL;BB5IIJJJ!1%!8!8!-11%GG))#BGEK00111%%l3333wr)   r0   c                     |                      |           t          j        | j        t          j                  }|                     ||d           |S r   r   r   s      r'   r3   z$DictFlatteningPreprocessor.transformC  r   r)   r4   r5   Nc                    t          |t                    s.t          t          |                                                    }t	          |          t	          | j                  k    s+J t	          |          t	          | j                  f            t          |                                | j                  D ]&\  }}|                    |||           ||j	        z  }'d S rL   )
r>   r   sorteditemsr   r   r   r   r8   rN   r   s         r'   r8   z DictFlatteningPreprocessor.writeJ  s    +{33 	C%f[->->-@-@&A&ABBK;3t'9#:#::::"##=
::: **,,d.@AA 	 	DAqGGAuf%%%afFF	 	r)   r   rc   r)   r'   rR   rR   +  s         
 XlSY  $s)      XlZ BJ     Xl	 	BJ 	 	PT 	 	 	 	 	 	r)   rR   c            	           e Zd ZdZ ee          dej        dede	e
         fd            Z ee          dedej        fd            Z ee          dedej        d	e
dd
fd            Zd
S )rT   z0Pads and batches the variable-length list value.r   r   r*   c                     t          | j        t                    sJ |j        } t	          |          || j                  | _        d| j        j        |j        z  z   }|fS )Nr:   )	r>   r   r	   child_spacer   r   child_preprocessorrN   max_len)r&   r   r   r   rN   s        r'   r   z&RepeatedValuesPreprocessor._init_shape[  sg    $/844444+"?"2;"?"?#
 #
 4*/)2CCCwr)   r0   c                     t          j        | j                  }t          |t                    r |D ]}| j                            |           n	 |                     ||d           |S )Nr   )r    r   r   r>   r=   r   rJ   r8   )r&   r0   r4   elems       r'   r3   z$RepeatedValuesPreprocessor.transformf  ss    $$k4(( 	# : :'33D9999: 

;q)))r)   r4   r5   Nc                    t          |t          t          j        f          s#t	          d                    | |                    t          |          | j        j        k    r-t	          d                    || j        j                            t          |          ||<   t          |          D ]6\  }}|dz   || j
        j        z  z   }| j
                            |||           7d S )Nz&Input for {} must be list type, got {}z$Input {} exceeds max len of space {}r:   )r>   r=   r    ra   rE   rF   r   r   r   	enumerater   rN   r8   )r&   r0   r4   r5   r   r   offset_is          r'   r8   z RepeatedValuesPreprocessor.writeq  s    +bj'9:: 		8??kRR    7776==!8    K((f -- 	A 	AGAtzA(?(D$DDH#))$x@@@@	A 	Ar)   r   rc   r)   r'   rT   rT   W  s        ::XlSY  $s)     XlZ BJ     XlA ABJ A APT A A A A A Ar)   rT   Fr   r*   c                    t          |            | j        }t          | t          j        j        t          j        j        f          r	t          }n%|t          k    r:t          
                    d                    t                               t          }n|t          k    r:t          
                    d                    t                               t          }nt          | t          j        j                  rt           }ntt          | t          j        j                  rt$          }nMt          | t&                    rt(          }n0t          | t          j        j                  r
|rt,          }nt.          }|S )z>Returns an appropriate preprocessor class for the given space.a  Defaulting to RLlib's GenericPixelPreprocessor because input space has the atari-typical shape {}. Turn this behaviour off by setting `preprocessor_pref=None` or `preprocessor_pref='deepmind'` or disabling the preprocessing API altogether with `_disable_preprocessor_api=True`.a  Defaulting to RLlib's AtariRamPreprocessor because input space has the atari-typical shape {}. Turn this behaviour off by setting `preprocessor_pref=None` or `preprocessor_pref='deepmind' or disabling the preprocessing API altogether with `_disable_preprocessor_api=True`.`.)r   r   r>   r?   r@   r{   MultiDiscreterS   ATARI_OBS_SHAPEr   r   rF   rW   ATARI_RAM_OBS_SHAPErV   r   rU   r   rR   r	   rT   MultiBinaryr   r   )r   include_multi_binary	obs_shaper   s       r'   r   r     sF    I%#*-sz/GHII &)	o	%	%@ AG@W@W	
 	
 	
 0	)	)	)
 ((	
 	
 	
 ,	E3:+	,	, 
&2	E3:?	+	+ &1	E8	$	$ &1	E3:1	2	2 &7K &.%r)   c                 D   t          | d          st          | t          j        j                  rd| _        nct          | t          j        j                  rDg }| j        D ]&}t          |          }|                    |           't          |          | _        | j        S )zAssigns shapes to spaces that don't have shapes.

    This is only needed for older gym versions that don't set shapes properly
    for Tuple and Discrete spaces.
    r   rc   )
hasattrr>   r?   r@   r{   r   r   r   r   tuple)r   shapessr   s       r'   r   r     s     5'"" (eSZ011 	(EKKsz/00 	(F\ % %,Q//e$$$$--EK;r)   )F))loggingcollectionsr   typingr   r   	gymnasiumr?   numpyr    ray.rllib.utils.annotationsr   r   ray.rllib.utils.imagesr   ray.rllib.utils.spaces.repeatedr	   "ray.rllib.utils.spaces.space_utilsr
   ray.rllib.utils.typingr   r   r   r;   	getLoggerr[   r   r   rW   rV   rS   r   r   rU   rR   rT   r_   r<   r   r   r   rc   r)   r'   <module>r      s?    # # # # # #                 = = = = = = = = ) ) ) ) ) ) 4 4 4 4 4 4 L L L L L L - - - - - -   		8	$	$ S S S S S S S Sl ' ' ' ' '| ' ' 'T ; ; ; ; ;< ; ; ; $I $I $I $I $I $I $I $IN     \   (     l   > $ $ $ $ $, $ $ $N ( ( ( ( ( ( ( (V )A )A )A )A )A )A )A )AX ' 'CI 'd ' ' ' 'T	 d3i      r)   