QDpy
Loading...
Searching...
No Matches
sim.py
1#!/usr/bin/env python3
2
3
4
5import math
6
7import numpy as np
8from gymnasium.envs.box2d import BipedalWalker
9
10
11class QDBipedalWalker(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],
17 abs(state[0]),
18 torque,
19 not (state[8] or state[13]),
20 *np.abs(state[4:8]),
21 *np.abs(state[9:13]),
22 ])
23 return state, reward, terminated, truncated, info
24
25
27 def __init__(self, **kwargs):
28 super().__init__(hardcore=True, **kwargs)
29
30
31FEATURE_NAMES = (
32 "meanDistance", "meanHeadStability", "meanTorquePerStep", "meanJump",
33 "meanLeg0HipAngle", "meanLeg0HipSpeed", "meanLeg0KneeAngle", "meanLeg0KneeSpeed",
34 "meanLeg1HipAngle", "meanLeg1HipSpeed", "meanLeg1KneeAngle", "meanLeg1KneeSpeed",
35)
36
37
38
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.
46
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.
51 """
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.")
56
57 observations = None
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)
63 rewards = []
64 episode_features = []
65 for episode in range(num_episode):
66 observation, _ = env.reset() if episode_seeds is None else env.reset(seed=episode_seeds[episode])
67 reward_sum = 0.0
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)
72 reward_sum += reward
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:
77 break
78 rewards.append(reward_sum)
79 episode_features.append(feature_sum / step)
80 if render_mode:
81 print("reward", reward_sum, "timesteps", step)
82
83 scores = {
84 "meanAvgReward": float(np.mean(rewards)),
85 **dict(zip(FEATURE_NAMES, np.mean(episode_features, axis=0))),
86 }
87 if observations is not None:
88 observations /= observation_window
89 scores["observations"] = observations.reshape(-1, windows)
90 return scores
91
92
93def make_env(env_name, seed=-1, *, render_mode=None):
94 if env_name.startswith("BipedalWalkerHardcore"):
95 env = QDBipedalWalkerHardcore(render_mode=render_mode)
96 elif env_name.startswith("BipedalWalker"):
97 env = QDBipedalWalker(render_mode=render_mode)
98 else:
99 raise ValueError(f"Unknown Walker environment: {env_name}")
100 if seed >= 0:
101 env.reset(seed=seed)
102 return env
103
104
105class Model:
106 ''' Simple MLP '''
107 def __init__(self, config):
108 self.layers = list(config["layers"])
109 self.input_size = config["input_size"]
110 self.output_size = config["output_size"]
111 self.init_nn()
112
113 def init_nn(self):
114 layers_size = [self.input_size] + self.layers + [self.output_size]
115 self.shapes = []
116 for i in range(1, len(layers_size)):
117 fst = layers_size[i-1]
118 snd = layers_size[i]
119 self.shapes.append((fst, snd))
120
121 self.weight = []
122 self.bias = []
123 self.param_count = 0
124
125 for shape in self.shapes:
126 self.weight.append(np.zeros(shape=shape))
127 self.bias.append(np.zeros(shape=shape[1]))
128 self.param_count += (math.prod(shape) + shape[1])
129
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):
134 w = self.weight[i]
135 b = self.bias[i]
136 h = np.matmul(h, w) + b
137 h = np.tanh(h)
138 return h
139
140 def set_model_params(self, model_params):
141 pointer = 0
142 for i in range(len(self.shapes)):
143 w_shape = self.shapes[i]
144 b_shape = self.shapes[i][1]
145 s_w = math.prod(w_shape)
146 s = s_w + b_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)
150 pointer += s
151
152
153# MODELINE "{{{1
154# vim:expandtab:softtabstop=4:shiftwidth=4:fileencoding=utf-8
155# vim:foldmethod=marker
init_nn(self)
Definition sim.py:113
list bias
Definition sim.py:122
input_size
Definition sim.py:109
output_size
Definition sim.py:110
int param_count
Definition sim.py:123
list shapes
Definition sim.py:115
list weight
Definition sim.py:121