Repository navigation
Expand file tree
/
Copy pathtasks.py
More file actions
412 lines (376 loc) · 15.7 KB
/
Copy pathtasks.py
File metadata and controls
412 lines (376 loc) · 15.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
"""Paper-era Hydrax domains, using the headless native MuJoCo simulator.
All public actions are normalized to [-1, 1]. Task state is copyable and includes
MuJoCo's time/qpos/qvel, any mocap target and solver warm start. The GPC
observation is a separate, smaller array. Planning costs use the left-endpoint
running cost at each ZOH knot plus terminal cost, as in Hydrax alg_base.py.
"""
from functools import lru_cache
import copy
import threading
import mujoco
from mujoco import rollout
import numpy as np
from assets import ensure_assets
# name in XML distribution, horizon seconds, number of knots, replanning Hz
SPECS = {
"pendulum": ("pendulum", 0.5, 5, 50),
"cart_pole": ("cart_pole", 1.0, 10, 50),
"double_cart_pole": ("double_cart_pole", 0.8, 10, 50),
"push_t": ("pusht", 0.5, 5, 50),
"walker": ("walker", 0.6, 4, 50),
"crane": ("crane", 0.8, 2, 30),
"humanoid": ("g1", 0.9, 3, 50),
}
TASK_IDS = tuple(SPECS)
PHYS = mujoco.mjtState.mjSTATE_FULLPHYSICS
MOCAP = (
mujoco.mjtState.mjSTATE_MOCAP_POS.value | mujoco.mjtState.mjSTATE_MOCAP_QUAT.value
)
@lru_cache(maxsize=None)
def _model(name):
path = ensure_assets() / name / "scene.xml"
if name == "g1":
spec = mujoco.MjSpec.from_file(str(path))
# Passive instrumentation of the same site used by the original cost.
spec.add_sensor(
name="benchmark_torso_position",
type=mujoco.mjtSensor.mjSENS_FRAMEPOS,
objtype=mujoco.mjtObj.mjOBJ_SITE,
objname="imu",
)
return spec.compile()
return mujoco.MjModel.from_xml_path(str(path))
def _squared(v):
return np.sum(np.square(v), axis=-1)
def _upright(quat):
w, x, y, z = np.moveaxis(quat, -1, 0)
return np.stack(
[2 * (x * z + w * y), 2 * (y * z - w * x), 1 - 2 * (x * x + y * y)], axis=-1
)
def _axis_angle(quat):
# Shortest rotation vector, equivalent to MJX quat_sub(quat, identity).
quat = np.where(quat[..., :1] < 0.0, -quat, quat)
v = quat[..., 1:]
length = np.linalg.norm(v, axis=-1, keepdims=True)
angle = 2 * np.arctan2(length, quat[..., :1])
return v * np.divide(
angle, length, out=np.full_like(angle, 2.0), where=length > 1.0e-12
)
class Task:
"""Deterministic full-state transition, observation and integrated planning objective."""
def __init__(self, task_id, seed=0, *, rollout_threads=2):
if rollout_threads < 1:
raise ValueError("The rollout thread count must be positive")
self.rollout_threads = rollout_threads
self.task_id = task_id
name, self.horizon, self.knots, hz = SPECS[task_id]
self.model = _model(name)
m = self.model
self.nu, self.dt, self.control_dt = m.nu, m.opt.timestep, 1.0 / hz
self.nphysics = mujoco.mj_stateSize(m, PHYS)
self.nmocap = 7 * m.nmocap
self.nx = self.nphysics + self.nmocap + m.nv
self.qslice = slice(1, 1 + m.nq)
self.vslice = slice(1 + m.nq, 1 + m.nq + m.nv)
self.seed = int(seed)
self._local = threading.local()
self._models = {self.dt: m}
self._model_lock = threading.Lock()
self.lo, self.hi = m.actuator_ctrlrange.T.copy()
self.sensors = {
m.sensor(i).name: slice(
int(m.sensor_adr[i]), int(m.sensor_adr[i] + m.sensor_dim[i])
)
for i in range(m.nsensor)
}
self.qstand = m.keyframe("stand").qpos.copy() if task_id == "humanoid" else None
def _data(self, model=None):
model = self.model if model is None else model
if not hasattr(self._local, "data"):
self._local.data = {}
if model not in self._local.data:
self._local.data[model] = mujoco.MjData(model)
return self._local.data[model]
def _snapshot(self, d):
x = np.empty(self.nx)
mujoco.mj_getState(self.model, d, x[: self.nphysics], PHYS)
if self.nmocap:
mujoco.mj_getState(
self.model, d, x[self.nphysics : self.nphysics + self.nmocap], MOCAP
)
x[-self.model.nv :] = d.qacc_warmstart
return x
def _load(self, x, model=None):
model = self.model if model is None else model
d = self._data(model)
mujoco.mj_setState(model, d, np.ascontiguousarray(x[: self.nphysics]), PHYS)
if self.nmocap:
mujoco.mj_setState(
model,
d,
np.ascontiguousarray(x[self.nphysics : self.nphysics + self.nmocap]),
MOCAP,
)
d.qacc_warmstart[:] = x[-model.nv :]
d.ctrl[:] = 0.0
return d
def _physical(self, u):
return self.lo + (0.5 * (np.clip(u, -1.0, 1.0) + 1.0)) * (self.hi - self.lo)
def reset(self, seed=None):
rng = np.random.default_rng(self.seed if seed is None else seed)
m = self.model
d = self._data()
mujoco.mj_resetData(m, d)
name = self.task_id
if name == "pendulum":
d.qpos[:] = rng.uniform(-np.pi, np.pi)
d.qvel[:] = rng.uniform(-8.0, 8.0)
elif name in ("cart_pole", "double_cart_pole"):
double = name == "double_cart_pole"
d.qpos[1:] = rng.uniform(-3.14, 3.14, m.nq - 1)
bound = 2.8 if double else 1.8
d.qpos[0] = rng.uniform(-bound, bound)
speed = 10.0 if double else 2.0
d.qvel[:] = rng.uniform(-speed, speed, m.nv)
elif name == "push_t":
limits = np.array([0.2, 0.2, np.pi, 0.2, 0.2])
d.qpos[:] = rng.uniform(-limits, limits)
d.mocap_pos[0, :2] = 0.0
d.mocap_quat[0] = [1.0, 0.0, 0.0, 0.0]
elif name == "walker":
lo, hi = m.jnt_range.T.copy()
lo[2], hi[2] = -1.5, 1.5
d.qpos[:] = rng.uniform(lo, hi)
d.qvel[:] = rng.uniform(-0.1, 0.1, m.nv)
elif name == "crane":
d.qpos[:] = m.qpos0 + rng.uniform(
[-1, 0, -1, 1, 0.3, 1, 0, 0, 0], [1, 1, 1, 2.2, 1, 1, 0, 0, 0]
)
d.qvel[:] = rng.uniform(-0.1, 0.1, m.nv)
d.mocap_pos[0] = rng.uniform([-1.5, 1.0, 0.0], [1.5, 3.0, 1.5])
d.mocap_quat[0] = [1.0, 0.0, 0.0, 0.0]
elif name == "humanoid":
d.qpos[:] = self.qstand + 0.1 * rng.normal(size=m.nq)
d.qvel[:] = 0.1 * rng.normal(size=m.nv)
u, v, w = rng.uniform(size=3)
d.qpos[3:7] = [
np.sqrt(1 - u) * np.sin(2 * np.pi * v),
np.sqrt(1 - u) * np.cos(2 * np.pi * v),
np.sqrt(u) * np.sin(2 * np.pi * w),
np.sqrt(u) * np.cos(2 * np.pi * w),
]
# Forward computes derived state without carrying acceleration from another episode.
mujoco.mj_forward(m, d)
d.qacc_warmstart[:] = 0.0
return self._snapshot(d)
def _duration_model(self, timestep):
key = round(float(timestep), 12)
with self._model_lock:
if key not in self._models:
m = copy.copy(self.model)
m.opt.timestep = timestep
self._models[key] = m
return self._models[key]
def physics_steps(self, duration):
"""Number of native integration steps used for the requested seconds."""
duration = float(duration)
if not np.isfinite(duration) or duration <= 0.0:
raise ValueError("Simulation duration must be finite and positive")
# Planning uses the source model step. Choose the closest number of
# equal substeps for off-grid durations and end at the exact elapsed time.
n = max(1, int(round(duration / self.dt)))
if self.task_id == "humanoid" and np.isclose(duration, self.control_dt):
n = 2 # Published interactive simulator uses a 0.01 s plant step.
return n
def step(self, x, u, duration=None):
duration = self.control_dt if duration is None else float(duration)
n = self.physics_steps(duration)
timestep = duration / n
m = (
self.model
if abs(timestep - self.dt) < 1.0e-12
else self._duration_model(timestep)
)
d = self._load(x, m)
d.ctrl[:] = self._physical(u)
mujoco.mj_step(m, d, nstep=n)
return self._snapshot(d)
def step_cost(self, x, u, duration=None):
t = self.control_dt if duration is None else duration
return self.step(x, u, t), t * self.cost(x, u)
def knot_durations(self, horizon):
h = int(horizon)
n = int(round(self.horizon / self.dt))
if not 1 <= h <= n:
raise ValueError(f"Choose 1 to {n} knots")
return np.diff(np.rint(np.linspace(0, n, h + 1)).astype(int)) * self.dt
def diff_state(self, x, reference):
dq = np.empty(self.model.nv)
mujoco.mj_differentiatePos(
self.model, dq, 1.0, reference[self.qslice], x[self.qslice]
)
return np.r_[dq, x[self.vslice] - reference[self.vslice]]
def _s(self, s, name):
return s[..., self.sensors[name]]
def _objective(self, q, v, s, u, terminal=False):
name = self.task_id
if name == "pendulum":
return (
2 * (1 + np.cos(q[..., 0]))
+ 0.01 * v[..., 0] ** 2
+ (0 if terminal else 0.001 * _squared(u))
)
if name == "cart_pole":
upright = 2 * (1 + np.cos(q[..., 1]))
return (
(10 if terminal else 1) * upright
+ q[..., 0] ** 2
+ 0.01 * _squared(v)
+ (0 if terminal else 0.01 * _squared(u))
)
if name == "double_cart_pole":
a, b = q[..., 1], q[..., 1] + q[..., 2]
upright = (2 + np.cos(a) + np.cos(b)) ** 2 + (np.sin(a) + np.sin(b)) ** 2
return (
10 * upright + 10 * q[..., 0] ** 2 + _squared(v)
if terminal
else upright + 0.1 * _squared(v[..., 1:]) + 0.001 * _squared(u)
)
if name == "push_t":
return (
_squared(self._s(s, "position"))
+ _squared(_axis_angle(self._s(s, "orientation")))
+ 0.01 * _squared(q[..., :2] - q[..., 3:] - [0.0, 0.1])
)
if name == "walker":
return (
10 * (self._s(s, "torso_position")[..., 2] - 1.2) ** 2
+ 3 * (self._s(s, "torso_zaxis")[..., 2] - 1.0) ** 2
+ (self._s(s, "torso_subtreelinvel")[..., 0] - 1.5) ** 2
+ (0 if terminal else 0.1 * _squared(u))
)
if name == "crane":
return _squared(self._s(s, "payload_pos")) + 0.1 * _squared(
self._s(s, "payload_vel")
)
return (
_squared(_upright(self._s(s, "imu-body-quat")))
+ 10 * (self._s(s, "benchmark_torso_position")[..., 2] - 0.9) ** 2
+ 0.1 * _squared(q[..., 7:] - self.qstand[7:])
+ (0 if terminal else 0.01 * _squared(u))
)
def _sensors(self, x):
d = self._load(x)
mujoco.mj_forward(self.model, d)
return d.sensordata.copy()
def cost(self, x, u):
return float(
self._objective(
x[self.qslice],
x[self.vslice],
self._sensors(x) if self.sensors else None,
self._physical(u),
)
)
def terminal_cost(self, x):
return float(
self._objective(
x[self.qslice],
x[self.vslice],
self._sensors(x) if self.sensors else None,
None,
True,
)
)
def observation(self, x):
q, v = x[self.qslice], x[self.vslice]
name = self.task_id
if name == "pendulum":
return np.r_[np.cos(q[0]), np.sin(q[0]), v]
if name in ("cart_pole", "double_cart_pole"):
return np.r_[
q[0], np.column_stack([np.cos(q[1:]), np.sin(q[1:])]).ravel(), v
]
if name == "walker":
return np.r_[np.cos(q[2]), np.sin(q[2]), q[0], q[3:], v]
s = self._sensors(x)
if name == "push_t":
return np.r_[q[-2:], q[:2], _axis_angle(self._s(s, "orientation"))[:1]]
if name == "crane":
return np.r_[self._s(s, "payload_pos"), self._s(s, "payload_vel"), q, v]
return np.r_[
self._s(s, "benchmark_torso_position")[2],
_upright(self._s(s, "imu-body-quat")),
q[7:],
v,
]
def _path_cost(self, initial, states):
"""Optional trajectory-wide planning cost on simulated physics states."""
return 0.0
def batch_scores(self, x, controls):
"""Score one population [K,H,nu] or independent populations [B,K,H,nu].
Batched populations start from B independent snapshots, each with its own
target and solver warm start. Results retain the leading [B,K] shape.
"""
x = np.asarray(x, dtype=np.float64)
controls = np.asarray(controls, dtype=np.float64)
if (
controls.ndim not in (3, 4)
or controls.shape[-1] != self.nu
or not all(controls.shape[:-1])
):
raise ValueError("Expected nonempty controls[K,H,nu] or controls[B,K,H,nu]")
shape = controls.shape[:-2]
if controls.ndim == 3 and x.shape == (self.nx,):
x = np.broadcast_to(x, (shape[0], self.nx))
elif controls.ndim == 4 and x.shape == (shape[0], self.nx):
x = np.repeat(x, shape[1], axis=0)
controls = controls.reshape(-1, *controls.shape[-2:])
else:
raise ValueError("Expected one initial state per population")
k, h, _ = controls.shape
t = self.knot_durations(h)
lengths = np.rint(t / self.dt).astype(int)
start = np.r_[0, np.cumsum(lengths)]
physical = self._physical(controls)
packed = np.repeat(physical, lengths, axis=1)
# A final sensor-only sample obtains freshly forward-computed terminal
# features. Its integrated state is discarded, so it adds no horizon time.
if self.sensors:
packed = np.concatenate([packed, physical[:, -1:]], axis=1)
if self.nmocap:
targets = np.broadcast_to(
x[:, None, self.nphysics : self.nphysics + self.nmocap],
(*packed.shape[:2], self.nmocap),
)
packed = np.concatenate([packed, targets], axis=-1)
if not hasattr(self._local, "batch"):
self._local.batch = rollout.Rollout(nthread=self.rollout_threads)
self._local.batch_data = [
mujoco.MjData(self.model) for _ in range(self.rollout_threads)
]
initial = np.ascontiguousarray(x[:, : self.nphysics])
warm = np.ascontiguousarray(x[:, -self.model.nv :])
states, sensors = self._local.batch.rollout(
self.model,
self._local.batch_data,
initial,
packed,
control_spec=mujoco.mjtState.mjSTATE_CTRL.value
| (MOCAP if self.nmocap else 0),
initial_warmstart=warm,
)
boundaries = np.concatenate(
[initial[:, None, :], states[:, start[1:] - 1]], axis=1
)
sb = sensors[:, start] if self.sensors else None
q, v = boundaries[..., self.qslice], boundaries[..., self.vslice]
running = self._objective(
q[:, :-1], v[:, :-1], sb[:, :-1] if self.sensors else None, physical
)
terminal = self._objective(
q[:, -1], v[:, -1], sb[:, -1] if self.sensors else None, None, True
)
# The final sensor readout is outside the simulated planning horizon.
path_cost = self._path_cost(initial, states[:, : start[-1]])
return (running @ t + terminal + path_cost).reshape(shape)