o
    ci4                     @   s  d dl Z d dlmZ d dl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Zd dlZd dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d	Zed
efddZdejdefddZ dedejfddZ!edej"j#defddZ$edej"j#defddZ%ededej"j#fddZ&ededej"j#fddZ'ede
e deeef fd d!Z(ed"eeef defd#d$Z)e	%d*d&eeef d'e*de	eeef  fd(d)Z+dS )+    N)OrderedDict)AnyDictOptionalSequenceTypeUnion)DeveloperAPI)NotSerializable)FlexDict)RepeatedSimplex__not_serializable__objc                 C   s   t | tjr
t| S t | tjrt| S t | tjrt| S t | tjr(t	| S t | tj
rC|  }t|D ]
\}}t|||< q6|S | S )zConvert an object that is a numpy type to a python type.

    If the object is not a numpy type, it is returned unchanged.

    Args:
        obj: The object to convert.
    )
isinstancenpintegerintfloatingfloatbool_boolstr_strndarraytolist	enumerate"convert_numpy_to_python_primitives)r   retiv r"   Q/home/ubuntu/.local/lib/python3.10/site-packages/ray/rllib/utils/serialization.pyr      s   	r   arrayreturnc                 C   s.   t  }t||  tt| 	dS )zPack numpy ndarray into Base64 encoded strings for serialization.

    This function uses numpy.save() instead of pickling to ensure
    compatibility.

    Args:
        array: numpy ndarray.

    Returns:
        b64 escaped string.
    ascii)
ioBytesIOr   savebase64	b64encodezlibcompressgetvaluedecode)r$   bufr"   r"   r#   _serialize_ndarray/   s   r1   
b64_stringc                 C   s    t jttt| ddS )zUnpack b64 escaped string into numpy ndarray.

    This function assumes the unescaped bytes are of npy format.

    Args:
        b64_string: Base64 escaped string.

    Returns:
        numpy ndarray.
    T)allow_pickle)r   loadr'   r(   r,   
decompressr*   	b64decode)r2   r"   r"   r#   _deserialize_ndarray@   s   r7   spacec                 C   s  | du rdS dt jjdtfdd}dt jjdtfdd}dt jjdtfdd	}dt jjdtfd
d}dt jjdtfdd}dt jjdtfdd}dtdtfdd}dt	dtfdd}dt
dtfdd}	dddtfdd}
t| t jjrw|| S t| t jjr|| S t| t jjr|| S t| t jjr|| S t| t jjr|| S t| t jjr|| S t| t jjr|
| S t| tr|| S t| t	r|| S t| t
r|	| S tdt| )zSerialize a gym Space into a JSON-serializable dict.

    Args:
        space: gym.spaces.Space

    Returns:
        Serialized JSON string.
    Nspr%   c                 S   s"   dt | jt | j| j| jjdS )Nbox)r8   lowhighshapedtype)r1   r;   r<   _shaper>   r   r9   r"   r"   r#   _box]   s   zgym_space_to_dict.<locals>._boxc                 S   s,   dt | jd}t| drt | j|d< |S )Ndiscreter8   nstart)r   rD   hasattrrE   )r9   dr"   r"   r#   	_discretef   s   
z$gym_space_to_dict.<locals>._discretec                 S   s   d| j dS )Nmulti-binaryrC   )rD   r@   r"   r"   r#   _multi_binaryp   s   z(gym_space_to_dict.<locals>._multi_binaryc                 S   s   dt | j| jjdS )Nmulti-discrete)r8   nvecr>   )r1   rL   r>   r   r@   r"   r"   r#   _multi_discretev   s   z*gym_space_to_dict.<locals>._multi_discretec                 S   s   ddd | j D dS )Ntuplec                 S      g | ]}t |qS r"   gym_space_to_dict.0r9   r"   r"   r#   
<listcomp>       z5gym_space_to_dict.<locals>._tuple.<locals>.<listcomp>r8   spacesrW   r@   r"   r"   r#   _tuple}   s   z!gym_space_to_dict.<locals>._tuplec                 S   s   ddd | j  D dS )Ndictc                 S      i | ]	\}}|t |qS r"   rP   rS   kr9   r"   r"   r#   
<dictcomp>       z4gym_space_to_dict.<locals>._dict.<locals>.<dictcomp>rV   )rW   itemsr@   r"   r"   r#   _dict   s   z gym_space_to_dict.<locals>._dictc                 S   s   d| j | j| jjdS )Nsimplex)r8   r=   concentrationr>   )r?   rc   r>   r   r@   r"   r"   r#   _simplex   s
   z#gym_space_to_dict.<locals>._simplexc                 S   s   dt | j| jdS )Nrepeated)r8   child_spacemax_len)rQ   rf   rg   r@   r"   r"   r#   	_repeated   s   z$gym_space_to_dict.<locals>._repeatedc                 S   s(   ddi}| j D ]
\}}t|||< q|S )Nr8   	flex_dict)rW   rQ   )r9   rG   r]   sr"   r"   r#   
_flex_dict   s
   z%gym_space_to_dict.<locals>._flex_dictgym.spaces.Textc                 S   sB   t | dd }|d u rt | dd }|d u rtdd| j| j|dS )Ncharacter_setcharsetz9Text space must have a character_set or charset attributetext)r8   
min_length
max_lengthrn   )getattr
ValueErrorrp   rq   )r9   rn   r"   r"   r#   _text   s   z gym_space_to_dict.<locals>._textz&Unknown space type for serialization, )gymrW   Boxr   DiscreteMultiBinaryMultiDiscreteTupler   r   r   r   Textrs   type)r8   rA   rH   rJ   rM   rY   ra   rd   rh   rk   rt   r"   r"   r#   rQ   P   sB   
	



rQ   c                 C   s(   dt | i}d| jv rt| j|d< |S Nr8   original_space)rQ   __dict__space_to_dictr~   )r8   rG   r"   r"   r#   r      s   
r   rG   c                    s>  | du rdS dt fdd dt dtjjf fdd}dt dtjjf fdd	}dt dtjjf fd
d}dt dtjjf fdd}dt dtjjfdd}dt dtjjfdd}dt dtf fdd}dt dtfdd}dt dt	fdd}	dt ddf fdd}
|||||||||	|
d
}| d }||vrt
d||| | S )zDe-serialize a dict into gym Space.

    Args:
        str: serialized JSON str.

    Returns:
        De-serialized gym space.
    NrG   c                 S   s,   |   }|d= d|v rt|d |d< |S )z?Common updates to the dict before we use it to construct spacesr8   r>   )copyr   r>   rG   r   r"   r"   r#   __common   s
   z%gym_space_from_dict.<locals>.__commonr%   c                    s>   |   }|t| d t| d d tjjdi  |S )Nr;   r<   )r;   r<   r"   )r   updater7   ru   rW   rv   r   r   r"   r#   rA      s   

z!gym_space_from_dict.<locals>._boxc                       t jjdi  | S Nr"   )ru   rW   rw   rG   r   r"   r#   rH         z&gym_space_from_dict.<locals>._discretec                    r   r   )ru   rW   rx   r   r   r"   r#   rJ      r   z*gym_space_from_dict.<locals>._multi_binaryc                    s4   |   }|dt|d i tjjdi  |S )NrL   r"   )r   r   r7   ru   rW   ry   r   r   r"   r#   rM      s   z,gym_space_from_dict.<locals>._multi_discretec                 S   s    dd | d D }t jj|dS )Nc                 S   rO   r"   gym_space_from_dictrR   r"   r"   r#   rT      rU   z7gym_space_from_dict.<locals>._tuple.<locals>.<listcomp>rW   rX   )ru   rW   rz   rG   rW   r"   r"   r#   rY      s   z#gym_space_from_dict.<locals>._tuplec                 S   s(   t dd | d  D }tjj|dS )Nc                 S   r[   r"   r   r\   r"   r"   r#   r^     r_   z6gym_space_from_dict.<locals>._dict.<locals>.<dictcomp>rW   rX   )r   r`   ru   rW   r   r   r"   r"   r#   ra     s   
z"gym_space_from_dict.<locals>._dictc                    s   t di  | S r   r   r   r   r"   r#   rd     s   z%gym_space_from_dict.<locals>._simplexc                 S   s   t | d }t|| d dS )Nrf   rg   )rf   rg   )r   r   )rG   rf   r"   r"   r#   rh     s   z&gym_space_from_dict.<locals>._repeatedc                 S   s   dd |   D }t|dS )Nc                 S   s"   i | ]\}}|d kr|t |qS )r8   r   )rS   r]   rj   r"   r"   r#   r^     s   " z;gym_space_from_dict.<locals>._flex_dict.<locals>.<dictcomp>rX   )r`   r   r   r"   r"   r#   rk     s   
z'gym_space_from_dict.<locals>._flex_dictrl   c                    r   r   )ru   rW   r{   r   r   r"   r#   rt     r   z"gym_space_from_dict.<locals>._text)
r:   rB   rI   rK   rN   rZ   rb   re   ri   ro   r8   z)Unknown space type for de-serialization, )r   ru   rW   rv   rw   rx   ry   r   r   r   rs   )rG   rA   rH   rJ   rM   rY   ra   rd   rh   rk   rt   	space_map
space_typer"   r   r#   r      s8   

	
r   c                 C   sZ   t | d }d| v r+d| d v sJ t| d d tr$t | d |_|S t| d |_|S r}   )r   r   r   r~   space_from_dict)rG   r8   r"   r"   r#   r   3  s   r   argskwargsc                 C   s   | D ]"}z
t t | W q ty$ } z
td| d| d}~ww | D ]'\}}z
t t | W q) tyP } ztd| d| d| d}~ww dS )a  Check if parameters to a function are serializable by ray.

    Args:
        args: arguments to be checked.
        kwargs: keyword arguments to be checked.

    Raises:
        NoteSerializable if either args are kwargs are not serializable
            by ray.
    zVRLModule constructor arguments must be serializable. Found non-serializable argument: z .
Original serialization error: Nz^RLModule constructor arguments must be serializable. Found non-serializable keyword argument: z = )raygetput	TypeErrorr
   r`   )r   r   arger]   r!   r"   r"   r#   !check_if_args_kwargs_serializableB  s:   r   type_c                 C   s   t | tr| S | jd | j S )zConverts a type into its full classpath ([module file] + "." + [class name]).

    Args:
        type_: The type to convert.

    Returns:
        The full classpath of the given type, e.g. "ray.rllib.algorithms.ppo.PPOConfig".
    .)r   r   
__module____qualname__)r   r"   r"   r#   serialize_typef  s   
r   Fmoduleerrorc                 C   s   t | tr| S t | trBz| dd\}}t|} t| |W S  ttt	t
fyA } z|r6t
d|  d|W Y d}~| S d}~ww t
d|  d)aV  Resolves a class path to a class.
    If the given module is already a class, it is returned as is.
    If the given module is a string, it is imported and the class is returned.

    Args:
        module: The classpath (str) or type to resolve.
        error: Whether to throw a ValueError if `module` could not be resolved into
            a class. If False and `module` is not resolvable, returns None.

    Returns:
        The resolved class or `module` (if `error` is False and no resolution possible).

    Raises:
        ValueError: If `error` is True and `module` cannot be resolved.
    r      z2Could not deserialize the given classpath `module=z` into a valid python class! Make sure you have all necessary pip packages installed and all custom modules are in your `PYTHONPATH` env variable.Nz
`module` (z$ must be type or string (classpath)!)r   r|   r   rsplit	importlibimport_modulerr   ModuleNotFoundErrorImportErrorAttributeErrorrs   )r   r   module_path
class_namer   r"   r"   r#   deserialize_typex  s&   






r   )F),r*   collectionsr   r   r'   r,   typingr   r   r   r   r   r   	gymnasiumru   numpyr   r   ray.rllib.utils.annotationsr	   ray.rllib.utils.errorr
   ray.rllib.utils.spaces.flexdictr   ray.rllib.utils.spaces.repeatedr   ray.rllib.utils.spaces.simplexr   NOT_SERIALIZABLEr   r   r   r1   r7   rW   SpacerQ   r   r   r   r   r   r   r   r"   r"   r"   r#   <module>   sP     wb #
