
    h                    ~   S r SSKJr  SSKrSSKrSSKrSSKrSSKJrJ	r	  SSK
Jr  SSKJr  SSKJr  SSKJr  SS	KJr  SS
KJr  SSKrSSKJrJr  SSKJrJrJrJr  SSKJ r J!r!J"r"J#r#  SSK$J%r%  SSK&J'r'J(r(J)r)J*r*J+r+J,r,J-r-J.r.J/r/J0r0  SSK1J2r2J3r3J4r4  SS/r5 " S S\5      r6 " S S\45      r7              SS jr8g)zAn async vector environment.    )annotationsN)CallableSequence)deepcopy)Enum)Queue)
Connection)SynchronizedArray)Any)Spacelogger)ActTypeEnvObsTypeRenderFrame)AlreadyPendingCallErrorClosedEnvironmentErrorCustomSpaceErrorNoAsyncCallError)is_space_dtype_shape_equiv)
CloudpickleWrapperbatch_differing_spacesbatch_spaceclear_mpi_env_varsconcatenatecreate_empty_arraycreate_shared_memoryiterateread_from_shared_memorywrite_to_shared_memory)	ArrayTypeAutoresetMode	VectorEnvAsyncVectorEnv
AsyncStatec                  (    \ rS rSrSrSrSrSrSrSr	g)	r%   .   z?The AsyncVectorEnv possible states given the different actions.defaultresetstepcall N)
__name__
__module____qualname____firstlineno____doc__DEFAULTWAITING_RESETWAITING_STEPWAITING_CALL__static_attributes__r,       [/home/james-whalen/.local/lib/python3.13/site-packages/gymnasium/vector/async_vector_env.pyr%   r%   .   s    IGMLLr7   c                     \ rS rSrSrSSSSSS\R                  4               SS jjr\SS j5       r	\SS j5       r
SSS	.     S S
 jjr  S!   S"S jjr S#   S$S jjr    S%S jrS&S jr S#   S'S jjrS(S jrS)S jrS*S jrS#S+S jjrS,S jrS-S jrS.S/S jjrS#S0S jjrS rS rS1S jrS rSrg)2r$   7   a  Vectorized environment that runs multiple environments in parallel.

It uses ``multiprocessing`` processes, and pipes for communication.

Example:
    >>> import gymnasium as gym
    >>> envs = gym.make_vec("Pendulum-v1", num_envs=2, vectorization_mode="async")
    >>> envs
    AsyncVectorEnv(Pendulum-v1, num_envs=2)
    >>> envs = gym.vector.AsyncVectorEnv([
    ...     lambda: gym.make("Pendulum-v1", g=9.81),
    ...     lambda: gym.make("Pendulum-v1", g=1.62)
    ... ])
    >>> envs
    AsyncVectorEnv(num_envs=2)
    >>> observations, infos = envs.reset(seed=42)
    >>> observations
    array([[-0.14995256,  0.9886932 , -0.12224312],
           [ 0.5760367 ,  0.8174238 , -0.91244936]], dtype=float32)
    >>> infos
    {}
    >>> _ = envs.action_space.seed(123)
    >>> observations, rewards, terminations, truncations, infos = envs.step(envs.action_space.sample())
    >>> observations
    array([[-0.1851753 ,  0.98270553,  0.714599  ],
           [ 0.6193494 ,  0.7851154 , -1.0808398 ]], dtype=float32)
    >>> rewards
    array([-2.96495728, -1.00214607])
    >>> terminations
    array([False, False])
    >>> truncations
    array([False, False])
    >>> infos
    {}
TNsamec	                   Xl         X l        X0l        X@l        XPl        X`l        Xpl        [        U[        5      (       a  UO
[        U5      U l	        [        U5      U l        US   " 5       n	U	R                  U l        U R                  U R                  S'   U	R                  U l        U	R                  U l        [!        U R                  U R                  5      U l        [        U["        5      (       aS  [        U5      S:X  aD  [        US   [$        5      (       d   e[        US   [$        5      (       d   eUu  U l        U l        OUS:X  a7  U	R&                  U l        [!        U R(                  U R                  5      U l        OYUS:X  aE  U R                    V
s/ s H  o" 5       R&                  PM     nn
US   U l        [+        U5      U l        O[-        SU 35      eU	R/                  5         A	[0        R2                  " U5      nU R                  (       aD   [5        U R(                  U R                  US9n[7        U R(                  XR                  S	9U l        O4Sn[=        U R(                  U R                  [>        R@                  S9U l        / / sU l!        U l"        URG                  5       U l$        U=(       d    [J        n[M        5          [O        U R                   5       H  u  nnURQ                  5       u  nnURS                  US[U        U 5      RV                   SU 3U[Y        U5      UUUU RH                  U R                  4S9nU RB                  R[                  U5        U RD                  R[                  U5        UUl        UR]                  5         UR/                  5         M     SSS5        [^        R`                  U l1        U Re                  5         gs  sn
f ! [:         a  n[-        S
5      UeSnAff = f! , (       d  f       NW= f)aG	  Vectorized environment that runs multiple environments in parallel.

Args:
    env_fns: Functions that create the environments.
    shared_memory: If ``True``, then the observations from the worker processes are communicated back through
        shared variables. This can improve the efficiency if the observations are large (e.g. images).
    copy: If ``True``, then the :meth:`AsyncVectorEnv.reset` and :meth:`AsyncVectorEnv.step` methods
        return a copy of the observations.
    context: Context for `multiprocessing`. If ``None``, then the default context is used.
    daemon: If ``True``, then subprocesses have ``daemon`` flag turned on; that is, they will quit if
        the head process quits. However, ``daemon=True`` prevents subprocesses to spawn children,
        so for some environments you may want to have it set to ``False``.
    worker: If set, then use that worker in a subprocess instead of a default one.
        Can be useful to override some inner vector env logic, for instance, how resets on termination or truncation are handled.
    observation_mode: Defines how environment observation spaces should be batched. 'same' defines that there should be ``n`` copies of identical spaces.
        'different' defines that there can be multiple observation spaces with different parameters though requires the same shape and dtype,
        warning, may raise unexpected errors. Passing a ``Tuple[Space, Space]`` object allows defining a custom ``single_observation_space`` and
        ``observation_space``, warning, may raise unexpected errors.
    autoreset_mode: The Autoreset Mode used, see https://farama.org/Vector-Autoreset-Mode for more information.

Warnings:
    worker is an advanced mode option. It provides a high degree of flexibility and a high chance
    to shoot yourself in the foot; thus, if you are writing your own worker, it is recommended to start
    from the code for ``_worker`` (or ``_async_worker``) method, and add changes.

Raises:
    RuntimeError: If the observation space of some sub-environment does not match observation_space
        (or, by default, the observation space of the first sub-environment).
    ValueError: If observation_space is a custom space (i.e. not a default space in Gym,
        such as gymnasium.spaces.Box, gymnasium.spaces.Discrete, or gymnasium.spaces.Dict) and shared_memory is True.
r   autoreset_mode      r;   	differentzwInvalid `observation_mode`, expected: 'same' or 'different' or tuple of single and batch observation space, actual got )nctx)rA   zUsing `AsyncVector(..., shared_memory=True)` caused an error, you can disable this feature with `shared_memory=False` however this is slower.N)rA   fnzWorker<z>-)targetnameargs)3env_fnsshared_memorycopycontextdaemonworkerobservation_mode
isinstancer"   r=   lennum_envsmetadatarender_modeaction_spacesingle_action_spacer   tupler   observation_spacesingle_observation_spacer   
ValueErrorclosemultiprocessingget_contextr   r   observationsr   r   npzerosparent_pipes	processesr   error_queue_async_workerr   	enumeratePipeProcesstyper-   r   appendstartr%   r2   _state_check_spaces)selfrG   rH   rI   rJ   rK   rL   rM   r=   	dummy_envenv
env_spacesrB   _obs_buffererD   idxenv_fnparent_pipe
child_pipeprocesss                        r8   __init__AsyncVectorEnv.__init__\   s   ^ *	 0 .-88 ~. 	 G AJL	 "***.*=*=&'$00#,#9#9 '(@(@$--P&..37G3HA3M.q159999.q159999DTAD"D$A6)090K0K-)4114==*& "[0 BFN#ce55
N0:1-)?
)K&  N  O_  N`  a  	 ))'2
211T]] %<11;--%! K 2--288!D -/)4>99;(=!(6V*-((*'Z++!"4:#6#6"7r#?*62"##((++ &  !!((5%%g.!'  "+  7 "0 !((y O, $   d "!s,   OAO CO7
O4#O//O47
Pc                $    U R                  S5      $ )z<Returns a tuple of np_random seeds for all the wrapped envs.np_random_seedget_attrrk   s    r8   ry   AsyncVectorEnv.np_random_seed   s     }}-..r7   c                $    U R                  S5      $ )zMReturns the tuple of the numpy random number generators for the wrapped envs.	np_randomrz   r|   s    r8   r   AsyncVectorEnv.np_random   s     }}[))r7   seedoptionsc               @    U R                  XS9  U R                  5       $ )a  Resets all sub-environments in parallel and return a batch of concatenated observations and info.

Args:
    seed: The environment reset seeds
    options: If to return the options

Returns:
    A batch of observations and info from the vectorized environment.
r   )reset_async
reset_wait)rk   r   r   s      r8   r)   AsyncVectorEnv.reset   s"     	d4  r7   c                0   U R                  5         Uc&  [        U R                  5       Vs/ s H  nSPM     nnO<[        U[        5      (       a'  [        U R                  5       Vs/ s H  oAU-   PM	     nn[        U5      U R                  :X  d!   SU R                   S[        U5       S35       eU R                  [        R                  :w  aA  [        SU R                  R                   S3[        U R                  R                  5      5      eUGb/  SU;   Ga(  UR                  S5      n[        U[        R                  5      (       d   S[        U5       35       eUR                   U R                  4:X  d!   S	U R                   S
UR                    35       eUR"                  [        R$                  :X  d   SUR"                   35       e[        R&                  " U5      (       d
   SU 35       e[)        U R*                  X5       H7  u  pgnU(       a  XrS.n	UR-                  SU	45        M&  UR-                  S5        M9     O6[)        U R*                  U5       H  u  pgXrS.n	UR-                  SU	45        M     [        R.                  U l        gs  snf s  snf )aL  Send calls to the :obj:`reset` methods of the sub-environments.

To get the results of these calls, you may invoke :meth:`reset_wait`.

Args:
    seed: List of seeds for each environment
    options: The reset option

Raises:
    ClosedEnvironmentError: If the environment was closed (if :meth:`close` was previously called).
    AlreadyPendingCallError: If the environment is already waiting for a pending call to another
        method (e.g. :meth:`step_async`). This can be caused by two consecutive
        calls to :meth:`reset_async`, with no call to :meth:`reset_wait` in between.
Nz=If seeds are passed as a list the length must match num_envs=z but got length=.z;Calling `reset_async` while waiting for a pending call to `z` to complete
reset_maskz9`options['reset_mask': mask]` must be a numpy array, got z0`options['reset_mask': mask]` must have shape `(z	,)`, got z>`options['reset_mask': mask]` must have `dtype=np.bool_`, got zK`options['reset_mask': mask]` must contain a boolean array, got reset_mask=r   r)   )
reset-noopN)_assert_is_runningrangerP   rN   intrO   ri   r%   r2   r   valuestrpopr]   ndarrayrf   shapedtypebool_anyzipr_   sendr3   )
rk   r   r   _ir   pipeenv_seed	env_reset
env_kwargss
             r8   r   AsyncVectorEnv.reset_async  s   & 	!<"'"67"6QD"6D7Dc""&+DMM&:;&:1H&:D;I&	wJ4==/Yijmnrjsittuv	w& ;;*,,,)MdkkN_N_M``mnDKK%%& 
 <7#: \2JBJJ  ^J4PZK[J\]^  ##(  mA$--PYZdZjZjYklm    BHH,cOPZP`P`Oabc,66  j\]g\hij  .11B1BD-U)	*2!GJIIw
34II23 .V #&d&7&7">&.C
		7J/0 #? !..O 8;s   J&Jc                &   U R                  5         U R                  [        R                  :w  a$  [	        S[        R                  R
                  5      eU R                  U5      (       d/  [        R                  U l        [        R                  " SU S35      e[        U R                   Vs/ s H  o"R                  5       PM     sn6 u  p4U R                  U5        0 n[        U6 u  p6[        U5       H  u  pxU R                  XXU5      nM     U R                   (       d%  [#        U R$                  X0R&                  5      U l        [        R                  U l        U R(                  (       a  [+        U R&                  5      U4$ U R&                  U4$ s  snf )a/  Waits for the calls triggered by :meth:`reset_async` to finish and returns the results.

Args:
    timeout: Number of seconds before the call to ``reset_wait`` times out. If `None`, the call to ``reset_wait`` never times out.

Returns:
    A tuple of batched observations and list of dictionaries

Raises:
    ClosedEnvironmentError: If the environment was closed (if :meth:`close` was previously called).
    NoAsyncCallError: If :meth:`reset_wait` was called without any prior call to :meth:`reset_async`.
    TimeoutError: If :meth:`reset_wait` timed out.
z=Calling `reset_wait` without any prior call to `reset_async`.z-The call to `reset_wait` has timed out after  second(s).)r   ri   r%   r3   r   r   _poll_pipe_envsr2   rZ   TimeoutErrorr   r_   recv_raise_if_errorsrc   	_add_inforH   r   rW   r\   rI   r   )	rk   timeoutr   results	successesinfos	info_datar   infos	            r8   r   AsyncVectorEnv.reset_waitL  sV   " 	!;;*222"R((.. 
 ##G,,$,,DK!..?yT  !4;L;L"M;L499;;L"MNi( '] +GANN52E , !! +--w8I8I!D !((/3yy**+RWWWd>O>ORWWW #Ns   +Fc                D    U R                  U5        U R                  5       $ )zTake an action for each parallel environment.

Args:
    actions: element of :attr:`action_space` batch of actions.

Returns:
    Batch of (observations, rewards, terminations, truncations, infos)
)
step_async	step_wait)rk   actionss     r8   r*   AsyncVectorEnv.stepz  s     	 ~~r7   c                   U R                  5         U R                  [        R                  :w  aA  [	        SU R                  R
                   S3[        U R                  R
                  5      5      e[        U R                  U5      n[        U R                  USS9 H  u  p4UR                  SU45        M     [        R                  U l        g)a  Send the calls to :meth:`Env.step` to each sub-environment.

Args:
    actions: Batch of actions. element of :attr:`VectorEnv.action_space`

Raises:
    ClosedEnvironmentError: If the environment was closed (if :meth:`close` was previously called).
    AlreadyPendingCallError: If the environment is already waiting for a pending call to another
        method (e.g. :meth:`reset_async`). This can be caused by two consecutive
        calls to :meth:`step_async`, with no call to :meth:`step_wait` in
        between.
z:Calling `step_async` while waiting for a pending call to `` to complete.T)strictr*   N)r   ri   r%   r2   r   r   r   r   rS   r   r_   r   r4   )rk   r   iter_actionsr   actions        r8   r   AsyncVectorEnv.step_async  s     	!;;*,,,)LT[[M^M^L__mnDKK%%& 
 t00': 1 1<MLDIIvv&' N --r7   c                   U R                  5         U R                  [        R                  :w  a$  [	        S[        R                  R
                  5      eU R                  U5      (       d/  [        R                  U l        [        R                  " SU S35      e/ / / / 0 4u  p#pEn/ n[        U R                  5       H  u  pU	R                  5       u  pUR                  U5        U(       d  M1  UR                  U
S   5        UR                  U
S   5        UR                  U
S   5        UR                  U
S   5        U R                  XjS   U5      nM     U R                  U5        U R                   (       d&  [#        U R$                  UU R&                  5      U l        [        R                  U l        U R(                  (       a  [+        U R&                  5      OU R&                  [,        R.                  " U[,        R0                  S	9[,        R.                  " U[,        R2                  S	9[,        R.                  " U[,        R2                  S	9U4$ )
a>  Wait for the calls to :obj:`step` in each sub-environment to finish.

Args:
    timeout: Number of seconds before the call to :meth:`step_wait` times out. If ``None``, the call to :meth:`step_wait` never times out.

Returns:
     The batched environment step information, (obs, reward, terminated, truncated, info)

Raises:
    ClosedEnvironmentError: If the environment was closed (if :meth:`close` was previously called).
    NoAsyncCallError: If :meth:`step_wait` was called without any prior call to :meth:`step_async`.
    TimeoutError: If :meth:`step_wait` timed out.
z;Calling `step_wait` without any prior call to `step_async`.z,The call to `step_wait` has timed out after r   r   r?   r>         )r   )r   ri   r%   r4   r   r   r   r2   rZ   r   rc   r_   r   rg   r   r   rH   r   rW   r\   rI   r   r]   arrayfloat64r   )rk   r   r\   rewardsterminationstruncationsr   r   env_idxr   env_step_returnsuccesss               r8   r   AsyncVectorEnv.step_wait  s     	!;;*111"P''-- 
 ##G,,$,,DK!..>wi{S  CEb"bRTBT?|%	&t'8'89MG'+yy{$OW%w##OA$67q12##OA$67""?1#56ua.@'J : 	i(!! +--!!!D !((+/99HT&&'$:K:KHHWBJJ/HH\2HH[1
 	
r7   c                N    U R                   " U/UQ70 UD6  U R                  5       $ )ad  Call a method from each parallel environment with args and kwargs.

Args:
    name (str): Name of the method or property to call.
    *args: Position arguments to apply to the method call.
    **kwargs: Keyword arguments to apply to the method call.

Returns:
    List of the results of the individual calls to the method or property for each environment.
)
call_async	call_wait)rk   rE   rF   kwargss       r8   r+   AsyncVectorEnv.call  s'     	.t.v.~~r7   c                $    U R                  S5      $ )z8Returns a list of rendered frames from the environments.renderr+   r|   s    r8   r   AsyncVectorEnv.render  s    yy""r7   c                \   U R                  5         U R                  [        R                  :w  aA  [	        SU R                  R
                   S3[        U R                  R
                  5      5      eU R                   H  nUR                  SXU445        M     [        R                  U l        g)a  Calls the method with name asynchronously and apply args and kwargs to the method.

Args:
    name: Name of the method or property to call.
    *args: Arguments to apply to the method call.
    **kwargs: Keyword arguments to apply to the method call.

Raises:
    ClosedEnvironmentError: If the environment was closed (if :meth:`close` was previously called).
    AlreadyPendingCallError: Calling `call_async` while waiting for a pending call to complete
z:Calling `call_async` while waiting for a pending call to `r   _callN)
r   ri   r%   r2   r   r   r   r_   r   r5   )rk   rE   rF   r   r   s        r8   r   AsyncVectorEnv.call_async  s     	!;;*,,,)LT[[M^M^L__mnDKK%%& 
 %%DIIwV 456 & --r7   c                   U R                  5         U R                  [        R                  :w  a$  [	        S[        R                  R
                  5      eU R                  U5      (       d/  [        R                  U l        [        R                  " SU S35      e[        U R                   Vs/ s H  o"R                  5       PM     sn6 u  p4U R                  U5        [        R                  U l        U$ s  snf )a  Calls all parent pipes and waits for the results.

Args:
    timeout: Number of seconds before the call to :meth:`step_wait` times out.
        If ``None`` (default), the call to :meth:`step_wait` never times out.

Returns:
    List of the results of the individual calls to the method or property for each environment.

Raises:
    NoAsyncCallError: Calling :meth:`call_wait` without any prior call to :meth:`call_async`.
    TimeoutError: The call to :meth:`call_wait` has timed out after timeout second(s).
z;Calling `call_wait` without any prior call to `call_async`.z,The call to `call_wait` has timed out after r   )r   ri   r%   r5   r   r   r   r2   rZ   r   r   r_   r   r   )rk   r   r   r   r   s        r8   r   AsyncVectorEnv.call_wait  s     	!;;*111"M''-- 
 ##G,,$,,DK!..>wi{S  !4;L;L"M;L499;;L"MNi( ((	 #Ns   +C2c                $    U R                  U5      $ )zGet a property from each parallel environment.

Args:
    name (str): Name of the property to be get from each individual environment.

Returns:
    The property with name
r   )rk   rE   s     r8   r{   AsyncVectorEnv.get_attr'  s     yyr7   c                   U R                  5         [        U[        [        45      (       d$  [	        U R
                  5       Vs/ s H  o2PM     nn[        U5      U R
                  :w  a%  [        S[        U5       SU R
                   S35      eU R                  [        R                  :w  aA  [        SU R                  R                   S3[        U R                  R                  5      5      e[        U R                  U5       H  u  pEUR!                  SX445        M     [        U R                   Vs/ s H  oDR#                  5       PM     sn6 u  p6U R%                  U5        gs  snf s  snf )a$  Sets an attribute of the sub-environments.

Args:
    name: Name of the property to be set in each individual environment.
    values: Values of the property to be set to. If ``values`` is a list or
        tuple, then it corresponds to the values for each individual
        environment, otherwise a single value is set for all environments.

Raises:
    ValueError: Values must be a list or tuple with length equal to the number of environments.
    AlreadyPendingCallError: Calling :meth:`set_attr` while waiting for a pending call to complete.
zUValues must be a list or tuple with length equal to the number of environments. Got `z` values for z environments.z8Calling `set_attr` while waiting for a pending call to `r   _setattrN)r   rN   listrU   r   rP   rO   rX   ri   r%   r2   r   r   r   r   r_   r   r   r   )rk   rE   valuesr   r   r   r   s          r8   set_attrAsyncVectorEnv.set_attr2  s6    	!&4-00&+DMM&:;&:f&:F;v;$--'F}M$--P 
 ;;*,,,)J4;;K\K\J]]klDKK%%& 
 t00&9KDIIzD=12 :T5F5FG5FTYY[5FGHi(! < Hs   E$3E)c                J   U(       a  SOUn U R                   [        R                  :w  aX  [        R                  " SU R                   R
                   S35        [        X R                   R
                   S35      nU" U5        U(       a;  U R                   H*  nUR                  5       (       d  M  UR                  5         M,     OwU R                   H,  nUc  M  UR                  (       a  M  UR                  S5        M.     U R                   H+  nUc  M  UR                  (       a  M  UR                  5         M-     U R                   H  nUc  M  UR!                  5         M     U R                   H  nUR#                  5         M     g! [        R                   a    Sn GNf = f)a  Close the environments & clean up the extra resources (processes and pipes).

Args:
    timeout: Number of seconds before the call to :meth:`close` times out. If ``None``,
        the call to :meth:`close` never times out. If the call to :meth:`close`
        times out, then all processes are terminated.
    terminate: If ``True``, then the :meth:`close` operation is forced and all processes are terminated.

Raises:
    TimeoutError: If :meth:`close` timed out.
r   z5Calling `close` while waiting for a pending call to `r   _waitTN)rY   N)ri   r%   r2   r   warnr   getattrrZ   r   r`   is_alive	terminater_   closedr   r   rY   join)rk   r   r   functionru   r   s         r8   close_extrasAsyncVectorEnv.close_extrasS  sG    !!g	{{j000KDKKL]L]K^^lm #4KK,=,=+>e)DE! >>##%%%%' * ))$t{{{IIo. * ))$t{{{IIK * %%D

 & ~~GLLN &% ++ 	I	s   A6F F"!F"c                "   U R                  5         Uc  g[        R                  " 5       U-   nU R                   HS  n[	        U[        R                  " 5       -
  S5      nUc    gUR
                  (       d  UR                  U5      (       a  MS    g   g)NTr   F)r   timeperf_counterr_   maxr   poll)rk   r   end_timer   deltas        r8   r   AsyncVectorEnv._poll_pipe_envs|  sx    !?$$&0%%D4#4#4#66:E|{{499U#3#3 & r7   c                   U R                  5         U R                   H7  nUR                  SU R                  U R                  U R
                  445        M9     [        U R                   Vs/ s H  oR                  5       PM     sn6 u  p#U R                  U5        [        U6 u  pE[        U5      (       d&  U R                  S:X  a  [        S5      e[        S5      e[        U5      (       d  [        SU R
                   S35      eg s  snf )Nrj   r;   zAsyncVectorEnv(..., observation_mode='same') however some of the sub-environments observation spaces are not equivalent. If this is intentional, use `observation_mode='different'` instead.zAsyncVectorEnv(..., observation_mode='different' or custom space) however the sub-environment's observation spaces do not share a common shape and dtype.z7Some environments have an action space different from `zT`. In order to batch actions, the action spaces from all environments must be equal.)r   r_   r   rM   rW   rT   r   r   r   allRuntimeError)rk   r   r   r   same_observation_spacessame_action_spacess         r8   rj   AsyncVectorEnv._check_spaces  s   !%%DII#--5500	 & !4;L;L"M;L499;;L"MNi(697m3*++$$." S  # p  %&&I$JbJbIc dd d  ' #Ns   +Dc                j    U R                   (       a"  [        S[        U 5      R                   S35      eg )NzTrying to operate on `z`, after a call to `close()`.)r   r   rf   r-   r|   s    r8   r   !AsyncVectorEnv._assert_is_running  s3    ;;((d)<)<(==Z[  r7   c                   [        U5      (       a  g U R                  [        U5      -
  nUS:  d   e[        U5       H  nU R                  R                  5       u  pEpg[        R                  " SU S35        [        R                  " U 5        U R                  U   R                  5         S U R                  U'   X2S-
  :X  d  M  [        R                  " S5        [        R                  U l        U" U5      e   g )Nr   z)Received the following error from Worker-z - Shutting it downr?   z4Raising the last exception back to the main process.)r   rP   sumr   ra   getr   errorr_   rY   r%   r2   ri   )rk   r   
num_errorsr   indexexctyper   traces           r8   r   AsyncVectorEnv._raise_if_errors  s    y>>]]S^3
A~~z"A+/+;+;+?+?+A(EELL;E7BUV LLE7$e$**,'+De$N"ST(00en$ #r7   c                l    [        U SS5      (       d"  [        U S5      (       a  U R                  SS9  ggg)zEOn deleting the object, checks that the vector environment is closed.r   Tri   )r   N)r   hasattrrY   r|   s    r8   __del__AsyncVectorEnv.__del__  s4    tXt,,x1H1HJJJ& 2I,r7   )ri   rS   r=   rJ   rI   rK   rG   ra   rQ   rP   rM   rV   r\   r_   r`   rR   rH   rT   rW   rL   )rG   zSequence[Callable[[], Env]]rH   boolrI   r  rJ   z
str | NonerK   r  rL   zTCallable[[int, Callable[[], Env], Connection, Connection, bool, Queue], None] | NonerM   zstr | Spacer=   zstr | AutoresetMode)returnztuple[int, ...])r  ztuple[np.random.Generator, ...])r   int | list[int | None] | Noner   zdict[str, Any] | Noner  tuple[ObsType, dict[str, Any]])NN)r   r  r   zdict | None)N)r   int | float | Noner  r  )r   r   r  z?tuple[ObsType, ArrayType, ArrayType, ArrayType, dict[str, Any]])r   z
np.ndarray)r   r  r  z;tuple[np.ndarray, np.ndarray, np.ndarray, np.ndarray, dict])rE   r   rF   r   r   r   r  tuple[Any, ...])r  ztuple[RenderFrame, ...] | None)rE   r   )r   r  r  r  )rE   r   r  r  )rE   r   r   zlist[Any] | tuple[Any] | objectNF)r   r  r   r  )r   z
int | None)r   zlist[bool] | tuple[bool])r-   r.   r/   r0   r1   r"   	NEXT_STEPrv   propertyry   r   r)   r   r   r*   r   r   r+   r   r   r   r{   r   r   r   rj   r   r   r  r6   r,   r7   r8   r$   r$   7   s   "N #" (..;.E.ES,S S 	S
 S SS &S ,Sj / / * * /3)-	! ,! '	!
 
(!( /3#=/+=/ =/B '+,X#,X 
(,X\  	H .4 -1:
):
	D:
x #..B	)B'R !F%,'r7   c                   U" 5       nUR                   nUR                  n	Sn
S nUR                  5           UR                  5       u  pUS:X  aA  UR                  " S0 UD6u  pU(       a  [        XX5        S nSn
UR                  X4S45        GOCUS:X  a  UR                  U0 4S45        GO&US:X  Ga  U[        R                  :X  aC  U
(       a  UR	                  5       u  pSu  nnnOUR                  U5      u  nnnnnU=(       d    Un
OU[        R                  :X  aB  UR                  U5      u  nnnnnU(       d  U(       a  UR	                  5       u  nnUUS.UEnUnOAU[        R                  :X  a  U
SL d   eUR                  U5      u  nnnnnO[        SU 35      eU(       a  [        XX5        S nUR                  XUUU4S45        GOUS	:X  a  UR                  S
5        OUS:X  am  Uu  nnnUS;   a  [        SU SU S35      eUR                  U5      n[        U5      (       a  UR                  U" U0 UD6S45        OUR                  US45        OxUS:X  a)  Uu  nnUR                  UU5        UR                  S
5        OIUS:X  a4  Uu  nnnUR                  US:X  a  UU:H  O[!        UU5      UU	:H  4S45        O[#        SU S35      eGM  UR                  5         g ! [$        [&        4 aW    [(        R*                  " 5       u  nnn[,        R.                  " 5       nUR1                  U UUU45        UR                  S5         Nwf = f! UR                  5         f = f)NFTr)   r   r*   )r   FF)
final_info	final_obszUnexpected autoreset_mode: rY   )NTr   )r)   r*   rY   r   rj   zTrying to call function `z` with `call`, use `z` directly instead.r   rj   r;   zReceived unknown command `zS`. Must be one of [`reset`, `step`, `close`, `_call`, `_setattr`, `_check_spaces`].r	  r,   )rV   rS   rY   r   r)   r    r   r"   r
  r*   	SAME_STEPDISABLEDrX   get_wrapper_attrcallableset_wrapper_attrr   r   KeyboardInterrupt	Exceptionsysexc_info	traceback
format_excput) r   rr   r   rs   rH   ra   r=   rm   rV   rS   	autoresetobservationcommanddatar   reward
terminated	truncatedreset_observation
reset_inforE   rF   r   attrr   obs_modesingle_obs_spacerT   
error_typeerror_messager   r   s                                    r8   rb   rb     s    (C--##LIKr IIKMG'!$'II$5$5! *)+ #'K %I		K.56L(		K,d34F"!]%<%<< ,/IIK)8G5
I  HHTN'"&%  * 7iI#}'>'>> #"! "Y8;		5): +/)4  ) 
 '8#}'='==$--- #"! %'B>BR%STT *)+ #'K		KYMtTUG#		,'G#%)"dFRR$3D69MdVSfg  ++D1D>>IItT4V4d;<IItTl+J&"e$$T51		,'O+BF?*,?		
 $,v#5 !14E E%?$46G&" 0<?	   #0	  :M  N O b 			 y) !'*||~$
M1$$&
M5AB		- ! 			s2   F1K& &M 'C.K& &A$M
M MM M")r   r   rr   r   r   r	   rs   r	   rH   z4SynchronizedArray | dict[str, Any] | tuple[Any, ...]ra   r   r=   r"   )9r1   
__future__r   rZ   r  r   r  collections.abcr   r   rI   r   enumr   r   multiprocessing.connectionr	   multiprocessing.sharedctypesr
   typingr   numpyr]   	gymnasiumr   r   gymnasium.corer   r   r   r   gymnasium.errorr   r   r   r   gymnasium.spaces.utilsr   gymnasium.vector.utilsr   r   r   r   r   r   r   r   r   r    gymnasium.vector.vector_envr!   r"   r#   __all__r%   r$   rb   r,   r7   r8   <module>r7     s    " "  
   .   ! 1 :   # = =  >   L K \
* W
'Y W
'tCCC C 	C
 HC C "Cr7   