Real environments: Gymnasium, MuJoCo and the engineering of the interaction loop
Build reliable reinforcement-learning environment loops with Gymnasium, vector resets, wrappers, probes and MuJoCo.
After this lesson you can
- Distinguish termination from truncation when constructing targets.
- Implement environment wrappers and handle vector autoreset modes.
- Explain MuJoCo state, control and numerical integration.
- Design custom environments and known-answer probes.
- Measure vector throughput under comparable conditions.
Before you start
- 22Markov decision processDiscounted returnAgent-environment loopTD(0)
- 00Pseudorandom generators and independent streamsComplete seeding of a training runDeterministic and sampling profilers
- 09Threads, processes and the GILExplicit and implicit Euler methodsRegion of absolute stability
- 03Stability of the explicit Euler step
The loop is also part of the agent
A network can calculate the exact formula we give it and learn the wrong target if the next observation belongs to another episode. A time cutoff, automatic reset or reward-changing wrapper are engineering decisions with mathematical consequences.
We follow the documented Gymnasium API and use the version recorded in each experiment. Vector reset names and conventions have changed between versions: record library version, environment identifier and wrappers alongside seeds. The official documentation is the reference for your installation.
An environment contract
The Gymnasium API separates initialization and transition. In an individual environment, reset(seed=semilla) returns (observación, info) and step(acción) returns (observación_siguiente, recompensa, terminated, truncated, info). After termination or truncation, reset before continuing. info may include diagnostics outside the agent’s observation.
Discrete(n) represents a finite set of integers; Box describes shape, type and bounds of a vector or matrix; MultiDiscrete combines discrete components and Dict groups named spaces. Check that observations and actions belong to their declared spaces with consistent types and shapes. Environment and action-space seeds are distinct randomness sources. To reproduce a sequence, typically seed the first reset and then allow the generator to advance; resetting repeatedly with the same seed can repeat the same episode.
In CartPole-v1 the registered limit is 500 steps; a fall can terminate earlier. Reaching the limit and falling are different causes, although flags can coincide on one transition. The target must prioritize true termination when both flags are true. See the environment specification and the registry of the version you run.
Termination and truncation
In the distinction between termination and truncation, termination belongs to the task defined by the MDP; truncation indicates collection stopped for an external condition such as a step limit. For a one-step target of a continuing task, the bootstrap mask is
If truncated but not terminated, must be the real final observation before reset. Replacing it with zero or the next episode’s first state changes the problem. In a finite horizon that is part of the task, remaining time affects the future: include it in state and treat the horizon’s end as task termination. Pardo and colleagues distinguish the two cases.
With constant reward and , continuing value is . Treating each cutoff as terminal estimates a different quantity, dependent on time remaining until that cutoff. If time is absent from the observation, the same apparent state can mix horizons. This is not exclusive to DQN: PPO and other critic-based methods also need the correct final observation.
In GAE, an implementation processing separate episodes can use and stop advantage recursion at any episode boundary, including truncation. At that boundary it retains the final-observation bootstrap when there was no true termination, but does not incorporate advantages from the new episode. The bootstrap mask and mask preventing crossing a reset serve different functions.
Wrappers change what is measured
A wrapper transforms an interface or adds state. Order matters. If RecordEpisodeStatistics must count TimeLimit cutoffs and record original reward, place the limit around the base environment, statistics around the limit and any reward transformation around statistics. The outer wrapper receives the inner result and can modify it afterward. In evaluation, document whether normalization statistics are frozen and from what data they were obtained.
Clipping actions, normalizing observations or rewards, repeating actions and preprocessing images solve different problems. Atari adds choices such as frame skip, grayscale, resizing and frame stacking; order and version form part of the protocol. Transformed reward may serve learning while untransformed return reports the task. Do not assume two scores are comparable without checking what each measures. Individual and vector wrappers have their own interfaces: check compatibility in Gymnasium documentation.
Multiple environments and three reset modes
Vectorized environments group observations, actions and results. SyncVectorEnv advances copies in one process; AsyncVectorEnv uses processes and communication, adding cost and requiring environment factories to run in child processes. More processes do not guarantee higher performance: it depends on simulation, communication and batch-processing costs.
In the currently documented autoreset API, the modes are:
- NEXT_STEP: the terminating step returns the final observation. The next call resets that copy; its action is ignored and the reset result is not a task transition.
- SAME_STEP: the terminating step already returns the new episode observation. In the documented API, retrieve the final observation from
info["final_obs"]with maskinfo["_final_obs"]; use that final observation to store the preceding transition. - DISABLED: the caller explicitly resets finished copies, for example with a reset mask supported by that version.
Earlier versions may use other names, such as final_observation; do not infer a universal key from one example. In a vector, each copy may finish at a different step: retain a per-copy mask and check the shapes of info. In the current implementation an integer seed on vector reset is expanded per copy; explicitly passing the same seed to all can generate identical trajectories in deterministic environments.
MuJoCo: model, state and physics
MuJoCo simulates mechanical systems defined with MJCF. mjModel contains compiled structure and parameters; mjData contains mutable state and quantities computed during simulation. A step applies controls, computes dynamics and constraints, and integrates state. A Gymnasium environment step can contain several physics steps: record both intervals before comparing trajectories or costs.
A joint defines degrees of freedom and limits; an actuator transforms control signals into forces according to its parameters; contacts appear when geometries interact and are resolved using MuJoCo’s constraint model. Friction, damping, contacts and controls can dissipate or supply energy. MuJoCo’s documented Euler integrator is semi-implicit; an overly large step can degrade accuracy or cause numerical problems, but energy variation alone does not prove instability.
To study energy conservation, remove actuation and dissipative forces, avoid contacts, enable energy calculation and compare integrators or steps over the same physical time. Reported energy and constraints have specific conventions: check what data.energy includes and observe warnings or automatic resets on invalid numerical states. The computation documentation and MJCF reference define these details.
Hopper, HalfCheetah, Walker2d, Ant and Humanoid have different bodies and action spaces. Their versioned identifiers can also change observations, rewards or dynamics. Report the exact identifier for any result and avoid comparing versions as if they were necessarily the same problem.
Custom environments, probes and performance
A custom environment must declare its spaces, correctly use the generator initialized by reset, respect the step contract and separate terminals from external cutoffs. check_env helps detect interface violations, but does not prove the rewards or designed problem make sense. A patch prioritization environment, for example, must specify what each action represents, how state changes and its cost or benefit, without confusing a learning simulation with an actual security assessment.
Probes are small MDPs with known answers: constant reward, observation-dependent reward, delayed discounted reward, action choice and combinations of these ideas. An agent that fails to learn these answers may have mask, index, discount or update errors even if it produces a plausible-looking curve on a large task. Fix each probe’s policy and assumptions before deriving its answer.
To measure local performance, use the same environment, version, number of copies and useful work; distinguish physical steps, vector calls and individual transitions. Measure warmup and multiple repetitions, reporting variability and process count. CPU, memory and GPU are shared, so an exact time obtained here is not an algorithm property. SyncVectorEnv, AsyncVectorEnv, systems such as EnvPool and JAX environments have different costs and requirements: a comparison applies only to the measured implementation and hardware.
Labs
The labs use Gymnasium 1.4 and installed MuJoCo. In an isolated environment you can install gymnasium[classic-control,mujoco], numpy and, for video, moviepy and imageio-ffmpeg. Mode ORYON_QUICK=1 reduces steps, workers and duration; ORYON_L13_OUT selects the output directory and ORYON_VIDEO=1 explicitly enables recording. ORYON_WORKERS selects 1 to 64 environments: default is 4 and fast mode uses at most 2. For example, 24 can be tried when the machine is available; processes have coordination costs and that count does not guarantee affinity or use of 24 physical cores. Performance depends on machine and shared load.
The custom environment represents three pending patches: its state includes the remaining decision budget because the horizon belongs to the task. An external TimeLimit can cut off before that horizon and produce truncated. The vector benchmark uses DISABLED: it retains each transition before resetting finished copies. On Windows we run the asynchronous benchmark in a child process guarded by __main__, so spawn workers do not rerun the cell.
import functools
import json
import os
from pathlib import Path
import subprocess
import sys
import tempfile
import time
import gymnasium as gym
import numpy as np
from gymnasium import spaces
from gymnasium.utils.env_checker import check_env
quick=os.environ.get('ORYON_QUICK','0')=='1'
out=Path(os.environ.get('ORYON_L13_OUT','oryon-m22-l13'))
out.mkdir(parents=True,exist_ok=True)
class PatchPriority(gym.Env):
metadata={'render_modes':[]}
def __init__(self,horizon=5):
self.horizon=horizon
self.action_space=spaces.Discrete(3)
self.observation_space=spaces.MultiDiscrete([2,2,2,horizon+1])
def reset(self,*,seed=None,options=None):
super().reset(seed=seed)
self.pending=np.ones(3,dtype=np.int64)
self.remaining=self.horizon
return self._obs(),{}
def _obs(self):
return np.array([*self.pending,self.remaining],dtype=np.int64)
def step(self,action):
if not self.action_space.contains(action): raise ValueError('Acción inválida')
value=(1.,2.,3.)[int(action)] if self.pending[action] else -.2
self.pending[action]=0; self.remaining-=1
terminated=bool(not self.pending.any() or self.remaining==0)
return self._obs(),value,terminated,False,{}
check_env(PatchPriority(),skip_render_check=True)
patch=gym.wrappers.TimeLimit(PatchPriority(),max_episode_steps=2)
obs,_=patch.reset(seed=1301)
obs,r,term,trunc,_=patch.step(0)
obs,r,term,trunc,_=patch.step(0)
assert trunc and not term and obs[-1]==3
patch.close()
print('PatchPriority: check_env correcto; corte externo distinguido del horizonte')
# TimeLimit dentro de estadísticas y normalización fuera: info registra retorno crudo.
metric_env=gym.make('CartPole-v1',max_episode_steps=10)
metric_env=gym.wrappers.RecordEpisodeStatistics(metric_env)
metric_env=gym.wrappers.NormalizeReward(metric_env)
metric_env.reset(seed=1308); metric_env.action_space.seed(1309)
normalized_total=0.0
while True:
_,reward,term,trunc,info=metric_env.step(metric_env.action_space.sample())
normalized_total+=reward
if term or trunc: break
assert 'episode' in info
print('Retorno crudo',float(info['episode']['r']),
'retorno normalizado',round(normalized_total,4),'longitud',int(info['episode']['l']))
metric_env.close()
# Las versiones y los errores de disponibilidad se dejan visibles.
print('Gymnasium',gym.__version__,'NumPy',np.__version__)
for name in ('CartPole-v1','Acrobot-v1','MountainCar-v0','Hopper-v5'):
env=None
try:
env=gym.make(name)
state,info=env.reset(seed=1302); env.action_space.seed(1303)
total=0.0; completed=0; cuts=0
for step in range(40 if quick else 2000):
state,reward,term,trunc,info=env.step(env.action_space.sample())
total+=reward
if term or trunc:
completed+=int(term); cuts+=int(trunc and not term)
state,info=env.reset()
print(name,'pasos',step+1,'retorno acumulado',round(total,3),
'terminales',completed,'cortes',cuts)
except (ImportError,gym.error.DependencyNotInstalled) as exc:
print(name,'no disponible:',type(exc).__name__,str(exc))
finally:
if env is not None: env.close()
async_program=r'''import functools,hashlib,json,multiprocessing as mp,time
import gymnasium as gym
import numpy as np
def worker(pipe,spec):
env=gym.make(spec); pending=False
try:
while True:
command,value=pipe.recv()
if command=='close': break
if command=='reset':
obs,info=env.reset(seed=value); pending=False
pipe.send((obs,info))
elif command=='step':
if pending: raise RuntimeError('Reinicia el entorno terminado antes de actuar')
result=env.step(int(value)); pending=result[2] or result[3]
pipe.send(result)
else: raise ValueError('Comando desconocido')
except EOFError:
pass
finally:
env.close(); pipe.close()
class PipeVector:
# Misma interfaz de lotes del ejercicio: no reinicia automáticamente.
def __init__(self,connections):
self.connections=list(connections); self.pending=False
def step_async(self,actions):
if self.pending: raise RuntimeError('Ya hay un lote pendiente')
actions=list(actions)
if len(actions)!=len(self.connections): raise ValueError('Número de acciones incorrecto')
for pipe,action in zip(self.connections,actions): pipe.send(('step',int(action)))
self.pending=True
def step_wait(self):
if not self.pending: raise RuntimeError('No hay lote pendiente')
result=[pipe.recv() for pipe in self.connections]
self.pending=False
return result
class PipeEnvironment:
def __init__(self,n):
self.parents=[]; self.processes=[]
self.observations=[None]*n
context=mp.get_context('spawn')
try:
for _ in range(n):
parent,child=context.Pipe()
self.parents.append(parent)
try:
process=context.Process(target=worker,args=(child,'CartPole-v1'))
process.start(); self.processes.append(process)
finally:
child.close()
except BaseException:
self.close(); raise
self.vector=PipeVector(self.parents)
def reset(self,seed=None,options=None):
mask=np.ones(len(self.parents),dtype=bool) if options is None else np.asarray(options['reset_mask'],dtype=bool)
if mask.shape!=(len(self.parents),): raise ValueError('Máscara de reset incompatible')
if self.vector.pending: raise RuntimeError('Hay un lote pendiente')
for i,pipe in enumerate(self.parents):
if mask[i]: pipe.send(('reset',None if seed is None else seed+i))
for i,pipe in enumerate(self.parents):
if mask[i]: self.observations[i]=pipe.recv()[0]
if any(obs is None for obs in self.observations): raise RuntimeError('Primero reinicia todas las copias')
return np.asarray(self.observations),{}
def step(self,actions):
self.vector.step_async(actions)
result=self.vector.step_wait()
self.observations=[x[0] for x in result]
return (np.asarray([x[0] for x in result]),np.asarray([x[1] for x in result]),
np.asarray([x[2] for x in result]),np.asarray([x[3] for x in result]),{})
def close(self):
for pipe in self.parents:
try: pipe.send(('close',None))
except (BrokenPipeError,EOFError,OSError): pass
for process in self.processes:
process.join(timeout=5)
if process.is_alive(): process.terminate(); process.join()
for pipe in self.parents: pipe.close()
def benchmark(mode,n,steps,warmup,repetitions):
startup=time.perf_counter()
if mode=='pipe': env=PipeEnvironment(n)
else:
cls=gym.vector.SyncVectorEnv if mode=='sync' else gym.vector.AsyncVectorEnv
env=cls([functools.partial(gym.make,'CartPole-v1') for _ in range(n)],
autoreset_mode=gym.vector.AutoresetMode.DISABLED)
rows=[]
try:
def advance(actions):
obs,reward,term,trunc,_=env.step(actions)
# Copia primero la transición final, antes de reiniciar cualquier copia.
transition=tuple(np.asarray(x).copy() for x in (obs,reward,term,trunc))
done=transition[2] | transition[3]
if np.any(done): env.reset(options={'reset_mask':done.copy()})
return transition
initial,_=env.reset(seed=1297)
startup_seconds=time.perf_counter()-startup
# La acción fija provoca finales y verifica también los resets parciales.
digest=hashlib.sha256(); digest.update(np.asarray(initial,dtype=np.float64).tobytes())
checked_resets=0
for _ in range(64):
obs,reward,term,trunc=advance(np.zeros(n,dtype=np.int64))
checked_resets+=int(np.count_nonzero(term | trunc))
for value,dtype in ((obs,np.float64),(reward,np.float64),(term,np.uint8),(trunc,np.uint8)):
digest.update(np.asarray(value,dtype=dtype).tobytes())
assert checked_resets>0, 'El cotejo no incluyó ningún reinicio parcial'
env.reset(seed=1299); rng=np.random.default_rng(1298)
for _ in range(warmup): advance(rng.integers(0,2,size=n))
for trial in range(repetitions):
env.reset(seed=1304+100*trial); rng=np.random.default_rng(1305+100*trial)
valid=0; start=time.perf_counter()
for _ in range(steps):
advance(rng.integers(0,2,size=n))
valid+=n
seconds=time.perf_counter()-start
rows.append({'transitions':valid,'seconds':seconds,'transitions_per_second':valid/seconds})
finally:
env.close()
rates=[row['transitions_per_second'] for row in rows]
return {'startup_seconds':startup_seconds,'trajectory_sha256':digest.hexdigest(),'checked_resets':checked_resets,
'runs':rows,'mean':float(np.mean(rates)),'std':float(np.std(rates))}
def main():
n=WORKERS; steps=STEPS; warmup=WARMUP; repetitions=REPETITIONS
result={mode:benchmark(mode,n,steps,warmup,repetitions) for mode in ('sync','async','pipe')}
counts=[[run['transitions'] for run in result[mode]['runs']] for mode in ('sync','async','pipe')]
assert counts[0]==counts[1]==counts[2], 'Los entornos no procesaron las mismas transiciones'
assert len({result[mode]['trajectory_sha256'] for mode in ('sync','async','pipe')})==1, 'Trayectorias diferentes'
print(json.dumps(result))
if __name__=='__main__': main()
'''
try: requested_workers=int(os.environ.get('ORYON_WORKERS','4'))
except ValueError as exc: raise ValueError('ORYON_WORKERS debe ser un entero entre 1 y 64') from exc
if not 1<=requested_workers<=64: raise ValueError('ORYON_WORKERS debe estar entre 1 y 64')
workers=min(2,requested_workers) if quick else requested_workers
steps=50 if quick else 2000
warmup=10 if quick else 100
repetitions=2 if quick else 5
with tempfile.TemporaryDirectory(prefix='oryon-vector-',dir=out) as tmp:
helper=Path(tmp)/'benchmark.py'
code=(async_program.replace('WORKERS',str(workers)).replace('STEPS',str(steps))
.replace('WARMUP',str(warmup)).replace('REPETITIONS',str(repetitions)))
helper.write_text(code,encoding='utf-8')
completed=subprocess.run([sys.executable,str(helper)],capture_output=True,text=True,encoding='utf-8')
if completed.returncode!=0:
raise RuntimeError('Benchmark asíncrono falló: '+completed.stderr[-2000:])
timings=json.loads(completed.stdout.strip().splitlines()[-1])
print('Benchmark DISABLED:',timings,'workers',workers,'calentamiento',warmup)
video=os.environ.get('ORYON_VIDEO','0')=='1'
if video:
env=gym.make('CartPole-v1',render_mode='rgb_array')
try:
env=gym.wrappers.RecordVideo(env,str(out/'video'),episode_trigger=lambda episode:episode==0)
state,_=env.reset(seed=1306); env.action_space.seed(1307)
while True:
state,reward,term,trunc,_=env.step(env.action_space.sample())
if term or trunc: break
finally: env.close()
print('Vídeo de CartPole guardado en',out/'video')npm run lab and open the connection link.The benchmark compares SyncVectorEnv, AsyncVectorEnv and a minimal PipeVector with the same DISABLED mode, actions and seeds per repetition. It first compares a fingerprint of observations, rewards and signals; then warms each implementation and shows individual measurements, mean and deviation. It separately measures construction and first reset, excluding startup and shutdown from sustained throughput. Each transition is copied before partial reset, whose cost is included in throughput. PipeVector uses the exercise’s batch interface; the adapter adds reset and close, but the benchmark does not automatically run the reader’s solution. Each environment and its processes close in finally; the guarded test supervises the entire process tree. Video records only with ORYON_VIDEO=1.
The output of TimeLimit can have terminated and truncated both true. For a value target, bootstrap is zero when terminated is true; on pure truncation use the transition’s final observation. In NEXT_STEP that observation appears on the terminating call; in SAME_STEP extract info['final_obs'] under mask info['_final_obs']. DISABLED requires explicit reset of finished indices.
The next five probes are small MDPs with analytical solutions. Interface check_agent receives a function returning two Q values for each identifier and observation. We separately check that environment transitions match those solutions. Such a suite detects some agent errors, but does not prove it works in every environment.
import gymnasium as gym
import numpy as np
from gymnasium import spaces
from gymnasium.utils.env_checker import check_env
class Probe(gym.Env):
metadata={'render_modes':[]}
def __init__(self,kind):
if kind not in range(5): raise ValueError('Sonda desconocida')
self.kind=kind; self.observation_space=spaces.Discrete(2); self.action_space=spaces.Discrete(2)
def reset(self,*,seed=None,options=None):
super().reset(seed=seed)
default=int(self.np_random.integers(2)) if self.kind in (1,4) else 0
self.state=int(options.get('state',default)) if options else default
if not self.observation_space.contains(self.state): raise ValueError('Estado inválido')
return self.state,{}
def step(self,action):
if not self.action_space.contains(action): raise ValueError('Acción inválida')
if self.kind==0: reward,terminated=1.0,True
elif self.kind==1: reward,terminated=(1.0 if self.state else -1.0),True
elif self.kind==2:
reward,terminated=(0.0,False) if self.state==0 else (1.0,True)
elif self.kind==3: reward,terminated=float(action),True
else: reward,terminated=float(action==self.state),True
if self.kind==2 and not terminated: self.state=1
return self.state,reward,terminated,False,{}
gamma=.9
truth={0:{0:[1.,1.]},1:{0:[-1.,-1.],1:[1.,1.]},
2:{0:[gamma,gamma],1:[1.,1.]},3:{0:[0.,1.]},
4:{0:[1.,0.],1:[0.,1.]}}
for kind,states in truth.items():
check_env(Probe(kind),skip_render_check=True)
for state,expected in states.items():
for action in range(2):
env=Probe(kind); obs,_=env.reset(seed=1310,options={'state':state})
nxt,reward,term,trunc,_=env.step(action)
continuation=0.0 if term else truth[kind][nxt][0]
assert np.isclose(reward+gamma*continuation,expected[action],atol=1e-12)
env.close()
def check_agent(predict_q,tolerance=.05):
failures=[]
for kind,states in truth.items():
for state,expected in states.items():
predicted=np.asarray(predict_q(kind,state),dtype=float)
if predicted.shape!=(2,) or not np.all(np.isfinite(predicted)) or not np.allclose(predicted,expected,atol=tolerance,rtol=0):
failures.append((kind,state))
return failures
assert not check_agent(lambda kind,state:truth[kind][state],1e-12)
assert check_agent(lambda kind,state:[0.,0.])
print('Cinco sondas verificadas; un oráculo pasa y el predictor nulo falla',
len(check_agent(lambda kind,state:[0.,0.])), 'casos')npm run lab and open the connection link.To test a trained agent, replace the oracle with a function querying its Q values after training on each probe. Declare the tolerance, and use multiple seeds for a stochastic test; the exact check above checks the probe contract and does not certify training.
The next MJCF model has two joints and two motors. To measure energy drift, controls, damping and contacts are disabled; gravity remains active. Flag energy enables kinetic and potential energy calculation. Numerical integration need not conserve exact energy: we compare differences after the same physical time with several steps. In the environment, TimeLimit is an external cutoff, not a physical goal.
import math
import os
import gymnasium as gym
import mujoco
import numpy as np
from gymnasium import spaces
from gymnasium.utils.env_checker import check_env
quick=os.environ.get('ORYON_QUICK','0')=='1'
XML='''<mujoco model="doble_pendulo">
<option timestep="0.002" gravity="0 0 -9.81" integrator="RK4">
<flag energy="enable"/>
</option>
<default>
<joint type="hinge" axis="0 1 0" damping="0"/>
<geom type="capsule" size="0.03" density="500" contype="0" conaffinity="0"/>
<motor ctrllimited="true" ctrlrange="-1 1"/>
</default>
<worldbody>
<body name="link1" pos="0 0 0">
<joint name="joint1"/>
<geom fromto="0 0 0 0 0 -0.5"/>
<body name="link2" pos="0 0 -0.5">
<joint name="joint2"/>
<geom fromto="0 0 0 0 0 -0.5"/>
</body>
</body>
</worldbody>
<actuator>
<motor name="motor1" joint="joint1"/>
<motor name="motor2" joint="joint2"/>
</actuator>
</mujoco>'''
def drift(timestep,duration):
model=mujoco.MjModel.from_xml_string(XML)
model.opt.timestep=timestep
data=mujoco.MjData(model)
data.qpos[:]=[.8,-.5]; data.qvel[:]=0; data.ctrl[:]=0
mujoco.mj_forward(model,data)
initial=float(np.sum(data.energy))
steps=round(duration/timestep)
for _ in range(steps): mujoco.mj_step(model,data)
mujoco.mj_forward(model,data)
final=float(np.sum(data.energy))
if not np.all(np.isfinite(data.qpos)) or not np.isfinite(final):
raise ArithmeticError('Estado o energía no finitos')
return initial,final,steps,float(data.time)
duration=.2 if quick else 4.0
print('MuJoCo',mujoco.__version__,'tiempo físico',duration)
for dt in (.002,.005,.01):
initial,final,steps,elapsed=drift(dt,duration)
print('dt',dt,'pasos',steps,'tiempo simulado',round(elapsed,6),
'energía inicial',round(initial,8),'final',round(final,8),
'deriva absoluta',round(final-initial,8))
class DoublePendulum(gym.Env):
metadata={'render_modes':[]}
def __init__(self):
self.model=mujoco.MjModel.from_xml_string(XML)
self.data=mujoco.MjData(self.model)
self.action_space=spaces.Box(-1.,1.,shape=(2,),dtype=np.float32)
self.observation_space=spaces.Box(-np.inf,np.inf,shape=(4,),dtype=np.float64)
def _obs(self):
return np.concatenate((self.data.qpos.copy(),self.data.qvel.copy()))
def reset(self,*,seed=None,options=None):
super().reset(seed=seed)
mujoco.mj_resetData(self.model,self.data)
self.data.qpos[:]=self.np_random.uniform(-.1,.1,size=2)
mujoco.mj_forward(self.model,self.data)
return self._obs(),{}
def step(self,action):
action=np.asarray(action,dtype=np.float32)
if not self.action_space.contains(action): raise ValueError('Acción inválida')
self.data.ctrl[:]=action
for _ in range(5): mujoco.mj_step(self.model,self.data)
obs=self._obs()
if not np.all(np.isfinite(obs)): raise ArithmeticError('Estado no finito')
reward=-float(obs[:2]@obs[:2]+.01*(obs[2:]@obs[2:])+.001*(action@action))
return obs,reward,False,False,{}
check_env(DoublePendulum(),skip_render_check=True)
env=gym.wrappers.TimeLimit(DoublePendulum(),max_episode_steps=3)
obs,_=env.reset(seed=1311)
for _ in range(3): obs,reward,term,trunc,info=env.step(np.zeros(2,dtype=np.float32))
assert not term and trunc and env.observation_space.contains(obs)
env.close()
print('Entorno validado; el límite externo se informa como truncamiento')npm run lab and open the connection link.Energy recorded by MuJoCo includes gravitational potential and kinetic energy in this model without springs or contacts. In other models mjData.energy excludes constraint energy, and actuators, dissipation and contacts can change mechanical energy. A smaller step is not a universal stability guarantee for every integrator or model. Measurements belong to the experiment, not a general law.
Exercises
import gymnasium as gym
class RemainingTime(gym.Wrapper):
pass
def start_workers(ctx, worker, specs):
pass
class PipeVector:
pass
agent_steps=10**7
frames_per_step=4
frames=agent_steps*frames_per_step
print('Fotogramas:',frames,'horas a 60 Hz:',frames/60/3600)