8from gymnasium.envs.box2d
import BipedalWalker
12 def step(self, action):
13 state, reward, terminated, truncated, info = super().step(action)
14 torque = np.clip(np.abs(action), 0, 1).sum()
15 info[
"qdpy_features"] = np.array([
16 self.hull.position[0],
19 not (state[8]
or state[13]),
23 return state, reward, terminated, truncated, info
27 def __init__(self, **kwargs):
28 super().__init__(hardcore=
True, **kwargs)
32 "meanDistance",
"meanHeadStability",
"meanTorquePerStep",
"meanJump",
33 "meanLeg0HipAngle",
"meanLeg0HipSpeed",
"meanLeg0KneeAngle",
"meanLeg0KneeSpeed",
34 "meanLeg1HipAngle",
"meanLeg1HipSpeed",
"meanLeg1KneeAngle",
"meanLeg1KneeSpeed",
43def simulate(model, env, render_mode=False, num_episode=5, *, max_episode_length=3000,
44 episode_seeds=None, observation_window=None):
45 """Return mean episode reward and behaviour statistics.
47 When ``observation_window`` is set, also return a float32 matrix under
48 ``observations`` with one row per episode and state coordinate, and
49 one column per time window. Each window averages its full width,
50 including zero padding after termination or the step limit.
52 if num_episode <= 0
or max_episode_length <= 0:
53 raise ValueError(
"The episode count and step limit must be positive.")
54 if episode_seeds
is not None and len(episode_seeds) != num_episode:
55 raise ValueError(
"Supply one reset seed per episode.")
58 if observation_window
is not None:
59 if observation_window < 1:
60 raise ValueError(
"The observation window must be positive.")
61 windows = (max_episode_length + observation_window - 1) // observation_window
62 observations = np.zeros((num_episode, env.observation_space.shape[0], windows), dtype=np.float32)
65 for episode
in range(num_episode):
66 observation, _ = env.reset()
if episode_seeds
is None else env.reset(seed=episode_seeds[episode])
68 feature_sum = np.zeros(len(FEATURE_NAMES))
69 for step
in range(1, max_episode_length + 1):
70 action = model.get_action(observation)
71 observation, reward, terminated, truncated, info = env.step(action)
73 feature_sum += info[
"qdpy_features"]
74 if observations
is not None:
75 observations[episode, :, (step - 1) // observation_window] += observation
76 if terminated
or truncated:
78 rewards.append(reward_sum)
79 episode_features.append(feature_sum / step)
81 print(
"reward", reward_sum,
"timesteps", step)
84 "meanAvgReward": float(np.mean(rewards)),
85 **dict(zip(FEATURE_NAMES, np.mean(episode_features, axis=0))),
87 if observations
is not None:
88 observations /= observation_window
89 scores[
"observations"] = observations.reshape(-1, windows)
93def make_env(env_name, seed=-1, *, render_mode=None):
94 if env_name.startswith(
"BipedalWalkerHardcore"):
96 elif env_name.startswith(
"BipedalWalker"):
99 raise ValueError(f
"Unknown Walker environment: {env_name}")
107 def __init__(self, config):
108 self.
layers = list(config[
"layers"])
116 for i
in range(1, len(layers_size)):
117 fst = layers_size[i-1]
119 self.
shapes.append((fst, snd))
126 self.
weight.append(np.zeros(shape=shape))
127 self.
bias.append(np.zeros(shape=shape[1]))
130 def get_action(self, x):
131 h = np.array(x).flatten()
132 nb_layers = len(self.
weight)
133 for i
in range(nb_layers):
136 h = np.matmul(h, w) + b
140 def set_model_params(self, model_params):
142 for i
in range(len(self.
shapes)):
144 b_shape = self.
shapes[i][1]
145 s_w = math.prod(w_shape)
147 chunk = np.array(model_params[pointer:pointer+s])
148 self.
weight[i] = chunk[:s_w].reshape(w_shape)
149 self.
bias[i] = chunk[s_w:].reshape(b_shape)