
    h=                        S r SSKJr  SSKJrJr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  SS	KJr  SS
KJrJrJrJrJr  SSKJrJrJr  S/r  " S S\5      r!g)zSImplementation of a synchronous (for loop) vectorization method of any environment.    )annotations)CallableIteratorSequence)deepcopy)AnyN)EnvSpace)ActTypeObsTypeRenderFrame)is_space_dtype_shape_equiv)batch_differing_spacesbatch_spaceconcatenatecreate_empty_arrayiterate)	ArrayTypeAutoresetMode	VectorEnvSyncVectorEnvc                     ^  \ rS rSrSrSS\R                  4       SU 4S jjjr\SS j5       r	\SS j5       r
SSS	.     SS
 jjr    SS jrSS jrSS jrSS jrSS jrSS jrSrU =r$ )r      aY  Vectorized environment that serially runs multiple environments.

Example:
    >>> import gymnasium as gym
    >>> envs = gym.make_vec("Pendulum-v1", num_envs=2, vectorization_mode="sync")
    >>> envs
    SyncVectorEnv(Pendulum-v1, num_envs=2)
    >>> envs = gym.vector.SyncVectorEnv([
    ...     lambda: gym.make("Pendulum-v1", g=9.81),
    ...     lambda: gym.make("Pendulum-v1", g=1.62)
    ... ])
    >>> envs
    SyncVectorEnv(num_envs=2)
    >>> obs, infos = envs.reset(seed=42)
    >>> obs
    array([[-0.14995256,  0.9886932 , -0.12224312],
           [ 0.5760367 ,  0.8174238 , -0.91244936]], dtype=float32)
    >>> infos
    {}
    >>> _ = envs.action_space.seed(42)
    >>> actions = envs.action_space.sample()
    >>> obs, rewards, terminates, truncates, infos = envs.step(actions)
    >>> obs
    array([[-0.1878752 ,  0.98219293,  0.7695615 ],
           [ 0.6102389 ,  0.79221743, -0.8498053 ]], dtype=float32)
    >>> rewards
    array([-2.96562607, -0.99902063])
    >>> terminates
    array([False, False])
    >>> truncates
    array([False, False])
    >>> infos
    {}
    >>> envs.close()
Tsamec                  > [         TU ]  5         Xl        X l        X0l        [        U[        5      (       a  UO
[        U5      U l        U Vs/ s H	  oU" 5       PM     snU l        [        U R                  5      U l
        U R                  S   R                  U l        U R                  U R                  S'   U R                  S   R                  U l        U R                  S   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  aD  U R                  S   R$                  U l        [        U R&                  U R                  5      U l        OgUS:X  aS  U R                  S   R$                  U l        [)        U R                   Vs/ s H  ofR$                  PM     sn5      U l        O[+        SU 35      eU R                   H  nUS:X  a=  UR$                  U R&                  :X  d"   SU R&                   S	UR$                   S
35       eOF[-        UR$                  U R&                  5      (       d!   SU R&                   SUR$                   35       eUR                  U R                  :X  a  M   SUR                   SU R                   35       e   [/        U R                  5       Vs/ s H  nSPM     snU l        [3        U R&                  U R                  [4        R6                  S9U l        [4        R6                  " U R                  4[4        R:                  S9U l        [4        R6                  " U R                  4[4        R>                  S9U l         [4        R6                  " U R                  4[4        R>                  S9U l!        [4        R6                  " U R                  4[4        R>                  S9U l"        gs  snf s  snf s  snf )a  Vectorized environment that serially runs multiple environments.

Args:
    env_fns: iterable of callable functions that create the environments.
    copy: If ``True``, then the :meth:`reset` and :meth:`step` methods return a copy of the observations.
    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 the same length but different high/low values batched together. Passing a ``Space`` object
        allows the user to set some custom observation space mode not covered by 'same' or 'different.'
    autoreset_mode: The Autoreset Mode used, see https://farama.org/Vector-Autoreset-Mode for more information.

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).
r   autoreset_mode      r   	differentzwInvalid `observation_mode`, expected: 'same' or 'different' or tuple of single and batch observation space, actual got zSyncVectorEnv(..., observation_mode='same') however the sub-environments observation spaces are not equivalent. single_observation_space=z$, sub-environment observation_space=zE. If this is intentional, use `observation_mode='different'` instead.zSyncVectorEnv(..., observation_mode='different' or custom space) however the sub-environments observation spaces do not share a common shape and dtype, single_observation_space=z$, sub-environment observation space=zRSub-environment action space doesn't make the `single_action_space`, action_space=z, single_action_space=N)nfndtype)#super__init__env_fnscopyobservation_mode
isinstancer   r   envslennum_envsmetadatarender_modeaction_spacesingle_action_spacer   tupler
   observation_spacesingle_observation_spacer   
ValueErrorr   range_env_obsr   npzeros_observationsfloat64_rewardsbool__terminations_truncations_autoreset_envs)	selfr&   r'   r(   r   env_fnenv_	__class__s	           Z/home/james-whalen/.local/lib/python3.13/site-packages/gymnasium/vector/sync_vector_env.pyr%   SyncVectorEnv.__init__@   s   * 		 0 .-88 ~. 	 -44G&VXG4	 DII		!--*.*=*=&'99Q<33#'99Q<#<#< '(@(@$--P&..37G3HA3M.q159999.q159999DTAD"D$A6)04		!0N0N-)4114==*& "[004		!0N0N-)?6:ii@is**i@*& ! N  O_  N`  a 
 99C6)))T-J-JJ _  `d  `}  `}  _~  ~b  cf  cx  cx  by  y~  J 2))4+H+H  b G  HL  He  He  Gf  fJ  KN  K`  K`  Ja  bb 
   D$<$<<gcdgdtdtcu  vL  MQ  Me  Me  Lf  gg<  (-T]]';<';!';</))T]]rxx
 $--!1DXXt}}&6bhhGHHdmm%5RXXF!xx(8Iq 52 A. =s   P1 P6P;c                $    U R                  S5      $ )z8Returns a tuple of np random seeds for the wrapped envs.np_random_seedget_attrr@   s    rE   rH   SyncVectorEnv.np_random_seed   s     }}-..    c                $    U R                  S5      $ )zKReturns a tuple of the numpy random number generators for the wrapped envs.	np_randomrI   rK   s    rE   rO   SyncVectorEnv.np_random   s     }}[))rM   Nseedoptionsc                  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Gbs  SU;   Gal  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SU R                  U'   SU R                  U'   SU R                  U'   0 n[!        [#        U R$                  X5      5       HC  u  nu  pxn	U	(       d  M  UR'                  XS9u  U R(                  U'   n
U R+                  XjU5      nME     O[        R,                  " U R                  4[        R                  S9U l        [        R,                  " U R                  4[        R                  S9U l        [        R,                  " U R                  4[        R                  S9U l        0 n[!        [#        U R$                  U5      5       H9  u  nu  pxUR'                  XS9u  U R(                  U'   n
U R+                  XjU5      nM;     [/        U R0                  U R(                  U R2                  5      U l        U R4                  (       a  [7        U R2                  5      U4$ U R2                  U4$ s  snf s  snf )a  Resets each of the sub-environments and concatenate the results together.

Args:
    seed: Seeds used to reset the sub-environments, either
        * ``None`` - random seeds for all environment
        * ``int`` - ``[seed, seed+1, ..., seed+n]``
        * List of ints - ``[1, 2, 3, ..., n]``
    options: Option information used for each sub-environment

Returns:
    Concatenated observations and info from each sub-environment
Nz=If seeds are passed as a list the length must match num_envs=z but got length=.
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=FrQ   r"   )r5   r,   r)   intr+   popr7   ndarraytypeshaper#   r<   anyr=   r>   r?   	enumeratezipr*   resetr6   	_add_infor8   r   r3   r9   r'   r   )r@   rR   rS   rC   irV   infosrB   single_seedenv_maskenv_infos              rE   r_   SyncVectorEnv.reset   sP   $ <"'"67"6QD"6D7Dc""&+DMM&:;&:1H&:D;I&	wJ4==/Yijmnrjsittuv	w& <7#: \2JBJJ  ^J4PZK[J\]^  ##(  mA$--PYZdZjZjYklm    BHH,cOPZP`P`Oabc,66  j\]g\hij  .3Dz*,1Dj)/4D  ,E3<DIIt04//Ch 814( 2; 2.DMM!$h !NN5A>E4 "$4==*:"((!KD "$--)9 JD#%88T]],<BHH#MD E)23tyy$3G)H%%C-0YY$ .7 .*a ( u: *I )))4==$:L:L
 04yyx**+RWWWd>P>PRWWWk 8;s   M4M9c                   [        U R                  U5      n0 n[        [        XR                  SS95       GH  u  nu  pEU R
                  [        R                  :X  a  U R                  U   (       a\  U R                  U   R                  5       u  U R                  U'   nSU R                  U'   SU R                  U'   SU R                  U'   GOU R                  U   R                  U5      u  U R                  U'   U R                  U'   U R                  U'   U R                  U'   nGOU R
                  [        R                  :X  a  U R                  U   (       a   SU R                  < 35       eU R                  U   R                  U5      u  U R                  U'   U R                  U'   U R                  U'   U R                  U'   nGOU R
                  [        R                   :X  a  U R                  U   R                  U5      u  U R                  U'   U R                  U'   U R                  U'   U R                  U'   nU R                  U   (       d  U R                  U   (       aP  U R#                  UU R                  U   US.U5      nU R                  U   R                  5       u  U R                  U'   nO[%        SU R
                   35      eU R#                  X&U5      nGM     ['        U R(                  U R                  U R*                  5      U l        [,        R.                  " U R                  U R                  5      U l        U R0                  (       a  [3        U R*                  5      OU R*                  [,        R0                  " U R                  5      [,        R0                  " U R                  5      [,        R0                  " U R                  5      U4$ )zySteps through each of the environments returning the batched results.

Returns:
    The batched environment step results
T)strictg        Fzself._autoreset_envs=)	final_obs
final_infozUnexpected autoreset mode, )r   r/   r]   r^   r*   r   r   	NEXT_STEPr?   r_   r6   r;   r=   r>   stepDISABLED	SAME_STEPr`   r4   r   r3   r9   r7   
logical_orr'   r   )r@   actionsrb   ra   actionrC   re   s          rE   rl   SyncVectorEnv.step   s7    $++W5'GYYt(LMNA{""m&=&==''*1511C1C1E.DMM!$h'*DMM!$,1D&&q)+0D%%a( 		!))&1a(a(**1-))!, $$(>(>>//2N7Lt7K7K6M4NN2 IIaL%%f-MM!$MM!$&&q)%%a($$(?(?? IIaL%%f-MM!$MM!$&&q)%%a( %%a(D,=,=a,@ NN&*mmA&6hOE 2611C1C1E.DMM!$h #>t?R?R>S!TUUNN5A6E] Nb )))4==$:L:L
  "}}T-?-?ARARS -1IIHT''(4;M;MGGDMM"GGD&&'GGD%%&
 	
rM   c                :    [        S U R                   5       5      $ )z2Returns the rendered frames from the environments.c              3  @   #    U  H  oR                  5       v   M     g 7f)N)render).0rB   s     rE   	<genexpr>'SyncVectorEnv.render.<locals>.<genexpr>:  s     7YcZZ\\Ys   )r1   r*   rK   s    rE   ru   SyncVectorEnv.render8  s    7TYY777rM   c                    / nU R                    HN  nUR                  U5      n[        U5      (       a  UR                  U" U0 UD65        M=  UR                  U5        MP     [	        U5      $ )zCalls a sub-environment method with name and applies args and kwargs.

Args:
    name: The method name
    *args: The method args
    **kwargs: The method kwargs

Returns:
    Tuple of results
)r*   get_wrapper_attrcallableappendr1   )r@   nameargskwargsresultsrB   functions          rE   callSyncVectorEnv.call<  s`     99C++D1H!!x889x(  W~rM   c                $    U R                  U5      $ )zGet a property from each parallel environment.

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

Returns:
    The property with name
)r   )r@   r~   s     rE   rJ   SyncVectorEnv.get_attrR  s     yyrM   c                h   [        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                  U5       H  u  pEUR                  X5        M     gs  snf )a  Sets an attribute of the sub-environments.

Args:
    name: The property name to change
    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.
zUValues must be a list or tuple with length equal to the number of environments. Got `z` values for z environments.N)
r)   listr1   r5   r,   r+   r4   r^   r*   set_wrapper_attr)r@   r~   valuesrC   rB   values         rE   set_attrSyncVectorEnv.set_attr]  s     &4-00&+DMM&:;&:f&:F;v;$--'F}M$--P 
 dii0JC  - 1 <s   B/c                    [        U S5      (       a*  U R                   Vs/ s H  o"R                  5       PM       nggs  snf )zClose the environments.r*   N)hasattrr*   close)r@   r   rB   s      rE   close_extrasSyncVectorEnv.close_extrasu  s1    4  $(II.ISYY[I. !.s   =)r?   r6   r9   r;   r=   r>   r/   r   r'   r&   r*   r-   r,   r(   r2   r.   r0   r3   )r&   z9Iterator[Callable[[], Env]] | Sequence[Callable[[], Env]]r'   boolr(   zstr | Spacer   zstr | AutoresetMode)returnztuple[int, ...])r   ztuple[np.random.Generator, ...])rR   zint | list[int | None] | NonerS   zdict[str, Any] | Noner   ztuple[ObsType, dict[str, Any]])rp   r   r   z?tuple[ObsType, ArrayType, ArrayType, ArrayType, dict[str, Any]])r   ztuple[RenderFrame, ...] | None)r~   strr   r   r   r   r   tuple[Any, ...])r~   r   r   r   )r~   r   r   z!list[Any] | tuple[Any, ...] | Any)r   r   )__name__
__module____qualname____firstlineno____doc__r   rk   r%   propertyrH   rO   r_   rl   ru   r   rJ   r   r   __static_attributes____classcell__)rD   s   @rE   r   r      s    "N (..;.E.EYJJYJ YJ &	YJ
 ,YJ YJv / / * * /3)-	HX ,HX '	HX
 
(HXTG
G
	HG
R8,	.0/ /rM   )"r   
__future__r   collections.abcr   r   r   r'   r   typingr   numpyr7   	gymnasiumr	   r
   gymnasium.corer   r   r   gymnasium.spaces.utilsr   gymnasium.vector.utilsr   r   r   r   r   gymnasium.vector.vector_envr   r   r   __all__r    rM   rE   <module>r      sQ    Y " 8 8      8 8 =  L K 
]/I ]/rM   